source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
50,223 | We're using Mercurial where I work and I want to have a setup similar to how I used SVN: Trunk Tags Production Branches Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'. Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial? | As the previous poster mentioned, the transplant extension can be used for cherry-picking individual changes from one branch to another. If, however, you always want to pull all the latest changes, the hg merge command will get you there. The simplest case is when you're using clones to implement branching (since that's the use case Mercurial is designed around). Assuming you've turned on the built-in fetch extension in your .hgrc / Mercurial.ini : cd ~/src/development# hack hack hackhg commit -m "Made some changes"cd ../productionhg fetch ../development If you're using local branches: hg update -C development# hack hack hackhg commit -m "Made some changes"hg update -C productionhg merge developmenthg commit -m "Merged from development" | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/956/"
]
} |
50,236 | Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control. | I recently discovered that you can use SetWindowPos to accomplish this. Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this: SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE); This changes the z-order of controls which, in turn, establishes the tab order. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
]
} |
50,255 | I've been reading a lot lately about the next release of Java possibly supporting closures . I feel like I have a pretty firm grasp on what closures are, but I can't think of a solid example of how they would make an Object-Oriented language "better". Can anyone give me a specific use-case where a closure would be needed (or even preferred)? | As a Lisp programmer I would wish that the Java community understands the following difference: functions as objects vs. closures . a) functions can be named or anonymous . But they can also be objects of themselves. This allows functions to be passed around as arguments, returned from functions or stored in data structures. This means that functions are first class objects in a programming language. Anonymous functions don't add much to the language, they just allow you to write functions in a shorter way. b) A closure is a function plus a binding environment . Closures can be passed downwards (as parameters) or returned upwards (as return values). This allows the function to refer to variables of its environment, even if the surrounding code is no longer active. If you have a) in some language, then the question comes up what to do about b) ? There are languages that have a) , but not b) . In the functional programming world a) (functions) and b (functions as closures) is nowadays the norm. Smalltalk had a) ( blocks are anonymous functions) for a long time, but then some dialects of Smalltalk added support for b) (blocks as closures). You can imagine that you get a slightly different programming model, if you add functions and closures to the language. From a pragmatic view, the anonymous function adds some short notation, where you pass or invoke functions. That can be a good thing. The closure (function plus binding) allows you for example to create a function that has access to some variables (for example to a counter value). Now you can store that function in an object, access it and invoke it. The context for the function object is now not only the objects it has access to, but also the variables it has access to via bindings. This is also useful, but you can see that variable bindings vs. access to object variables now is an issue: when should be something a lexical variable (that can be accessed in a closure) and when should it be a variable of some object (a slot ). When should something be a closure or an object? You can use both in the similar ways. A usual programming exercise for students learning Scheme (a Lisp dialect) is to write a simple object system using closures. The result is a more complicated programming language and a more complicated runtime model. Too complicated? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
]
} |
50,303 | I'm using PHP's PDO layer for data access in a project, and I've been reading up on it and seeing that it has good innate support for persistent DB connections. I'm wondering when/if I should use them. Would I see performance benefits in a CRUD-heavy app? Are there downsides to consider, perhaps related to security? If it matters to you, I'm using MySQL 5.x. | You could use this as a rough "ruleset": YES , use persistent connections, if: There are only few applications/users accessing the database, i.e. you will not result in 200 open (but probably idle) connections, because there are 200 different users shared on the same host. The database is running on another server that you are accessing over the network An (one) application accesses the database very often NO , don't use persistent connections, if: Your application only needs to access the database 100 times an hour. You have many webservers accessing one database server You're using Apache in prefork mode. It uses one connection for each child process, which can ramp up fairly quickly. (via @Powerlord in the comments) Using persistent connections is considerable faster, especially if you are accessing the database over a network. It doesn't make so much difference if the database is running on the same machine, but it is still a little bit faster. However - as the name says - the connection is persistent, i.e. it stays open, even if it is not used. The problem with that is, that in "default configuration", MySQL only allows 1000 parallel "open channels". After that, new connections are refused (You can tweak this setting). So if you have - say - 20 Webservers with each 100 Clients on them, and every one of them has just one page access per hour, simple math will show you that you'll need 2000 parallel connections to the database. That won't work. Ergo: Only use it for applications with lots of requests. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/50303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
]
} |
50,312 | I'm running some JMeter tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap. I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using ps like this: PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID` ...running the command every X seconds and appending the results to a text file. (for anyone wondering, pmem = % mem usage and nlwp is number of threads) However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, pcpu is defined as: cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. In other words, pcpu gives me the % CPU utilization for the process for the lifetime of the process. Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what top would give me(CPU utilization of the process since the last update). How can I collect this from within a shell script? | Use top -b (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
]
} |
50,316 | I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids. Edit: Someone has already asked this . Thanks Joel Coohorn. | From Mozilla's documentation <form name="form1" id="form1" method="post" autocomplete="off" action="http://www.example.com/form.cgi">[...]</form> http://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
]
} |
50,327 | I need a Datepicker for a WPF application. What is considered to be the best one? | There is also the WPF Tool Kit which has a DatePicker/Calendar control (i added emphasis because this is the answer) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013/"
]
} |
50,346 | One of my co-workers claims that even though the execution path is cached, there is no way parameterized SQL generated from an ORM is as quick as a stored procedure. Any help with this stubborn developer? | I would start by reading this article: http://decipherinfosys.wordpress.com/2007/03/27/using-stored-procedures-vs-dynamic-sql-generated-by-orm/ Here is a speed test between the two: http://www.blackwasp.co.uk/SpeedTestSqlSproc.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
]
} |
50,371 | Is there a good external merge tool for tortoisesvn (I don't particularly like the built in Merge tool). I use WinMerge for diffs, but it doesn't work with the three way merge (maybe a better question would be is there a way to force tortoisesvn to merge like tortoisecvs?) [Edit] After trying all of them, for me, the SourceGear is the one I prefer. The way to specify the DiffMerge from sourcegear is: C:\Program Files\SourceGear\DiffMerge\DiffMerge.exe /t1="My Working Version" /t2="Repository Version" /t3="Base" /r=%merged %mine %theirs %base | Perforce Merge Tool Even though Perforce is obviously not free the merge tool is. It's 100x better than the default TortoiseSvn one. To integrate with TortoiseSvn set the merge tool to: C:\Path-To\P4Merge.exe %base %theirs %mine %merged | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
]
} |
50,373 | I'm trying to mixin the MultiMap trait with a HashMap like so: val children:MultiMap[Integer, TreeNode] = new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] The definition for the MultiMap trait is: trait MultiMap[A, B] extends Map[A, Set[B]] Meaning that a MultiMap of types A & B is a Map of types A & Set[B] , or so it seems to me. However, the compiler complains: C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]] new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] ^ one error found It seems that generics are tripping me up again. | I had to import scala.collection.mutable.Set . It seems the compiler thought the Set in HashMap[Integer, Set[TreeNode]] was scala.collection.Set . The Set in the MultiMap def is scala.collection. mutable .Set . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
]
} |
50,386 | I'm currently working on putting together a fairly simple ORM tool to serve as a framework for various web projects for a client. Most of the projects are internal and will not require massive amounts of concurrency and all will go against SQL Server. I've suggested that they go with ORM tools like SubSonic, NHibernate, and a number of other open source projects out there, but for maintainability and flexibility reasons they want to create something custom. So my question is this: What are some features that I should make sure to include in this ORM tool? BTW, I'll be using MyGeneration to do the code generation templates. | For the love of all that's holy (and the women and the children), do everything possible to convince them not to go with a custom O/RM solution. Why are people wanting to re-invent the wheel when there are perfectly-good, open-source wheels already in existence?!?! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
]
} |
50,398 | Does anyone have a good solution for integrating some C# code into a java application? The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc. Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stuff in there, so I would rather keep it tightly integrated if possible. Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant. | You would use the Java Native Interface to call your C# code compiled into a DLL. If its a small amount of C#, it would be much easier to port it to Java. If its a lot, this might be a good way to do it. Here is a highlevel overview of it: http://en.wikipedia.org/wiki/Java_Native_Interface Your other option would be to create a COM assembly from the C# code and use J-Interop to invoke it. http://sourceforge.net/projects/j-interop/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5208/"
]
} |
50,417 | When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows) | From Joe Grossberg 's blog (no longer available): But if you're using GNU Emacs 21.2 (the latest version, which includes this as part of the standard distro), you can just put the following lines into your .emacs file ;; recentf stuff(require 'recentf)(recentf-mode 1)(setq recentf-max-menu-items 25)(global-set-key "\C-x\ \C-r" 'recentf-open-files) Then, when you launch emacs, hit CTRL - X CTRL - R . It will show a list of the recently-opened files in a buffer. Move the cursor to a line and press ENTER . That will open the file in question, and move it to the top of your recent-file list. (Note: Emacs records file names. Therefore, if you move or rename a file outside of Emacs, it won't automatically update the list. You'll have to open the renamed file with the normal CTRL - X CTRL - F method.) Jayakrishnan Varnam has a page including screenshots of how this package works. Note: You don't need the (require 'recentf) line. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
50,426 | I have a few controls that inherit from ASP.NET buttons and use onserverclick . If the user clicks twice, the button fires two server side events. How can I prevent this? I tried setting this.disabled='true' after the click (in the onclick attribute) via javascript, but that blocks the first postback as well. | See this example for disabling control on postback. It should help you do what you're trying to achieve. http://encosia.com/2007/04/17/disable-a-button-control-during-postback/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
]
} |
50,467 | Is there a good way to adjust the size of a UITextView to conform to its content? Say for instance I have a UITextView that contains one line of text: "Hello world" I then add another line of text: "Goodbye world" Is there a good way in Cocoa Touch to get the rect that will hold all of the lines in the text view so that I can adjust the parent view accordingly? As another example, look at the notes' field for events in the Calendar application - note how the cell (and the UITextView it contains) expands to hold all lines of text in the notes' string. | This works for both iOS 6.1 and iOS 7: - (void)textViewDidChange:(UITextView *)textView{ CGFloat fixedWidth = textView.frame.size.width; CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; CGRect newFrame = textView.frame; newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height); textView.frame = newFrame;} Or in Swift (Works with Swift 4.1 in iOS 11) let fixedWidth = textView.frame.size.widthlet newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height) If you want support for iOS 6.1 then you should also: textview.scrollEnabled = NO; | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/50467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1967/"
]
} |
50,499 | 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 execfile : script_1.py calls script_2.py . In turn, script_2.py calls script_3.py . How can I get the file name and path of script_3.py , from code within script_3.py , without having to pass that information as arguments from script_2.py ? (Executing os.getcwd() returns the original starting script's filepath not the current file's.) | p1.py: execfile("p2.py") p2.py: import inspect, osprint (inspect.getfile(inspect.currentframe())) # script filename (usually with path)print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/50499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
50,524 | From the Java 6 Pattern documentation: Special constructs (non-capturing) (?: X ) X , as a non-capturing group … (?> X ) X , as an independent, non-capturing group Between (?:X) and (?>X) what is the difference? What does the independent mean in this context? | It means that the grouping is atomic , and it throws away backtracking information for a matched group. So, this expression is possessive; it won't back off even if doing so is the only way for the regex as a whole to succeed. It's "independent" in the sense that it doesn't cooperate, via backtracking, with other elements of the regex to ensure a match. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/50524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4265/"
]
} |
50,528 | So I was reading those Windows Vista UI guidelines someone linked to in another question, and they mentioned that you should be able to survive a switch to 120 DPI. Well, I fire up my handy VM with my app installed, and what do we get... AAAAGH!!! MASSIVE UI FAIL! Everything's all jumbled: some containers aren't big enough for their text; some controls that were positioned "next to each other" are now all squished together/spread apart; some buttons aren't tall enough; my ListView columns aren't wide enough... eeek. It sounds like a completely different approach is in order. My previous one was basically using the VS2008 Windows Forms designer to create, I guess, a pixel-based layout. I can see that if I were to stick with Windows Forms, FlowLayoutPanel s would be helpful, although I've found them rather inflexible in the past. They also don't solve the problem where the containers (e.g. the form itself) aren't big enough; presumably there's a way to do that? Maybe that AutoSize property? This might also be a sign that it's time to jump ship to WPF; I'm under the impression that it's specifically designed for this kind of thing. The basic issue seems to come down to these: If I were to stick with Windows Forms, what are all the tricks to achieving a font-size-independent layout that can survive the user setting his fonts large, or setting the display to 120 DPI? Does WPF have significant advantages here, and if so, can you try to convince me that it's worth the switch? Are there any general "best-practices" for font-size-independent layouts, either in the .NET stack or in general? | Learn how the Anchor and Dock properties work on your controls, leave anything that can AutoSize itself alone, and use a TableLayoutPanel when you can. If you do these three things, you'll get a lot of the WPF design experience in Windows Forms. A well-designed TableLayoutPanel will do its best to size the controls so that they fit the form properly. Combined with AutoSize controls, docking, and the AutoScaleMode mentioned by Soeren Kuklau you should be able to make something that scales well. If not, your form might just have too many controls on it; consider splitting it into tab pages, floating toolboxes, or some other space. In WPF it's a lot easier because the concept of auto-sizing controls is built-in; in most cases if you are placing a WPF element by using a coordinate pair you are doing it wrong. Still, you can't change the fact that at lower resolutions it doesn't take much 120 dpi text to fill up the screen. Sometimes the problem is not your layout, but an attempt to put too much into a small space. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
]
} |
50,532 | How do I format a number in Java? What are the "Best Practices"? Will I need to round a number before I format it? 32.302342342342343 => 32.30 .7323 => 0.73 etc. | From this thread , there are different ways to do this: double r = 5.1234;System.out.println(r); // r is 5.1234int decimalPlaces = 2;BigDecimal bd = new BigDecimal(r);// setScale is immutablebd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);r = bd.doubleValue();System.out.println(r); // r is 5.12 f = (float) (Math.round(n*100.0f)/100.0f); DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );double dd = 100.2397;double dd2dec = new Double(df2.format(dd)).doubleValue();// The value of dd2dec will be 100.24 The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/50532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
]
} |
50,539 | One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover does anyone have any ideas or have created such a thing before we have a couple ideas but they involve to much database usage We prefer that it be FREE!!! | From this thread , there are different ways to do this: double r = 5.1234;System.out.println(r); // r is 5.1234int decimalPlaces = 2;BigDecimal bd = new BigDecimal(r);// setScale is immutablebd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);r = bd.doubleValue();System.out.println(r); // r is 5.12 f = (float) (Math.round(n*100.0f)/100.0f); DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );double dd = 100.2397;double dd2dec = new Double(df2.format(dd)).doubleValue();// The value of dd2dec will be 100.24 The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/50539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
]
} |
50,561 | Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object? | You can only tell whether the current thread holds a normal lock ( Thread.holdsLock(Object) ). You can't get a reference to the thread that has the lock without native code. However, if you're doing anything complicated with threading, you probably want to familiarize yourself with the java.util.concurrent packages. The ReentrantLock does allow you to get its owner (but its a protected method, so you'd have to extend this). Depending on your application, it may well be that by using the concurrency packages, you'll find that you don't need to get the lock's owner after all. There are non-programmatic methods to find the lock owners, such as signaling the JVM to issue a thread dump to stderr, that are useful to determine the cause of deadlocks. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220/"
]
} |
50,568 | I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them? | The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it. The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost. If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4072/"
]
} |
50,571 | I'm looking at developing a device which will need to support Ethernet over USB (hosted in Linux, XP, and Vista). As I understand it, Vista and Linux support the industry standard USB CDC. However, in classic Windows style, XP only supports it's own Remote NDIS. So, now I'm thinking of just bowing down and doing it over RNDIS, as opposed to rolling my own CDC driver for XP. I've been reading some older documentation that says even XP is pretty buggy with NDIS (suprise!). Does anyone have experience with XP's RNDIS drivers? Are they safe for product development? Any insight would be much appreciated. | The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it. The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost. If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4831/"
]
} |
50,605 | Suppose I have the following C code. unsigned int u = 1234;int i = -5678;unsigned int result = u + i; What implicit conversions are going on here, and is this code safe for all values of u and i ? (Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.) | Short Answer Your i will be converted to an unsigned integer by adding UINT_MAX + 1 , then the addition will be carried out with the unsigned values, resulting in a large result (depending on the values of u and i ). Long Answer According to the C99 Standard: 6.3.1.8 Usual arithmetic conversions If both operands have the same type, then no further conversion is needed. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank. Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type. Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type. Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type. In your case, we have one unsigned int ( u ) and signed int ( i ). Referring to (3) above, since both operands have the same rank, your i will need to be converted to an unsigned integer. 6.3.1.3 Signed and unsigned integers When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised. Now we need to refer to (2) above. Your i will be converted to an unsigned value by adding UINT_MAX + 1 . So the result will depend on how UINT_MAX is defined on your implementation. It will be large, but it will not overflow, because: 6.2.5 (9) A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. Bonus: Arithmetic Conversion Semi-WTF #include <stdio.h>int main(void){ unsigned int plus_one = 1; int minus_one = -1; if(plus_one < minus_one) printf("1 < -1"); else printf("boring"); return 0;} You can use this link to try this online: https://repl.it/repls/QuickWhimsicalBytes Bonus: Arithmetic Conversion Side Effect Arithmetic conversion rules can be used to get the value of UINT_MAX by initializing an unsigned value to -1 , ie: unsigned int umax = -1; // umax set to UINT_MAX This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information: Is it safe to use -1 to set all bits to true? | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/50605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
]
} |
50,618 | Syntax aside, what is the difference between try {}catch() {}finally { x = 3;} and try {}catch() {}x = 3; edit: in .NET 2.0? so try { throw something maybe x = 3}catch (...) { x = 3} is behaviourally equivalent? | Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception. In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will. In the .NET platform, in some cases the execution of the finally block won't occur:Security Exceptions, Thread suspensions, Computer shut down :), etc. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5278/"
]
} |
50,744 | What's the simplest way of blocking a thread until a file has been unlocked and is accessible for reading and renaming? For example, is there a WaitOnFile() somewhere in the .NET Framework? I have a service that uses a FileSystemWatcher to look for files that are to be transmitted to an FTP site, but the file created event fires before the other process has finished writing the file. The ideal solution would have a timeout period so the thread doesn't hang forever before giving up. Edit: After trying out some of the solutions below, I ended up changing the system so that all files wrote to Path.GetTempFileName() , then performed a File.Move() to the final location. As soon as the FileSystemWatcher event fired, the file was already complete. | This was the answer I gave on a related question : /// <summary> /// Blocks until the file is not locked any more. /// </summary> /// <param name="fullPath"></param> bool WaitForFile(string fullPath) { int numTries = 0; while (true) { ++numTries; try { // Attempt to open the file exclusively. using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 100)) { fs.ReadByte(); // If we got this far the file is ready break; } } catch (Exception ex) { Log.LogWarning( "WaitForFile {0} failed to get an exclusive lock: {1}", fullPath, ex.ToString()); if (numTries > 10) { Log.LogWarning( "WaitForFile {0} giving up after 10 tries", fullPath); return false; } // Wait for the lock to be released System.Threading.Thread.Sleep(500); } } Log.LogTrace("WaitForFile {0} returning true after {1} tries", fullPath, numTries); return true; } | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/50744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
]
} |
50,794 | How does unix handle full path name with space and arguments ? In windows we quote the path and add the command-line arguments after, how is it in unix? "c:\foo folder with space\foo.exe" -help update: I meant how do I recognize a path from the command line arguments. | You can either quote it like your Windows example above, or escape the spaces with backslashes: "/foo folder with space/foo" --help /foo\ folder\ with\ space/foo --help | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
]
} |
50,801 | How would you find the fractional part of a floating point number in PHP? For example, if I have the value 1.25 , I want to return 0.25 . | $x = $x - floor($x) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/50801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4925/"
]
} |
50,824 | I wrote a simple tool to generate a DBUnit XML dataset using queries that the user enters. I want to include each query entered in the XML as a comment, but the DBUnit API to generate the XML file doesn't support inserting the comment where I would like it (above the data it generates), so I am resorting to putting the comment with ALL queries either at the top or bottom. So my question: is it valid XML to place it at either location? For example, above the XML Declaration: <!-- Queries used: ... --><?xml version='1.0' encoding='UTF-8'?><dataset> ...</dataset> Or below the root node: <?xml version='1.0' encoding='UTF-8'?><dataset> ...</dataset><!-- Queries used: ... --> I plan to initially try above the XML Declaration, but I have doubts on if that is valid XML, despite the claim from wikipedia : Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA. I plan to post back if this works, but it would be nice to know if it is an official XML standard. UPDATE: See my response below for the result of my test. | According to the XML specification , a well-formed XML document is: document ::= prolog element Misc* where prolog is prolog ::= XMLDecl? Misc* (doctypedecl Misc*)? and Misc is Misc ::= Comment | PI | S and XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' which means that, if you want to have comments at the top, you cannot have an XML type declaration. You can, however, have comments after the declaration and outside the document element, either at the top or the bottom of the document, because Misc* can contain comments. The specification agrees with Wikipedia on comments: 2.5 Comments [Definition: Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor MAY, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity references MUST NOT be recognized within comments. All of this together means that you can put comments anywhere that's not inside other markup , except that you cannot have an XML declaration if you lead with a comment . However, while in theory theory agrees with practice, in practice it doesn't, so I'd be curious to see how your experiment works out. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
} |
50,900 | So I have about 10 short css files that I use with mvc app.There are likeerror.csslogin.cssetc...Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this if(Debug.Mode){<link rel="stylesheet" type="text/css" href="error.css" /> <link rel="stylesheet" type="text/css" href="login.css" /> <link rel="stylesheet" type="text/css" href="menu.css" /> <link rel="stylesheet" type="text/css" href="page.css" /> } else {<link rel="stylesheet" type="text/css" href="site.css" /> } I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits. | Specifically, like this in C#: #if (DEBUG) Debug Stuff#endif C# has the following preprocessor directives: #if #else #elif // Else If#endif#define#undef // Undefine#warning // Causes the preprocessor to fire warning#error // Causes the preprocessor to fire a fatal error#line // Lets the preprocessor know where this source line came from#region // Codefolding#endregion | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438/"
]
} |
50,945 | If I had 20 directories under trunk/ with lots of files in each and only needed 3 of those directories, would it be possible to do a Subversion checkout with only those 3 directories under trunk? | Indeed, thanks to the comments to my post here, it looks like sparse directories are the way to go. I believe the following should do it: svn checkout --depth empty http://svnserver/trunk/projsvn update --set-depth infinity proj/foosvn update --set-depth infinity proj/barsvn update --set-depth infinity proj/baz Alternatively, --depth immediates instead of empty checks out files and directories in trunk/proj without their contents. That way you can see which directories exist in the repository. As mentioned in @zigdon's answer, you can also do a non-recursive checkout. This is an older and less flexible way to achieve a similar effect: svn checkout --non-recursive http://svnserver/trunk/projsvn update trunk/foosvn update trunk/barsvn update trunk/baz | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/50945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
50,965 | So, to simplify my life I want to be able to append from 1 to 7 additional characters on the end of some jpg images my program is processing*. These are dummy padding (fillers, etc - probably all 0x00) just to make the file size a multiple of 8 bytes for block encryption. Having tried this out with a few programs, it appears they are fine with the additional characters, which occur after the FF D9 that specifies the end of the image - so it appears that the file format is well defined enough that the 'corruption' I'm adding at the end shouldn't matter. I can always post process the files later if needed, but my preference is to do the simplest thing possible - which is to let them remain (I'm decrypting other file types and they won't mind, so having a special case is annoying). I figure with all the talk of Steganography hullaballo years ago, someone has some input here... (encryption processing by 8 byte blocks, I don't want to save pre-encrypted file size, so append 0x00 to input data, and leave them there after decoding) | No, you can add bits to the end of a jpg file, without making it unusable. The heading of the jpg file tells how to read it, so the program reading it will stop at the end of the jpg data. In fact, people have hidden zip files inside jpg files by appending the zip data to the end of the jpg data. Because of the way these formats are structured, the resulting file is valid in either format. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/50965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
]
} |
50,983 | I liked the discussion at Differences in Generics , and was wondering whether there were any languages that used this feature particularly well. I really dislike Java's List<? extends Foo> for a List of things that are Liskov-substitutable for Foo . Why can't List<Foo> cover that? And honestly, Comparable<? super Bar> ? I also can't remember for the life of my why you should never return an Array of generics: public T[] getAll<T>() { ... } I never liked templates in C++, but that was mostly because none of the compilers could ever spit out a remotely meaningful error message for them. One time I actually did a make realclean && make 17 times to get something to compile; I never did figure out why the 17th time was the charm. So, who actually likes using generics in their pet language? | Haskell implements type-constructor parameterisation (generics, or parametric polymorphism) quite well. So does Scala (although it needs a bit of hand-holding sometimes). Both of these languages have higher-kinded types (a.k.a. abstract type constructors, or type-constructor polymorphism, or higher-order polymorphism). See here: Generics of a Higher Kind | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/50983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
]
} |
51,007 | One of the things I miss the most in ActionScript is the lack of operator overloading, in particular ==. I kind of work around this issue by adding a "Compare" method to my classes, but that doesn't help in many cases, like when you want to use things like the built in Dictionary. Is there a good way to work around this problem? | Nope. But it doesn't hurt to add equals methods to your own classes. I try to never use == when comparing objects (the same goes for === , which is the same thing for objects) since it only checks identity . Sadly all the collections in Flash and Flex assume that identity is the only measure of equality that is needed. There are hints in Flex that someone wanted to alleviate this problem at one time, but it seems like it was abandoned: there is an interface called IUID , and it is mentioned in the Flex Developer's Guide , but it is not used anywhere. Not even the collections in Flex use it to determine equality. And since you are asking for a solution for Flash, it may not have helped you anyway. I've written some more about this (in the context of Flex) on my blog: Is there no equality? . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815/"
]
} |
51,019 | What does it mean when a PostgreSQL process is "idle in transaction"? On a server that I'm looking at, the output of "ps ax | grep postgres" I see 9 PostgreSQL processes that look like the following: postgres: user db 127.0.0.1(55658) idle in transaction Does this mean that some of the processes are hung, waiting for a transaction to be committed? Any pointers to relevant documentation are appreciated. | The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too. If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/51019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
51,021 | Ruby has two different exceptions mechanisms: Throw/Catch and Raise/Rescue. Why do we have two? When should you use one and not the other? | I think http://hasno.info/ruby-gotchas-and-caveats has a decent explanation of the difference: catch/throw are not the same as raise/rescue. catch/throw allows you to quickly exit blocks back to a point where a catch is defined for a specific symbol, raise rescue is the real exception handling stuff involving the Exception object. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/51021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653/"
]
} |
51,032 | Consider these two function definitions: void foo() { }void foo(void) { } Is there any difference between these two? If not, why is the void argument there? Aesthetic reasons? | In C : void foo() means "a function foo taking an unspecified number of arguments of unspecified type" void foo(void) means "a function foo taking no arguments" In C++ : void foo() means "a function foo taking no arguments" void foo(void) means "a function foo taking no arguments" By writing foo(void) , therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an extern "C" if we're compiling C++). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/51032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
]
} |
51,050 | I'm not a usability specialist, and I really don't care to be one. I just want a small set of rules of thumb that I can follow while coding my user interfaces so that my product has decent usability. At first I thought that this question would be easy to answer "Use your common sense", but if it's so common among us developers we wouldn't, as a group, have a reputation for our horrible interfaces. Any suggestions? | Source: http://stuffthathappens.com/blog/wp-content/uploads/2008/03/simplicity.png | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
} |
51,054 | I am looking for a way to delete all files older than 7 days in a batch file. I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task. Similar things can be done in BASH in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either. | Enjoy: forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path" See forfiles documentation for more details. For more goodies, refer to An A-Z Index of the Windows XP command line . If you don't have forfiles installed on your machine, copy it from any Windows Server 2003 to your Windows XP machine at %WinDir%\system32\ . This is possible since the EXE is fully compatible between Windows Server 2003 and Windows XP. Later versions of Windows and Windows Server have it installed by default. For Windows 7 and newer (including Windows 10): The syntax has changed a little. Therefore the updated command is: forfiles /p "C:\what\ever" /s /m *.* /D -<number of days> /C "cmd /c del @path" | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/51054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
]
} |
51,094 | This question talks about different payment processors and what they cost, but I'm looking for the answer to what do I need to do if I want to accept credit card payments? Assume I need to store credit card numbers for customers, so that the obvious solution of relying on the credit card processor to do the heavy lifting is not available. PCI Data Security , which is apparently the standard for storing credit card info, has a bunch of general requirements, but how does one implement them ? And what about the vendors, like Visa , who have their own best practices? Do I need to have keyfob access to the machine? What about physically protecting it from hackers in the building? Or even what if someone got their hands on the backup files with the sql server data files on it? What about backups? Are there other physical copies of that data around? Tip: If you get a merchant account, you should negotiate that they charge you "interchange-plus" instead of tiered pricing. With tiered pricing, they will charge you different rates based on what type of Visa/MC is used -- ie. they charge you more for cards with big rewards attached to them. Interchange plus billing means you only pay the processor what Visa/MC charges them, plus a flat fee. (Amex and Discover charge their own rates directly to merchants, so this doesn't apply to those cards. You'll find Amex rates to be in the 3% range and Discover could be as low as 1%. Visa/MC is in the 2% range). This service is supposed to do the negotiation for you (I haven't used it, this is not an ad, and I'm not affiliated with the website, but this service is greatly needed.) This blog post gives a complete rundown of handling credit cards (specifically for the UK). Perhaps I phrased the question wrong, but I'm looking for tips like these: Use SecurID or eToken to add an additional password layer to the physical box. Make sure the box is in a room with a physical lock or keycode combination. | I went through this process not to long ago with a company I worked for and I plan on going through it again soon with my own business. If you have some network technical knowledge, it really isn't that bad. Otherwise you will be better off using Paypal or another type of service. The process starts by getting a merchant account setup and tied to your bank account. You may want to check with your bank, because a lot of major banks provide merchant services. You may be able to get deals, because you are already a customer of theirs, but if not, then you can shop around. If you plan on accepting Discover or American Express, those will be separate, because they provide the merchant services for their cards, no getting around this. There are other special cases also. This is an application process, be prepared. Next you will want to purchase an SSL certificate that you can use for securing your communications for when the credit card info is transmitted over public networks. There are plenty of vendors, but my rule of thumb is to pick one that is a brand name in a way. The better they are known, the better your customer has probably heard of them. Next you will want to find a payment gateway to use with your site. Although this can be optional depending on how big you are, but majority of the time it won't be. You will need one. The payment gateway vendors provide a way to talk to the Internet Gateway API that you will communicate with. Most vendors provide HTTP or TCP/IP communication with their API. They will process the credit card information on your behalf. Two vendors are Authorize.Net and PayFlow Pro . The link I provide below has some more information on other vendors. Now what? For starters there are guidelines on what your application has to adhere to for transmitting the transactions. During the process of getting everything setup, someone will look at your site or application and make sure you are adhering to the guidelines, like using SSL and that you have terms of use and policy documentation on what the information the user is giving you is used for. Don't steal this from another site. Come up with your own, hire a lawyer if you need to. Most of these things fall under the PCI Data Security link Michael provided in his question. If you plan on storing the credit card numbers, then you better be prepared to put some security measures in place internally to protect the info. Make sure the server the information is stored on is only accessible to members who need to have access. Like any good security, you do things in layers. The more layers you put in place the better. If you want you can use key fob type security, like SecureID or eToken to protect the room the server is in. If you can't afford the key fob route, then use the two key method. Allow a person who has access to the room to sign out a key, which goes along with a key they already carry. They will need both keys to access the room. Next you protect the communication to the server with policies. My policy is that the only thing communicating to it over the network is the application and that information is encrypted. The server should not be accessible in any other form. For backups, I use truecrypt to encrypt the volumes the backups will be saved to. Anytime the data is removed or stored somewhere else, then again you use truecrypt to encrypt the volume the data is on. Basically where ever the data is, it needs to be encrypted. Make sure all processes for getting at the data carries auditing trails. use logs for access to the server room, use cameras if you can, etc... Another measure is to encrypt the credit card information in the database. This makes sure that the data can only be viewed in your application where you can enforce who sees the information. I use pfsense for my firewall. I run it off a compact flash card and have two servers setup. One is for fail over for redundancy. I found this blog post by Rick Strahl which helped tremendously to understand doing e-commerce and what it takes to accept credit cards through a web application. Well, this turned out to be a long answer. I hope these tips help. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/51094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245/"
]
} |
51,113 | It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.) So how do you tell if it has no records without just wrapping it in a try/catch? | if(dr.Read()){ //do stuff}else{ //it's empty} usually you'll do this though: while(dr.Read()){} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
]
} |
51,148 | I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it. So how in C# would I so this in the example below? using System.Diagnostics;...Process foo = new Process();foo.StartInfo.FileName = @"C:\bar\foo.exe";foo.StartInfo.Arguments = "Username Password";bool isRunning = //TODO: Check to see if process foo.exe is already runningif (isRunning){ //TODO: Switch to foo.exe process}else{ foo.Start(); } | This should do it for ya. Check Processes //Namespaces we need to useusing System.Diagnostics;public bool IsProcessOpen(string name){ //here we're going to get a list of all running processes on //the computer foreach (Process clsProcess in Process.GetProcesses()) { //now we're going to see if any of the running processes //match the currently running processes. Be sure to not //add the .exe to the name you provide, i.e: NOTEPAD, //not NOTEPAD.EXE or false is always returned even if //notepad is running. //Remember, if you have the process running more than once, //say IE open 4 times the loop thr way it is now will close all 4, //if you want it to just close the first one it finds //then add a return; after the Kill if (clsProcess.ProcessName.Contains(name)) { //if the process is found to be running then we //return a true return true; } } //otherwise we return a false return false;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1292/"
]
} |
51,156 | Say I have a list as follows: item1 item2 item3 Is there a CSS selector that will allow me to directly select the last item of a list? In this case item 3. Cheers! | Not that i'm aware of. The traditional solution is to tag the first & last items with class="first" & class="last" so you can identify them. The CSS psudo-class first-child will get you the first item but not all browsers support it. CSS3 will have last-child too (this is currently supported by Firefox, Safari but not IE 6/7/beta 8) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131/"
]
} |
51,165 | I have a list of objects I wish to sort based on a field attr of type string. I tried using - list.sort(function (a, b) { return a.attr - b.attr}) but found that - doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string? | Use String.prototype.localeCompare a per your example: list.sort(function (a, b) { return ('' + a.attr).localeCompare(b.attr);}) We force a.attr to be a string to avoid exceptions. localeCompare has been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn't respect a locale: if (item1.attr < item2.attr) return -1;if ( item1.attr > item2.attr) return 1;return 0; | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/51165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
]
} |
51,180 | I'm tearing my hair out with this one. If I start a block comment /* in VS.NET 2005+ then carriage return, Visual Studio insists that I have another asterisk * . I know there's an option to turn this off but I just can't find it. Anyone know how to turn this feature off? | Update: this setting was changed in VS 2015 update 2. See this answer . This post addresses your question. The gist of it is: Text Editor > C# > Advanced > Generate XML documentation comments for /// | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4458/"
]
} |
51,185 | Does javascript use immutable or mutable strings? Do I need a "string builder"? | They are immutable. You cannot change a character within a string with something like var myString = "abbdef"; myString[2] = 'c' . The string manipulation methods such as trim , slice return new strings. In the same way, if you have two references to the same string, modifying one doesn't affect the other let a = b = "hello";a = a + " world";// b is not affected However, I've always heard what Ash mentioned in his answer (that using Array.join is faster for concatenation) so I wanted to test out the different methods of concatenating strings and abstracting the fastest way into a StringBuilder. I wrote some tests to see if this is true (it isn't!). This was what I believed would be the fastest way, though I kept thinking that adding a method call may make it slower... function StringBuilder() { this._array = []; this._index = 0;}StringBuilder.prototype.append = function (str) { this._array[this._index] = str; this._index++;}StringBuilder.prototype.toString = function () { return this._array.join('');} Here are performance speed tests. All three of them create a gigantic string made up of concatenating "Hello diggity dog" one hundred thousand times into an empty string. I've created three types of tests Using Array.push and Array.join Using Array indexing to avoid Array.push , then using Array.join Straight string concatenation Then I created the same three tests by abstracting them into StringBuilderConcat , StringBuilderArrayPush and StringBuilderArrayIndex http://jsperf.com/string-concat-without-sringbuilder/5 Please go there and run tests so we can get a nice sample. Note that I fixed a small bug, so the data for the tests got wiped, I will update the table once there's enough performance data. Go to http://jsperf.com/string-concat-without-sringbuilder/5 for the old data table. Here are some numbers (Latest update in Ma5rch 2018), if you don't want to follow the link. The number on each test is in 1000 operations/second ( higher is better ) Browser Index Push Concat SBIndex SBPush SBConcat Chrome 71.0.3578 988 1006 2902 963 1008 2902 Firefox 65 1979 1902 2197 1917 1873 1953 Edge 593 373 952 361 415 444 Exploder 11 655 532 761 537 567 387 Opera 58.0.3135 1135 1200 4357 1137 1188 4294 Findings Nowadays, all evergreen browsers handle string concatenation well. Array.join only helps IE 11 Overall, Opera is fastest, 4 times as fast as Array.join Firefox is second and Array.join is only slightly slower in FF but considerably slower (3x) in Chrome. Chrome is third but string concat is 3 times faster than Array.join Creating a StringBuilder seems to not affect perfomance too much. Hope somebody else finds this useful Different Test Case Since @RoyTinker thought that my test was flawed, I created a new case that doesn't create a big string by concatenating the same string, it uses a different character for each iteration. String concatenation still seemed faster or just as fast. Let's get those tests running. I suggest everybody should keep thinking of other ways to test this, and feel free to add new links to different test cases below. http://jsperf.com/string-concat-without-sringbuilder/7 | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/51185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
]
} |
51,195 | I want to write a little "DBQuery" function in perl so I can have one-liners which send an SQL statement and receive back and an array of hashes, i.e. a recordset. However, I'm running into an issue with Perl syntax (and probably some odd pointer/reference issue) which is preventing me from packing out the information from the hash that I'm getting from the database. The sample code below demonstrates the issue. I can get the data "Jim" out of a hash inside an array with this syntax: print $records[$index]{'firstName'} returns "Jim" but if I copy the hash record in the array to its own hash variable first, then I strangely can't access the data anymore in that hash: %row = $records[$index]; $row{'firstName'}; returns "" (blank) Here is the full sample code showing the problem. Any help is appreciated: my @records = ( {'id' => 1, 'firstName' => 'Jim'}, {'id' => 2, 'firstName' => 'Joe'});my @records2 = ();$numberOfRecords = scalar(@records);print "number of records: " . $numberOfRecords . "\n";for(my $index=0; $index < $numberOfRecords; $index++) { #works print 'you can print the records like this: ' . $records[$index]{'firstName'} . "\n"; #does NOT work %row = $records[$index]; print 'but not like this: ' . $row{'firstName'} . "\n";} | The nested data structure contains a hash reference , not a hash. # Will work (the -> dereferences the reference)$row = $records[$index];print "This will work: ", $row->{firstName}, "\n";# This will also work, by promoting the hash reference into a hash%row = %{ $records[$index] };print "This will work: ", $row{firstName}, "\n"; If you're ever presented with a deep Perl data structure, you may profit from printing it using Data::Dumper to print it into human-readable (and Perl-parsable) form. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
} |
51,212 | I am writing a little application to download files over http (as, for example, described here ). I also want to include a little download progress indicator showing the percentage of the download progress. Here is what I came up with: sys.stdout.write(rem_file + "...") urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("%2d%%" % percent) sys.stdout.write("\b\b\b") sys.stdout.flush() Output: MyFileName... 9% Any other ideas or recommendations to do this? One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor? EDIT: Here a better alternative using a global variable for the filename in dlProgress and the '\r' code: global rem_file # global variable to be used in dlProgress urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("\r" + rem_file + "...%d%%" % percent) sys.stdout.flush() Output: MyFileName...9% And the cursor shows up at the END of the line. Much better. | There's a text progress bar library for python at http://pypi.python.org/pypi/progressbar/2.2 that you might find useful: This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386/"
]
} |
51,224 | I'm trying to write a regular expression that validates a date. The regex needs to match the following M/D/YYYY MM/DD/YYYY Single digit months can start with a leading zero (eg: 03/12/2008) Single digit days can start with a leading zero (eg: 3/02/2008) CANNOT include February 30 or February 31 (eg: 2/31/2008) So far I have ^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$ This matches properly EXCEPT it still includes 2/30/2008 & 2/31/2008. Does anyone have a better suggestion? Edit: I found the answer on RegExLib ^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$ It matches all valid months that follow the MM/DD/YYYY format. Thanks everyone for the help. | This is not an appropriate use of regular expressions. You'd be better off using [0-9]{2}/[0-9]{2}/[0-9]{4} and then checking ranges in a higher-level language. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/51224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3742/"
]
} |
51,233 | How can I retrieve the page title of a webpage (title html tag) using Python? | I'll always use lxml for such tasks. You could use beautifulsoup as well. import lxml.htmlt = lxml.html.parse(url)print(t.find(".//title").text) EDIT based on comment: from urllib2 import urlopenfrom lxml.html import parseurl = "https://www.google.com"page = urlopen(url)p = parse(page)print(p.find(".//title").text) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/51233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386/"
]
} |
51,269 | I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class public class UserInfo{ [Category("change me!")] public int Age { get; set; } [Category("change me!")] public string Name { get; set; }} This is a class that is provided by a third party vendor and I can't change the code . But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid. May I know how to do this? | Well you learn something new every day, apparently I lied: What isn’t generally realised is that you can change attribute instance values fairly easily at runtime. The reason is, of course, that the instances of the attribute classes that are created are perfectly normal objects and can be used without restriction. For example, we can get the object: ASCII[] attrs1=(ASCII[]) typeof(MyClass).GetCustomAttributes(typeof(ASCII), false); …change the value of its public variable and show that it has changed: attrs1[0].MyData="A New String";MessageBox.Show(attrs1[0].MyData); …and finally create another instance and show that its value is unchanged: ASCII[] attrs3=(ASCII[]) typeof(MyClass).GetCustomAttributes(typeof(ASCII), false); MessageBox.Show(attrs3[0].MyData); http://www.vsj.co.uk/articles/display.asp?id=713 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
} |
51,283 | How do you get around this Ajax cross site scripting problem on FireFox 3? | If you're using jQuery it has a callback function to overcome this: http://docs.jquery.com/Ajax/jQuery.ajax#options As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will be automatically added to your Ajax request. Alternatively you could make your ajax request to a server-side script which does the cross-domain call for you, then passes the data back to your script | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5321/"
]
} |
51,311 | I am about to start a new project and would like to document its development in a very simple blog. My requirements are: self-hosted on my Gentoo-based LAMP stack (that seems to rule out blogger) Integration in a django based website (as in www.myproject.com/about, www.myproject.com/blog etc rather than www.myproject.com and a totally different site at blog.myproject.com) very little or no learning curve that's specific to the blog engine (don't want to learn an API just to blog, but having to get deeper into Django to be able to roll my own would be OK) According to the answers so far, there is a chance that this excludes Wordpress Should I a) install blog engine X (please specify X) b) use django to hand-roll a way to post new entries and a page on my website to display the posts in descending chronological order | If you're the perfectionist kind, roll your own . It isn't that hard You learn something useful You'll get exactly what you want and need Be warned that you may run into a quagmire fighting comment spam, fixing security holes, etc. But it'll probably be a fun project. If you are the practical type and ready to face some integration pain , use an existing engine like WadcomBlog (Python) or PyBlosxom , or something completely different like MovableType or WordPress. Here's a simple Django blog example to get you started. Some pros and cons of rolling your blog engine this article by Phil Haack. Jeff Croft apparently rolled his own as well. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
} |
51,320 | For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows. I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it). Any help? EDIT: I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically. | http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots() File[] roots = File.listRoots();for(int i = 0; i < roots.length ; i++) System.out.println("Root["+i+"]:" + roots[i]); google: list drives java, first hit:-) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018/"
]
} |
51,339 | I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL: SELECT f.* FROM Foo fWHERE f.FooId IN ( SELECT fb.FooId FROM FooBar fb WHERE fb.BarId = 1000) Any help would be gratefully received. | Have a look at this article . Basically, if you want to get the equivalent of IN, you need to construct an inner query first, and then use the Contains() method. Here's my attempt at translating: var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId;var result = from f in Foo where innerQuery.Contains(f.FooId) select f; | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/51339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1904/"
]
} |
51,352 | I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page. What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this. I've been doing this via JavaScript, which works so far, using the following code document.getElementById('chart').src = '/charts/10.png'; The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond. What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it. I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image. A good suggestion I've had is to use the following <img src="/charts/10.png" lowsrc="/spinner.gif"/> Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed. Any other ideas? | I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback. function PreloadImage(imgSrc, callback){ var objImagePreloader = new Image(); objImagePreloader.src = imgSrc; if(objImagePreloader.complete){ callback(); objImagePreloader.onload=function(){}; } else{ objImagePreloader.onload = function() { callback(); // clear onLoad, IE behaves irratically with animated gifs otherwise objImagePreloader.onload=function(){}; } }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3847/"
]
} |
51,363 | I've encountered multiple third party .Net component-vendors that use a licensing scheme. On an evaluation copy, the components show up with a nag-screen or watermark or some such indicator. On a licensed machine, a Licenses.licx is created - with what appears to be just the assembly full name/identifiers. This file has to be included when the client assembly is built. How does this model work? Both from component-vendors' and users' perspective. What is the .licx file used for? Should it be checked in? We've had a number of issues with the wrong/right .licx file being checked in and what not | Almost everything about .Net licensing is explained here . No need to rewrite, I think. It is better to exclude license files from project in source control, if you can. Otherwise, editing visual components may be pain in the ass. Also, storing license files in source control repository is not a need. Hope this helps. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
]
} |
51,390 | When java was young, people were excited about writing applets. They were cool and popular, for a little while. Now, I never see them anymore. Instead we have flash, javascript, and a plethora of other web app-building technologies. Why don't sites use java applets anymore? I'm also curious: historically, why do you think this occurred? What could have been done differently to keep Java applets alive? | I think Java applets were overshadowed by Flash and ActionScript (pun unintended), being much easier to use for what Java Applets were being used at the time (animations + stateful applications). Flash's success in this respect in turn owes to its much smaller file sizes, as well as benefiting from the Sun vs. Microsoft suit that resulted in Microsoft removing the MSJVM from Internet Explorer, at a time of Netscape's demise and IE's heavy dominance. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3561/"
]
} |
51,412 | Say I have the following methods: def methodA(arg, **kwargs): passdef methodB(arg, *args, **kwargs): pass In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define methodA as follows, the second argument will be passed on as positional rather than named variable arguments. def methodA(arg, **kwargs): methodB("argvalue", kwargs) How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB? | Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments. methodB("argvalue", **kwargs) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
]
} |
51,438 | How do you get a Media Type (MIME type) from a file using Java? So far I've tried JMimeMagic & Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly. How would you probe the file to determine its actual type (not merely based on the extension)? | In Java 7 you can now just use Files.probeContentType(path) . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/51438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1900/"
]
} |
51,470 | In PostgreSQL , I can do something like this: ALTER SEQUENCE serial RESTART WITH 0; Is there an Oracle equivalent? | Here is a good procedure for resetting any sequence to 0 from Oracle guru Tom Kyte . Great discussion on the pros and cons in the links below too. [email protected]> create or replaceprocedure reset_seq( p_seq_name in varchar2 )is l_val number;begin execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by -' || l_val || ' minvalue 0'; execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';end;/ From this page: Dynamic SQL to reset sequence value Another good discussion is also here: How to reset sequences? | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/51470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917/"
]
} |
51,492 | For me usable means that: it's being used in real-wold it has tools support. (at least some simple editor) it has human readable syntax (no angle brackets please) Also I want it to be as close to XML as possible, i.e. there must be support for attributes as well as for properties. So, no YAML please. Currently, only one matching language comes to my mind - JSON . Do you know any other alternatives? | YAML is a 100% superset of JSON, so it doesn't make sense to reject YAML and then consider JSON instead. YAML does everything JSON does, but YAML gives so much more too (like references). I can't think of anything XML can do that YAML can't, except to validate a document with a DTD, which in my experience has never been worth the overhead. But YAML is so much faster and easier to type and read than XML. As for attributes or properties, if you think about it, they don't truly "add" anything... it's just a notational shortcut to write something as an attribute of the node instead of putting it in its own child node. But if you like that convenience, you can often emulate it with YAML's inline lists/hashes. Eg: <!-- XML --><Director name="Spielberg"> <Movies> <Movie title="Jaws" year="1975"/> <Movie title="E.T." year="1982"/> </Movies></Director># YAMLDirector: name: Spielberg Movies: - Movie: {title: E.T., year: 1975} - Movie: {title: Jaws, year: 1982} For me, the luxury of not having to write each node tag twice, combined with the freedom from all the angle-bracket litter makes YAML a preferred choice. I also actually like the lack of formal tag attributes, as that always seemed to me like a gray area of XML that needlessly introduced two sets of syntax (both when writing and traversing) for essentially the same concept. YAML does away with that confusion altogether. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/51492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196/"
]
} |
51,499 | One I am aware of is Perl::Critic And my googling has resulted in no results on multiple attempts so far. :-( Does anyone have any recommendations here? Any resources to configure Perl::Critic as per our coding standards and run it on code base would be appreciated. | In terms of setting up a profile, have you tried perlcritic --profile-proto ? This will emit to stdout all of your installed policies with all their options with descriptions of both, including their default values, in perlcriticrc format. Save and edit to match what you want. Whenever you upgrade Perl::Critic, you may want to run this command again and do a diff with your current perlcriticrc so you can see any changes to existing policies and pick up any new ones. In terms of running perlcritic regularly, set up a Test::Perl::Critic test along with the rest of your tests. This is good for new code. For your existing code, use Test::Perl::Critic::Progressive instead. T::P::C::Progressive will succeed the first time you run it, but will save counts on the number of violations; thereafter, T::P::C::Progressive will complain if any of the counts go up. One thing to look out for is when you revert changes in your source control system. (You are using one, aren't you?) Say I check in a change and run tests and my changes reduce the number of P::C violations. Later, it turns out my change was bad, so I revert to the old code. The T::P::C::Progressive test will fail due to the reduced counts. The easiest thing to do at this point is to just delete the history file (default location t/.perlcritic-history) and run again. It should reproduce your old counts and you can write new stuff to bring them down again. Perl::Critic has a lot of policies that ship with it, but there are a bunch of add-on distributions of policies. Have a look at Task::Perl::Critic and Task::Perl::Critic::IncludingOptionalDependencies . You don't need to have a single perlcriticrc handle all your code. Create separate perlcriticrc files for each set of files you want to test and then a separate test that points to each one. For an example, have a look at the author tests for P::C itself at http://perlcritic.tigris.org/source/browse/perlcritic/trunk/Perl-Critic/xt/author/ . When author tests are run, there's a test that runs over all the code of P::C, a second test that applies additional rules just on the policies, and a third one that criticizes P::C's tests. I personally think that everyone should run at the "brutal" severity level, but knock out the policies that they don't agree with. Perl::Critic isn't entirely self compliant; even the P::C developers don't agree with everything Conway says. Look at the perlcriticrc files used on Perl::Critic itself and search the Perl::Critic code for instances of "## no critic"; I count 143 at present. (Yes, I'm one of the Perl::Critic developers.) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
]
} |
51,502 | I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects. However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read. For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing): if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life()did_i_not_warn_you_biz()my_father_is_avenged() The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this: if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() #-- while --#-- if --did_i_not_warn_you_biz()my_father_is_avenged() And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me. | Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5342/"
]
} |
51,520 | Given a path such as "mydir/myfile.txt" , how do I find the file's absolute path in Python? E.g. on Windows, I might end up with: "C:/example/cwd/mydir/myfile.txt" | >>> import os>>> os.path.abspath("mydir/myfile.txt")'C:/example/cwd/mydir/myfile.txt' Also works if it is already an absolute path: >>> import os>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")'C:/example/cwd/mydir/myfile.txt' | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/51520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
]
} |
51,526 | I have a list of structs and I want to change one element. For example : MyList.Add(new MyStruct("john");MyList.Add(new MyStruct("peter"); Now I want to change one element: MyList[1].Name = "bob" However, whenever I try and do this I get the following error: Cannot modify the return value of System.Collections.Generic.List.this[int]‘ because it is not a variable If I use a list of classes, the problem doesn't occur. I guess the answer has to do with structs being a value type. So, if I have a list of structs should I treat them as read-only ? If I need to change elements in a list then I should use classes and not structs? | MyList[1] = new MyStruct("bob"); structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created). In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989/"
]
} |
51,553 | I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows): SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples; Is this normal behaviour when using a SQL database? The schema (the table holds responses to a survey): CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);\copy tuples from '350,000 responses.csv' delimiter as ',' I wrote some tests in Java and Python for context and they crush SQL (except for pure python): java 1.5 threads ~ 7 ms java 1.5 ~ 10 ms python 2.5 numpy ~ 18 ms python 2.5 ~ 370 ms Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown) Tunings i've tried without success include (blindly following some web advice): increased the shared memory available to Postgres to 256MB increased the working memory to 2MBdisabled connection and statement loggingused a stored procedure via CREATE FUNCTION ... LANGUAGE SQL So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help. No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest. The sqlite3 timing is driven by the Python program and is running from disk (not :memory:) I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data. The Postgres query doesn't change timing on subsequent runs. I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!) | Postgres is doing a lot more than it looks like (maintaining data consistency for a start!) If the values don't have to be 100% spot on, or if the table is updated rarely, but you are running this calculation often, you might want to look into Materialized Views to speed it up. (Note, I have not used materialized views in Postgres, they look at little hacky, but might suite your situation). Materialized Views Also consider the overhead of actually connecting to the server and the round trip required to send the request to the server and back. I'd consider 200ms for something like this to be pretty good, A quick test on my oracle server, the same table structure with about 500k rows and no indexes, takes about 1 - 1.5 seconds, which is almost all just oracle sucking the data off disk. The real question is, is 200ms fast enough? -------------- More -------------------- I was interested in solving this using materialized views, since I've never really played with them. This is in oracle. First I created a MV which refreshes every minute. create materialized view mv_so_x build immediate refresh complete START WITH SYSDATE NEXT SYSDATE + 1/24/60 as select count(*),avg(a),avg(b),avg(c),avg(d) from so_x; While its refreshing, there is no rows returned SQL> select * from mv_so_x;no rows selectedElapsed: 00:00:00.00 Once it refreshes, its MUCH faster than doing the raw query SQL> select count(*),avg(a),avg(b),avg(c),avg(d) from so_x; COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)---------- ---------- ---------- ---------- ---------- 1899459 7495.38839 22.2905454 5.00276131 2.13432836Elapsed: 00:00:05.74SQL> select * from mv_so_x; COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)---------- ---------- ---------- ---------- ---------- 1899459 7495.38839 22.2905454 5.00276131 2.13432836Elapsed: 00:00:00.00SQL> If we insert into the base table, the result is not immediately viewable view the MV. SQL> insert into so_x values (1,2,3,4,5);1 row created.Elapsed: 00:00:00.00SQL> commit;Commit complete.Elapsed: 00:00:00.00SQL> select * from mv_so_x; COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)---------- ---------- ---------- ---------- ---------- 1899459 7495.38839 22.2905454 5.00276131 2.13432836Elapsed: 00:00:00.00SQL> But wait a minute or so, and the MV will update behind the scenes, and the result is returned fast as you could want. SQL> / COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)---------- ---------- ---------- ---------- ---------- 1899460 7495.35823 22.2905352 5.00276078 2.17647059Elapsed: 00:00:00.00SQL> This isn't ideal. for a start, its not realtime, inserts/updates will not be immediately visible. Also, you've got a query running to update the MV whether you need it or not (this can be tune to whatever time frame, or on demand). But, this does show how much faster an MV can make it seem to the end user, if you can live with values which aren't quite upto the second accurate. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5357/"
]
} |
51,572 | How does one reliably determine a file's type? File extension analysis is not acceptable. There must be a rubyesque tool similar to the UNIX file(1) command? This is regarding MIME or content type, not file system classifications, such as directory, file, or socket. | There is a ruby binding to libmagic that does what you need. It is available as a gem named ruby-filemagic : gem install ruby-filemagic Require libmagic-dev . The documentation seems a little thin, but this should get you started: $ irb irb(main):001:0> require 'filemagic' => trueirb(main):002:0> fm = FileMagic.new=> #<FileMagic:0x7fd4afb0>irb(main):003:0> fm.file('foo.zip') => "Zip archive data, at least v2.0 to extract"irb(main):004:0> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
51,574 | Has anyone had good experiences with any Java libraries for Graph algorithms. I've tried JGraph and found it ok, and there are a lot of different ones in google. Are there any that people are actually using successfully in production code or would recommend? To clarify, I'm not looking for a library that produces graphs/charts, I'm looking for one that helps with Graph algorithms, eg minimum spanning tree, Kruskal's algorithm Nodes, Edges, etc. Ideally one with some good algorithms/data structures in a nice Java OO API. | If you were using JGraph, you should give a try to JGraphT which is designed for algorithms. One of its features is visualization using the JGraph library. It's still developed, but pretty stable. I analyzed the complexity of JGraphT algorithms some time ago. Some of them aren't the quickest, but if you're going to implement them on your own and need to display your graph, then it might be the best choice. I really liked using its API, when I quickly had to write an app that was working on graph and displaying it later. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/51574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5346/"
]
} |
51,582 | Let's say I have the following class: public class Test<E> { public boolean sameClassAs(Object o) { // TODO help! }} How would I check that o is the same class as E ? Test<String> test = new Test<String>();test.sameClassAs("a string"); // returns true;test.sameClassAs(4); // returns false; I can't change the method signature from (Object o) as I'm overridding a superclass and so don't get to choose my method signature. I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails. | An instance of Test has no information as to what E is at runtime. So, you need to pass a Class<E> to the constructor of Test. public class Test<E> { private final Class<E> clazz; public Test(Class<E> clazz) { if (clazz == null) { throw new NullPointerException(); } this.clazz = clazz; } // To make things easier on clients: public static <T> Test<T> create(Class<T> clazz) { return new Test<T>(clazz); } public boolean sameClassAs(Object o) { return o != null && o.getClass() == clazz; }} If you want an "instanceof" relationship, use Class.isAssignableFrom instead of the Class comparison. Note, E will need to be a non-generic type, for the same reason Test needs the Class object. For examples in the Java API, see java.util.Collections.checkedSet and similar. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
]
} |
51,584 | If you are sending work/progress reports to the project lead on a daily or weekly basis, I wondered if you would consider using Twitter or similar services for these updates. Say if you're working remotely or with a distributed team and the project lead has a hard time getting an overview about the topics people are working on, and where the issues/time consumers are, would you set up some private accounts (or even a private company-internal service) to broadcast progress updates to your colleagues? edit Thanks for the link to those products, but do you already use one of it in your company too? For real-life professional use? | Try Laconica : An open source Twitter-like system you could run on your own servers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834/"
]
} |
51,589 | I'm attempting to make a DTS package to transfer data between two databases on the same server and I'm getting the following errors. Iv read that the Multiple-step OLE DB operation generated error can occur when you are transferring between different database types and there is loss of precision, but this is not that case here. How do I examine the column meta data? Error: 0xC0202009 at Data Flow Task, piTech [183]: An OLE DB error has occurred. Error code: 0x80040E21. An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E21 Description: "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.". Error: 0xC0202025 at Data Flow Task, piTech [183]: Cannot create an OLE DB accessor. Verify that the column metadata is valid. Error: 0xC004701A at Data Flow Task, DTS.Pipeline: component "piTech" (183) failed the pre-execute phase and returned error code 0xC0202025. | Take a look at the fields's proprieties (type, length, default value, etc.), they should be the same. I had this problem with SQL Server 2008 R2 because the fields's length are not equal. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
]
} |
51,592 | I assume that char* = "string" is the same to char* = new char[6] . I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves? | No. You only need to manually free strings when you manually allocate the memory yourself using the malloc function (in C) or the new operator (in C++). If you do not use malloc or new , then the char* or string will be created on the stack or as a compile-time constant. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
]
} |
51,619 | My server already runs IIS on TCP ports 80 and 443. I want to make a centralized "push/pull" Git repository available to all my team members over the Internet. So I should use HTTP or HTTPS. But I cannot use Apache because of IIS already hooking up listening sockets on ports 80 and 443! Is there any way to publish a Git repository over IIS ? Does Git use WebDAV? Update. It seems that Git HTTP installation is read-only. That's sad. I intended to keep the stable branch on a build server and redeploy using a hook on push. Does anyone see a workaround besides using SVN for that branch? | Bonobo Git Server https://bonobogitserver.com/ GitAspx - By Jeremy Skinner https://github.com/JeremySkinner/git-dot-aspx/ https://github.com/JeremySkinner/git-dot-aspx/downloads Install Instructions https://www.jeremyskinner.co.uk/2010/10/19/gitaspx-0-3-available/ Git Web https://gitweb.codeplex.com/ WebGitNET https://github.com/otac0n/WebGitNet Alternatively ... (non-IIS, but highly recommend, free and open-source) Gitea (fork of Gogs): https://gitea.io Gogs : https://gogs.io SCM Manager allows you to easily set up revision control endpoints for Git , Hg , and SVN under the same hosting process. HTTP/HTTPS is supported along with built-in user authentication. https://www.scm-manager.org https://bitbucket.org/sdorra/scm-manager/ | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
]
} |
51,624 | The rich presentational capabilities of WPF and Silverlight mean developers like me will be working closely with graphic designers more often these days, as is the case in my next project. Does anyone out there have any tips and experience (from both points of view) on making this go more smoothly? For example, when I mentioned source control to a designer recently, I was quickly told you can't source control graphics, images etc, so it is a waste of time. So I responded: ok but, what about XAML files in WPF/Silverlight? Scott Hanselman spoke about this topic in a podcast , but he focused more on the tools, while I'm more interested in the communication issues/aspects. | I have spent 4 months on a project working extremely closely with a designer and he has still not picked up the basic idea of CVS (which is not my choice of source control system). I'm talking template files, JavaScript and CSS here. He's not stupid, it's just one of these things that makes his job harder so he resists fully commiting himself to it. In my case I had to really hammer home the point that almost all of my JavaScript depended on the mark-up and when he changed his pure CSS, DIV-based layout into a table-based one without telling me then all my JS is going to break. Often during the course of the project myself and the designer, who I get on with quite well and play soccer with outside of work, had very heated exchanges about our respective responsibilities. If I didn't know him well enough to just get past these exchanges then I think it would have created an unbearable working environment. So I think it's important you establish between you both and with some sort of manager or project supervisor exactly what is expected of both parties during the project. In my case there have been very few problems lately, because the situation with CVS has been sorted out as well as the idea that he can't just go and change the mark-up whenever he feels like it. Rather than try and create template files and work on them directly, the designer only works on static files and its my responsibility to plug them into my template files. It's all about communication and a little bit of compromise on both sides. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023/"
]
} |
51,658 | I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way? | import ctypesimport osimport platformimport sysdef get_free_space_mb(dirname): """Return folder/drive free space (in megabytes).""" if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes)) return free_bytes.value / 1024 / 1024 else: st = os.statvfs(dirname) return st.f_bavail * st.f_frsize / 1024 / 1024 Note that you must pass a directory name for GetDiskFreeSpaceEx() to work( statvfs() works on both files and directories). You can get a directory namefrom a file with os.path.dirname() . Also see the documentation for os.statvfs() and GetDiskFreeSpaceEx . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
51,768 | As part of some error handling in our product, we'd like to dump some stack trace information. However, we experience that many users will simply take a screenshot of the error message dialog instead of sending us a copy of the full report available from the program, and thus I'd like to make some minimal stack trace information available in this dialog. A .NET stack trace on my machine looks like this: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)at System.IO.StreamReader..ctor(String path)at LVKWinFormsSandbox.MainForm.button1_Click(Object sender, EventArgs e) in C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36 I have this question: The format looks to be this: at <class/method> [in file:line ##] However, the at and in keywords, I assume these will be localized if they run, say, a norwegian .NET runtime instead of the english one I have installed. Is there any way for me to pick apart this stack trace in a language-neutral manner, so that I can display only the file and line number for those entries that have this? In other words, I'd like this information from the above text: C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36 Any advice you can give will be helpful. | You should be able to get a StackTrace object instead of a string by saying var trace = new System.Diagnostics.StackTrace(exception); You can then look at the frames yourself without relying on the framework's formatting. See also: StackTrace reference | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/51768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
]
} |
51,782 | I have always made a point of writing nice code comments for classes and methods with the C# xml syntax. I always expected to easily be able to export them later on. Today I actually have to do so, but am having trouble finding out how. Is there something I'm missing? I want to go Menu->Build->Build Code Documentation , but there is no option to do that, there. | Actually it's in the project properties. Build tab, Output section, XML documentation file, and enter the filename. It will be built on every build of the project. After that you can build the actual help with Sandcastle . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/51782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
]
} |
51,783 | Flat files and relational databases give us a mechanism to serialize structured data. XML is superb for serializing un-structured tree-like data. But many problems are best represented by graphs. A thermal simulation program will, for instance, work with temperature nodes connected to each others through resistive edges. So what is the best way to serialize a graph structure? I know XML can, to some extent, do it---in the same way that a relational database can serialize a complex web of objects: it usually works but can easily get ugly. I know about the dot language used by the graphviz program, but I'm not sure this is the best way to do it. This question is probably the sort of thing academia might be working on and I'd love to have references to any papers discussing this. | How do you represent your graph in memory? Basically you have two (good) options: an adjacency list representation an adjacency matrix representation in which the adjacency list representation is best used for a sparse graph, and a matrix representation for the dense graphs. If you used suchs representations then you could serialize those representations instead. If it has to be human readable you could still opt for creating your own serialization algorithm. For example you could write down the matrix representation like you would do with any "normal" matrix: just print out the columns and rows, and all the data in it like so: 1 2 31 #t #f #f2 #f #f #t3 #f #t #f (this is a non-optimized, non weighted representation, but can be used for directed graphs) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428/"
]
} |
51,786 | How can I generate UML diagrams (especially sequence diagrams) from existing Java code? | ObjectAid UML Explorer Is what I used. It is easily installed from the repository: Name: ObjectAid UML ExplorerLocation: http://www.objectaid.com/update/current And produces quite nice UML diagrams: Description from the website: The ObjectAid UML Explorer is different from other UML tools. It uses the UML notation to show a graphical representation of existing code that is as accurate and up-to-date as your text editor, while being very easy to use. Several unique features make this possible: Your source code and libraries are the model that is displayed, they are not reverse engineered into a different format. If you update your code in Eclipse, your diagram is updated as well; there is no need to reverse engineer source code. Refactoring updates your diagram as well as your source code. When you rename a field or move a class, your diagram simply reflects the changes without going out of sync. All diagrams in your Eclipse workspace are updated with refactoring changes as appropriate. If necessary, they are checked out of your version control system. Diagrams are fully integrated into the Eclipse IDE. You can drag Java classes from any other view onto the diagram, and diagram-related information is shown in other views wherever applicable. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/51786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772/"
]
} |
51,871 | Some of the features I think it must include are: Print Entire Solution Ability to print line numbers Proper choice of coding font and size to improve readability Nice Header Information Ability to print regions collapsed Couple feature additions: Automatically insert page breaksafter methods/classes Keep long lines readable (nearly allcurrent implementations are broken) Note: There are many reasons to need to print code... One very good one is escrow. | I use PrettyCode.Print for .NET . It does everything on your list, and more. (I use it for printing code excerpts for copyright registration paperwork, which is similar to your escrow case.) It is a little slow to open a really big solution, but not unbearably so, and the output quality is excellent. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744/"
]
} |
51,925 | We are currently evaluating different applications that interface with Visual Studio 2008 (C#) and Subversion to do automated builds of our core libraries. We are hoping to have nightly builds performed and either email the list of changes made to each developer or have the latest versions be pushed to each workstation. What has been your experience with these tools and what are some recommendations? Suggested software Cruise Control .NET Hudson TeamCity Suggested articles Continuous Integration: From Theory to Practice 2nd Edition (CC.net) Automating Your ASP.NET Build and Deploy Process with Hudson | Cruise Control.net (ccnet) does everything you are looking for. Its pretty easy to use, just make sure if you are going to run it as a service, you give it an account and don't make it run as network service, that way you can give it rights on intranet boxes and have it do xcopy deploys. It has all kinds of email modes, on failure, on all, on fix after failure, and many many more. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/51925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3111/"
]
} |
51,927 | How do I figure out if an array contains an element? I thought there might be something like [1, 2, 3].includes(1) which would evaluate as true . | Some syntax sugar 1 in [1,2,3] | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/51927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5419/"
]
} |
51,931 | I'm having a problem running a T4 template using TextTransform.exe on my build server. On my dev machine the template works perfectly. The error message is as follows. error : Running transformation: System.TypeLoadException: Could not instantiate type System.Xml.Linq.XDocument The build server has the windows 2008 SDK on it, my machine has VS 2008. I thought mayve it couldn't find System.Data.Xml so I ensure the dll was present in the same directory, but no luck. Any ideas? | Some syntax sugar 1 in [1,2,3] | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/51931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2086/"
]
} |
51,949 | Given a string "filename.conf" , how to I verify the extension part? I need a cross platform solution. | Is this too simple of a solution? #include <iostream>#include <string>int main(){ std::string fn = "filename.conf"; if(fn.substr(fn.find_last_of(".") + 1) == "conf") { std::cout << "Yes..." << std::endl; } else { std::cout << "No..." << std::endl; }} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/51949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
]
} |
51,950 | I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ? | InternalsVisibleTo attribute to the rescue! Just add: [assembly:InternalsVisibleToAttribute("UnitTestAssemblyName")] to your Core classes AssemblyInfo.cs file See Friend Assemblies (C# Programming Guide) for best practices. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/51950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
]
} |
51,969 | In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command ALTER DATABASE <database> SET READ_COMMITTED_SNAPSHOT ON; ? I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI. | SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name= 'YourDatabase' Return value: 1 : READ_COMMITTED_SNAPSHOT option is ON . Read operations under the READ COMMITTED isolation level are based on snapshot scans and do not acquire locks. 0 (default): READ_COMMITTED_SNAPSHOT option is OFF . Read operations under the READ COMMITTED isolation level use Shared (S) locks . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/51969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5217/"
]
} |
51,988 | Have any well-documented or open source projects targeted iPhone , Blackberry , and Android ? Are there other platforms which are better-suited to such an endeavor ? Note that I am particularly asking about client-side software, not web apps, though any information about the difficulties of using web apps across multiple mobile platforms is also interesting. | The HTML5 standard has support for releasing stand-alone HTML5 apps. Essentially a HTML5 app is a bundle of HTML5 , JavaScript and CSS files that will run stand-alone in the browser of the desktop or device. You can distribute them like any other program, including selling them on the iStore for the iPhone . The support for this is patchy at the moment but is likely to improve tremendously in the next year or two. Google for HTML5 apps for information and resources. A good introduction to HTML5 is the online book "Dive Into HTML5" by Mark Pilgrim . This is a work in progress, but sufficiently complete to be useful. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/51988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/654/"
]
} |
52,002 | Definition: A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction How to check if the given string is a palindrome? This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C. Looking for solutions in any and all languages possible. | PHP sample : $string = "A man, a plan, a canal, Panama";function is_palindrome($string){ $a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string)); return $a==strrev($a);} Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/52002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
]
} |
52,008 | I need to design a small project for generating excel reports in .NET, which will be sent to users to use. The excel reports will contain PivotTables. I don't have much experience with them, but I can think of three implementation alternatives: Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data. Generate a small access database and send it along with the excel file, connect to it. Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think. What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about? | PHP sample : $string = "A man, a plan, a canal, Panama";function is_palindrome($string){ $a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string)); return $a==strrev($a);} Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/52008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
]
} |
52,080 | How can I build a loop in JavaScript? | For loops for (i = startValue; i <= endValue; i++) { // Before the loop: i is set to startValue // After each iteration of the loop: i++ is executed // The loop continues as long as i <= endValue is true} For...in loops for (i in things) { // If things is an array, i will usually contain the array keys *not advised* // If things is an object, i will contain the member names // Either way, access values using: things[i]} It is bad practice to use for...in loops to itterate over arrays. It goes against the ECMA 262 standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by Prototype . (Thanks to Chase Seibert for pointing this out in the comments) While loops while (myCondition) { // The loop will continue until myCondition is false} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/52080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
52,092 | This caught my attention last night. On the latest ALT.NET Podcast Scott Bellware discusses how as opposed to Ruby, languages like C#, Java et al. are not truly object oriented rather opting for the phrase "class-oriented". They talk about this distinction in very vague terms without going into much detail or discussing the pros and cons much. What is the real difference here and how much does it matter? What are other languages then are "object-oriented"? It sounded pretty interesting but I don't want to have to learn Ruby just to know what if anything I am missing. Update After reading some of the answers below it seems like people generally agree that the reference is to duck-typing. What I'm not sure I understand still though is the claim that this ultimately changes all that much. Especially if you are already doing proper TDD with loose coupling etc. Can someone show me an example of a specific thing I could do with Ruby that I cannot do with C# and that exemplifies this different OOP approach? | The duck typing comments here are more attributing to the fact that Ruby and Python are more dynamic than C#. It doesn't really have anything to do with it's OO Nature. What (I think) Bellware meant by that is that in Ruby, everything is an object. Even a class. A class definition is an instance of an object. As such, you can add/change/remove behavior to it at runtime. Another good example is that NULL is an object as well. In ruby, everything is LITERALLY an object. Having such deep OO in it's entire being allows for some fun meta-programming techniques such as method_missing. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/52092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
} |
52,103 | I am looking to manage a SQL Server 2008 DB using Management Studio 2005. The reason for this is because our server is a 64-bit machine and we only have the 64-bit version of the software. Is this possible? How about managing a SQL Server 2005 DB using Management Studio 2008? | UPDATE: You can use Cumulative update package 5 for SQL Server 2005 Service Pack 2 to connect to 2008. FIX:50002151 946127 ( http://support.microsoft.com/kb/946127/ ) FIX: You may experience problems when you use SQL Server Management Studio in SQL Server 2005 to connect to an instance of SQL Server 2008 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/52103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316/"
]
} |
52,108 | What is the shortcut to open a file within your solution in Visual Studio 2008 (+ Resharper)? | Ctrl + T (ReSharper, Goto, type) will open a class file for you. Looks like Ctrl + Shift + T opens files. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/52108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
]
} |
52,176 | Since Graduating from a very small school in 2006 with a badly shaped & outdated program (I'm a foreigner & didn't know any better school at the time) I've come to realize that I missed a lot of basic concepts from a mathematical & software perspective that are mostly the foundations of other higher concepts. I.e. I tried to listen/watch the open courseware from MIT on Introduction to Algorithms but quickly realized I was missing several mathematical concepts to better understand the course. So what are the core mathematical concepts a good software engineer should know? And what are the possible books/sites you will recommend me? | Math for Programmers . A good read. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/52176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5413/"
]
} |
52,187 | I need to test a serial port application on Linux, however, my test machine only has one serial port. Is there a way to add a virtual serial port to Linux and test my application by emulating a device through a shell or script? Note: I cannot remap the port, it hard coded on ttys2 and I need to test the application as it is written. | Complementing the @slonik's answer. You can test socat to create Virtual Serial Port doing the following procedure (tested on Ubuntu 12.04): Open a terminal (let's call it Terminal 0) and execute it: socat -d -d pty,raw,echo=0 pty,raw,echo=0 The code above returns: 2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/22013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/32013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs [3,3] and [5,5] Open another terminal and write (Terminal 1): cat < /dev/pts/2 this command's port name can be changed according to the pc. it's depends on the previous output. 2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**2**2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**3**2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs you should use the number available on highlighted area. Open another terminal and write (Terminal 2): echo "Test" > /dev/pts/3 Now back to Terminal 1 and you'll see the string "Test". | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/52187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
]
} |
52,213 | When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience. Is there a way, in HTTP headers or equivalents, to change this behaviour? | <input autocomplete="off"> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/52213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000/"
]
} |
52,234 | Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible? If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)? | tf diff /shelveset:shelveset /format:unified Edit: This writes to standard output. You can pipe the output to a file. For more options, see Difference Command . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/52234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
]
} |
52,239 | We are working with an oracle database in which the person that set it up is "long gone" and thus do not know the sysdba password, but need it. We have root access to the box (its on linux). Is there any way to recover or change the sys passwords? | Have you tried logging into Linux as your installed Oracle user then sqlplus "/ as sysdba" When you log in you'll be able to change your password. alter user sys identified by <new password>; Good luck :) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/52239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
]
} |
52,290 | So basically I am looking for good templates for writing both technical and functional specs on a project or work request. What do you use? How deep do you get while writing the specs? Any additional general tips you could provide would be appreciated. My company needs these badly. I work for a contractor and right now we do not use these documents at all. EDIT: I have read Joel's take about Painless Specification , I really liked it, but are there any other opinions :) | On general tips; We are implementing a process of 1) Business Requirements Statement (BRS) 2) Functional Specification 3) Technical specification The BRS covers what the business problems are, and what the requirements are around solutions, testing, security, reliability and delivery. This defines what would make a successful solution. The functional spec details what is needed, how it should look, how long fields should be, etc. The technical spec details where the data comes from, any tricky code that may need to be considered. The customer owns the requirements. The developers own the tech specs, and the functional spec is a middle ground. Testing is done against the tech specs (usually unit testing) then against the functional specs (usually system testing) and then against the requirements (UAT). The important part of this (and we are struggling with) is that the developers still need to deliver to the functional spec, and the original business requirements. In reality the functional and tech specs are just there for clarity. In short, my main tip is to first work out the process you wish to implement. Then seek agreement from all parties involved in your proposed process, then work on the templates to fit. The templates themselves are only are a small part of the change you want to make. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/52290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4144/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.