source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
156,815 | In a question answer I find the following coding tip:- 2) simple lambdas with one parameter: x => x.ToString() //simplify so many calls As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples. I've researched lambdas so I think I know what they do, however I may not fully understand so a little unpacking might also be in order. | When you need to create an instance of a delegate which has a single parameter, lambda expressions allow you to create that delegate "inline" in a very concise manner. For instance, here's code to find a particular person in a list, by their name: List<Person> list = new List<Person>();// [..] Populate list herePerson jon = list.Find(p => p.Name == "Jon"); In C# 2.0 you could use an anonymous method which was a little bit more longwinded, but not too bad: List<Person> list = new List<Person>();// [..] Populate list herePerson jon = list.Find(delegate(Person p) { return p.Name == "Jon"; }); In C# 1.0 you'd have to create a whole extra method. In addition, if you wanted to parameterise it, you'd have to create a different type, whereas anonymous methods and lambda expressions capture their executing environment (local variables etc) so they act like closures: public Person FindByName(List<Person> list, String name){ return list.Find(p => p.Name == name); // The "name" variable is captured} There's more about this in my article about closures . While passing delegates into methods isn't terribly common in C# 2.0 and .NET 2.0, it's a large part of the basis of LINQ - so you tend to use it a lot in C# 3.0 with .NET 3.5. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22284/"
]
} |
156,911 | I am going to work on a project where a fairly large web app needs to tweaked to handle several languages. The thing runs with a hand crafted PHP code but it's pretty clean. I was wondering what would be the best way to do that? Making something on my own, trying to fit the actual architecture. Rewriting a good part of it using a framework (e.g., Symfony) that will manage i18n for me? For option 1, where should I store the i18n data? *.po, xliff, pure DB? I thought about an alternative: using Symfony only for the translation, but setting the controller to load the website as it already is. Quick, but dirty. On the other hand, it allows us to make the next modification, moving slowly to full Symfony: this web site is really a good candidate for that. But maybe there are some standalone translation engines that would do the job better than an entire web framework. It's a bit like using a bazooka to kill a fly... | There are a number of ways of tackling this. None of them "the best way" and all of them with problems in the short term or the long term.The very first thing to say is that multi lingual sites are not easy, translators and lovely people but hard to work with and most programmers see the problem as a technical one only. There is also another dimension, outside the scope of this answer, as to whether you are translating or localising. This involves looking at the target audiences cultural mores and then tailoring language, style, layout, colour, typeface etc., to that culture. Finally do not use MT, Machine Translation, for anything serious or if it needs to be accurate and when acquiring translators ensure that they are translating from a foreign language into their native language which means that they understand all the nuances of the target language. Right. Solutions. On the basis that you do not want to rewrite the site then simply clone the site you have and translate the copies to the target language. Assuming the code base is stable you can use a VCS to manage any code changes. You can tweak individual parts of the site to fit the target language, for example French text is on average 30% larger than the equivalent English text so using one site to deliver this means you may (will) have formatting problems and need to swap a different css file in and out depending on the language. It might seem a clunky way to do it but then how long are the sites going to exist? The management overhead of doing it this way may well be less than other options. Second way without rebuilding. Replace all content in the current site with tags and then put the different language in file or db tables, sniff the users desired language (do you have registered users who can make a preference or do you want to get the browser language tag, or is it going to be URL dot-com dot-fr, dot-de that make the choice) and then replace the tags with the target language. Then you need to address the sizing issues and the image issues separately. This solution is in effect when frameworks like Symfony and Zend do to implement l10n. Then you could rebuild with a framework or with gettext and possibly have a cleaner solution but remember frameworks were designed to solve other problems, not translation and the translation component has come into the framework as partial solution not the full one. The big problem with all the solutions is ongoing maintenance. Because not only do you have a code base but also multiple language bases to maintain. Unless you all in one solution is really clever and effective then to ongoing task will be difficult. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
]
} |
156,916 | I need to list all files whose names start with 'SomeLongString'. But the case of 'SomeLongString' can vary. How? I am using zsh, but a bash solution is also welcome. | ZSH: $ unsetopt CASE_GLOB Or, if you don't want to enable case-insensitive globbing in general, you can activate it for only the varying part: $ print -l (#i)(somelongstring)* This will match any file that starts with "somelongstring" (in any combination of lower/upper case). The case-insensitive flag applies for everything between the parentheses and can be used multiple times. Read the manual zshexpn(1) for more information. UPDATE Almost forgot, you have to enable extendend globbing for this to work: setopt extendedglob | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
]
} |
156,936 | I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help. I would like to expose an iterator for a class like this: template <class T>class MyContainer{public: // Here is the problem: // typedef for MyIterator without exposing std::vector publicly? MyIterator Begin() { return mHiddenContainerImpl.begin(); } MyIterator End() { return mHiddenContainerImpl.end(); }private: std::vector<T> mHiddenContainerImpl;}; Am I trying at something that isn't a problem? Should I just typedef std::vector< T >::iterator? I am hoping on just depending on the iterator, not the implementing container... | You may find the following article interesting as it addresses exactly the problem you have posted: On the Tension Between Object-Oriented and Generic Programming in C++ and What Type Erasure Can Do About It | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2166173/"
]
} |
156,975 | I have a JLabel (actually, it is a JXLabel). I have put an icon and text on it. <icon><text> Now I wand to add some spacing on the left side of the component, like this: <space><icon><text> I DON'T accept suggestion to move the JLabel or add spacing by modifying the image. I just want to know how to do it with plain java code. | I have found the solution! setBorder(new EmptyBorder(0,10,0,0)); Thanks everyone! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15173/"
]
} |
157,005 | In HTML forms, buttons can be disabled by defining the "disabled" attribute on them, with any value: <button name="btn1" disabled="disabled">Hello</button> If a button is to be enabled, the attribute should not exist as there is no defined value that the disabled attribute can be set to that would leave the button enabled. This is causing me problems when I want to enable / disable buttons when using JSP Documents (jspx). As JSP documents have to be well-formed XML documents, I can't see any way of conditionally including this attribute, as something like the following isn't legal: <button name="btn1" <%= (isDisabled) ? "disabled" : "" %/> >Hello</button> While I could replicate the tag twice using a JSTL if tag to get the desired effect, in my specific case I have over 15 attributes declared on the button (lots of javascript event handler attributes for AJAX) so duplicating the tag is going to make the JSP very messy. How can I solve this problem, without sacrificing the readability of the JSP? Are there any custom tags that can add attributes to the parent by manipulating the output DOM? | I use a custom JSP tag with dynamic attributes. You use it like this: <util:element elementName="button" name="btn1" disabled="$(isDisabled ? 'disabled' : '')"/> Basically, what this tag does is generate an XML element with elementName and puts all attributes present in the tag, but skips the empty ones. The tag itself is pretty easy to implement, my implementation is just 44 lines long. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24068/"
]
} |
157,018 | I recently started learning Emacs . I went through the tutorial, read some introductory articles, so far so good. Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22. I read all information I could find but most of it seems fairly outdated and I'm still confused. The questions: What is their difference? Which mode should I install and use? Are there other Emacs add-ons that are essential for Python development? Relevant links: EmacsEditor @ wiki.python.org PythonMode @ emacswiki.org | If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it didn't work very nicely in the past, but there are updates available that fix some of the issues (for instance, on the emacswiki page you link), and you would hope some were integrated upstream by now. If I were the GNU Emacs kind, I would use python.el until I found specific reasons not to. The python-mode.el's single biggest problem as far as I've seen is that it doesn't quite understand triple-quoted strings. It treats them as single-quoted, meaning that a single quote inside a triple-quoted string will throw off the syntax highlighting: it'll think the string has ended there. You may also need to change your auto-mode-alist to turn on python-mode for .py files; I don't remember if that's still the case but my init.el has been setting auto-mode-alist for many years now. As for other addons, nothing I would consider 'essential'. XEmacs's func-menu is sometimes useful, it gives you a little function/class browser menu for the current file. I don't remember if GNU Emacs has anything similar. I have a rst-mode for reStructuredText editing, as that's used in some projects. Tying into whatever VC you use, if any, may be useful to you, but there is builtin support for most and easily downloaded .el files for the others. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/712/"
]
} |
157,026 | I just need a file (picture, pdf or other type file for printing) of the framework structure.It is very usefull while learning .Net framework. | .NET Framework 3.5 Common Namespaces and Types Poster November 2007 Edition The .NET Framework 3.5 Common Namespaces and Types Poster Overview The .NET Framework 3.5 Common Namespaces and Types Poster is downloadable as XPS or PDF format. There is also an XPS format file which prints over 16 letter or A4 pages for easy printing. Some assembly is required if you choose this print method. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22641/"
]
} |
157,039 | I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three. My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the split loop refactoring in mind), looks rather bloated: (alt 1) r = xrange(1, 10)twos = 0threes = 0for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1print twosprint threes This looks rather nice, but has the drawback of expanding the expression to a list: (alt 2) r = xrange(1, 10)print len([1 for v in r if v % 2 == 0])print len([1 for v in r if v % 3 == 0]) What I would really like is something like a function like this: (alt 3) def count(iterable): n = 0 for i in iterable: n += 1 return nr = xrange(1, 10)print count(1 for v in r if v % 2 == 0)print count(1 for v in r if v % 3 == 0) But this looks a lot like something that could be done without a function. The final variant is this: (alt 4) r = xrange(1, 10)print sum(1 for v in r if v % 2 == 0)print sum(1 for v in r if v % 3 == 0) and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well. So, my question to you is: Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better. To clear up some confusion below: In reality my filter predicates are more complex than just this simple test. The objects I iterate over are larger and more complex than just numbers My filter functions are more different and hard to parameterize into one predicate | Having to iterate over the list multiple times isn't elegant IMHO. I'd probably create a function that allows doing: twos, threes = countmatching(xrange(1,10), lambda a: a % 2 == 0, lambda a: a % 3 == 0) A starting point would be something like this: def countmatching(iterable, *predicates): v = [0] * len(predicates) for e in iterable: for i,p in enumerate(predicates): if p(e): v[i] += 1 return tuple(v) Btw, "itertools recipes" has a recipe for doing much like your alt4. def quantify(seq, pred=None): "Count how many times the predicate is true in the sequence" return sum(imap(pred, seq)) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2010/"
]
} |
157,044 | I'm attempting to check for the existence of a node using the following .NET code: xmlDocument.SelectSingleNode( String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName)); This always raises: XPathException: Expression must evaluate to a node-set. Why am I getting this error and how can I resolve it? Thank you. | The expression given evaluates to a boolean, not a node-set. I assume you want to check whether the ProjectName equals the parametrized text. In this case you need to write //ErrorTable/ProjectName[text()='{0}'] This gives you a list of all nodes (a nodeset) matching the given condition. This list may be empty, in which case the C#-Expression in your sample will return null. As an afterthought: You can use the original xpath expression, but not with SelectSingleNode, but with Evaluate, like this: (bool)xmlDocument.CreateNavigator().Evaluate(String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName)); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
]
} |
157,114 | I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as " true " in case the value of this specified column isn't null and " false " in case the value is null . How can I select such a boolean with T-SQL? | You have to use a CASE statement for this: SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName; | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/157114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5703/"
]
} |
157,119 | As far as i know it is not possible to do the following in C# 2.0 public class Father{ public virtual Father SomePropertyName { get { return this; } }}public class Child : Father{ public override Child SomePropertyName { get { return this; } }} I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic. public new Child SomePropertyName Is there any solution in 2.0?What about any features in 3.5 that address this matter? | This is not possible in any .NET language because of type-safety concerns. In type-safe languages, you must provide covariance for return values, and contravariance for parameters. Take this code: class B { S Get(); Set(S);}class D : B { T Get(); Set(T);} For the Get methods, covariance means that T must either be S or a type derived from S . Otherwise, if you had a reference to an object of type D stored in a variable typed B , when you called B.Get() you wouldn't get an object representable as an S back -- breaking the type system. For the Set methods, contravariance means that T must either be S or a type that S derives from. Otherwise, if you had a reference to an object of type D stored in a variable typed B , when you called B.Set(X) , where X was of type S but not of type T , D::Set(T) would get an object of a type it did not expect. In C#, there was a conscious decision to disallow changing the type when overloading properties, even when they have only one of the getter/setter pair, because it would otherwise have very inconsistent behavior ( "You mean, I can change the type on the one with a getter, but not one with both a getter and setter? Why not?!?" -- Anonymous Alternate Universe Newbie). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/157119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20335/"
]
} |
157,149 | Is it possible to split the information in a .csproj across more than one file? A bit like a project version of the partial class feature. | You can not have more than one master csproj. But because the underneath wiring of the csproj is done using msbuild you can simply have multiple partial csproj that import each other. The solution file would see the most derived csproj. project1.csproj <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> ....</Project> project2.csproj <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="project1.csproj" /> ...</Project> project.csproj - this is the main project that is referred by the solution file. <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="project2.csproj" /> ...</Project> Bottom line is that using msbuild Import feature you can have partial csproj files where each one would contain definitions that the main project (project.csproj in my example) would use. Visual Studio will show a Security Warning for project dialog when you open your changed solution or project file. Choose the option Load Project Normally and press OK . When opening the solution again later the warning will not be shown because the configuration to Load Project Normally is stored in the suo file. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/157149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24092/"
]
} |
157,163 | I want to run a command as soon as a certain text appears in a log file. How do I do that in Bash? | Use command tail -f file.log | grep --line-buffered "my pattern" | while read linedo echo $linedone The --line-buffered is the key here, otherwise the read will fail. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24094/"
]
} |
157,195 | Anybody knows how to do this? I got all the information of the email (body, subject, from , to, cc, bcc) and need to generate an .eml file out of it. | You can construct javax.mail.Message object (or have it already constructed from the mail server) and then you can use writeTo() method to save it to file.See JavaMail API for more information. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/157195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6200/"
]
} |
157,198 | I was reading this article about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author uses the next Idiom: Listing 7. Attempting to solve the out-of-order write problem public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { //1 Singleton inst = instance; //2 if (inst == null) { synchronized(Singleton.class) { //3 inst = new Singleton(); //4 } instance = inst; //5 } } } return instance;} And my question is: Is there any reason to synchronize twice some code with the same lock?Have this any purpose it? Many thanks in advance. | The point of locking twice was to attempt to prevent out-of-order writes. The memory model specifies where reorderings can occur, partly in terms of locks. The lock ensures that no writes (including any within the singleton constructor) appear to happen after the "instance = inst;" line. However, to go deeper into the subject I'd recommend Bill Pugh's article . And then never attempt it :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24097/"
]
} |
157,232 | I have wrapped Log4net in a static wrapper and want to log loggingEvent.LocationInformation.MethodNameloggingEvent.LocationInformation.ClassName However all I get is the name of my wrapper. How can I log that info using a forwardingappender and a static wrapper class like Logger.Debug("Logging to Debug");Logger.Info("Logging to Info");Logger.Warn("Logging to Warn");Logger.Error(ex);Logger.Fatal(ex); | Well the error was somewhere in my appender but for completeness ill include the answer to the best of my knowledge: the Facade you need should wrap ILogger and NOT ILog public static class Logger { private readonly static Type ThisDeclaringType = typeof(Logger); private static readonly ILogger defaultLogger; static Logger() { defaultLogger = LoggerManager.GetLogger(Assembly.GetCallingAssembly(),"MyDefaultLoggger"); ... public static void Info(string message) { if (defaultLogger.IsEnabledFor(infoLevel)) { defaultLogger.Log(typeof(Logger), infoLevel, message, null); } } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/157232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15555/"
]
} |
157,260 | In the past and with most my current projects I tend to use a for loop like this: var elements = document.getElementsByTagName('div');for (var i=0; i<elements.length; i++) { doSomething(elements[i]);} I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this: var elements = document.getElementsByTagName('div'), length = elements.length;while(length--) { doSomething(elements[length]);} What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter? | Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, you must be careful , you can't use it if any of the values in array could be "falsy" . In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar. var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];for (var i=0, item; item = list[i]; i++) { // Look no need to do list[i] in the body of the loop console.log("Looping: index ", i, "item" + item);} Note that this can also be used to loop backwards. var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}]; for (var i = list.length - 1, item; item = list[i]; i--) { console.log("Looping: index ", i, "item", item);} ES6 Update for...of gives you the name but not the index, available since ES6 for (const item of list) { console.log("Looping: index ", "Sorry!!!", "item" + item);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/157260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21677/"
]
} |
157,271 | I want to buy a 128bit SSL certificate for a website selling services. I checked http://www.rapidssl.com/ssl-certificate-products/ssl-certificate.htm and http://www.geotrust.com/ssl/compare-ssl-certificates.html . Why are the prices for QuickSSL (Geotrust, $249) and RapidSSL (rapidSSL, $69) so different? Is there any particular reason for this or it's just marketing? RapidSSL says the following: However it is our opinion that sites conducting more than 50 transactions will require a Professional Level SSL certificate due to the increased likelihood that the website's customers will expect SSL from a highly credible and established SSL provider and well known internationally accepted SSL brand. (by "professional level SSL" they mean Geotrust certs) P.S. will users really pay attention to the SSL issuing authority brand name? | The job of the SSL certificate authority(CA)/provider is to validate your organizational identity so that when customers access your web site, they not only get the padlock for security, but they know that your identity as the fully qualified hostname are authentic and not some phishing scam. True, most all users look no further than the padlock indicating secure connection to their bank web site, email, etc. However, if any CA were to become compromised, all browsers who trust that CA would be vulnerable, because an attacker could forge a certificate for any domain , including yours. Your choice of certificate provider has no bearing on this. I have yet to hear about this actually happening. MITM attacks are a big deal now with wireless hotspots becoming more and more prevalent. One more thing is browser compatibility. You would expect that your newly purchased cert be compatible with every modern browser. This is because they are all loaded with a list of root CA certs that trust a select list of SSL certificate authorities. If you buy from a CA that is not on that list, all your client browsers will get a security warning that the site's cert is not trusted. Just doublecheck that RapidSSL, Geotrust, or whoever you go with is in the list of all the browsers you care about. (e.g. for Firefox, it's at Tools/Options/Advanced/Encryption/View Certificates/Authorities tab) In the end, just get the cheapest one that gives you the level of encryption you want. It'll get the job done. Check with your web host provider. They may have discounts. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/157271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6647/"
]
} |
157,318 | We are using a PHP scripting for tunnelling file downloads, since we don't want to expose the absolute path of downloadable file: header("Content-Type: $ctype");header("Content-Length: " . filesize($file));header("Content-Disposition: attachment; filename=\"$fileName\"");readfile($file); Unfortunately we noticed that downloads passed through this script can't be resumed by the end user. Is there any way to support resumable downloads with such a PHP-based solution? | The first thing you need to do is to send the Accept-Ranges: bytes header in all responses, to tell the client that you support partial content. Then, if request with a Range: bytes=x-y header is received (with x and y being numbers) you parse the range the client is requesting, open the file as usual, seek x bytes ahead and send the next y - x bytes. Also set the response to HTTP/1.0 206 Partial Content . Without having tested anything, this could work, more or less: $filesize = filesize($file);$offset = 0;$length = $filesize;if ( isset($_SERVER['HTTP_RANGE']) ) { // if the HTTP_RANGE header is set we're dealing with partial content $partialContent = true; // find the requested range // this might be too simplistic, apparently the client can request // multiple ranges, which can become pretty complex, so ignore it for now preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches); $offset = intval($matches[1]); $length = intval($matches[2]) - $offset;} else { $partialContent = false;}$file = fopen($file, 'r');// seek to the requested offset, this is 0 if it's not a partial content requestfseek($file, $offset);$data = fread($file, $length);fclose($file);if ( $partialContent ) { // output the right headers for partial content header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize);}// output the regular HTTP headersheader('Content-Type: ' . $ctype);header('Content-Length: ' . $filesize);header('Content-Disposition: attachment; filename="' . $fileName . '"');header('Accept-Ranges: bytes');// don't forget to send the data tooprint($data); I may have missed something obvious, and I have most definitely ignored some potential sources of errors, but it should be a start. There's a description of partial content here and I found some info on partial content on the documentation page for fread . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/157318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
157,342 | Cron installation is vixie-cron /etc/cron.daily/rmspam.cron #!/bin/bash/usr/bin/rm /home/user/Maildir/.SPAM/cur/*; I Have this simple bash script that I want to add to a cron job (also includes spam learning commands before) but this part always fails with "File or directory not found" From what I figure is the metachar isn't being interperted correctly when run as a cron job. If I execute the script from the commandline it works fine. I'd like a why for this not working and of course a working solution :) Thanks edit #1came back to this question when I got popular question badge for it. I first did this, #!/bin/bashfind /home/user/Maildir/.SPAM/cur/ -t file | xargs rm and just recently was reading through the xargs man page and changed it to this #!/bin/bashfind /home/user/Maildir/.SPAM/cur/ -t file | xargs --no-run-if-empty rm short xargs option is -r | If there are no files in the directory, then the wildcard will not be expanded and will be passed to the command directly. There is no file called "*", and then the command fails with "File or directory not found." Try this instead: if [ -f /home/user/Maildir/.SPAM/cur/* ]; then rm /home/user/Maildir/.SPAM/cur/*fi Or just use the "-f" flag to rm. The other problem with this command is what happens when there is too much spam for the maximum length of the command line. Something like this is probably better overall: find /home/user/Maildir/.SPAM/cur -type f -exec rm '{}' + If you have an old find that only execs rm one file at a time: find /home/user/Maildir/.SPAM/cur -type f | xargs rm That handles too many files as well as no files. Thanks to Charles Duffy for pointing out the + option to -exec in find. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4275/"
]
} |
157,354 | I happened to debate with a friend during college days whether advanced mathematics is necessary for any veteran programmer. He used to argue fiercely against that. He said that programmers need only basic mathematical knowledge from high school or fresh year college math, no more no less, and that almost all of programming tasks can be achieved without even need for advanced math. He argued, however, that algorithms are fundamental & must-have asset for programmers. My stance was that all computer science advances depended almost solely on mathematics advances, and therefore a thorough knowledge in mathematics would help programmers greatly when they're working with real-world challenging problems. I still cannot settle on which side of the arguments is correct. Could you tell us your stance, from your own experience? | To answer your question as it was posed I would have to say, "No, mathematics is not necessary for programming". However, as other people have suggested in this thread, I believe there is a correlation between understanding mathematics and being able to "think algorithmically". That is, to be able to think abstractly about quantity, processes, relationships and proof. I started programming when I was about 9 years old and it would be a stretch to say I had learnt much mathematics by that stage. However, with a bit of effort I was able to understand variables, for loops, goto statements (forgive me, I was Vic 20 BASIC and I hadn't read any Dijkstra yet) and basic co-ordinate geometry to put graphics on the screen. I eventually went on to complete an honours degree in Pure Mathematics with a minor in Computer Science. Although I focused mainly on analysis, I also studied quite a bit of discrete maths, number theory, logic and computability theory. Apart from being able to apply a few ideas from statistics, probability theory, vector analysis and linear algebra to programming, there was little maths I studied that was directly applicable to my programming during my undergraduate degree and the commercial and research programming I did afterwards. However, I strongly believe the formal methods of thinking that mathematics demands — careful reasoning, searching for counter-examples, building axiomatic foundations, spotting connections between concepts — has been a tremendous help when I have tackled large and complex programming projects. Consider the way athletes train for their sport. For example, footballers no doubt spend much of their training time on basic football skills. However, to improve their general fitness they might also spend time at the gym on bicycle or rowing machines, doing weights, etc. Studying mathematics can be likened to weight-training or cross-training to improve your mental strength and stamina for programming. It is absolutely essential that you practice your basic programming skills but studying mathematics is an incredible mental work-out that improves your core analytic ability. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/157354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24113/"
]
} |
157,392 | I want to find out, with an SQL query, whether an index is UNIQUE or not. I'm using SQLite 3. I have tried two approaches: SELECT * FROM sqlite_master WHERE name = 'sqlite_autoindex_user_1' This returns information about the index ("type", "name", "tbl_name", "rootpage" and "sql"). Note that the sql column is empty when the index is automatically created by SQLite. PRAGMA index_info(sqlite_autoindex_user_1); This returns the columns in the index ("seqno", "cid" and "name"). Any other suggestions? Edit: The above example is for an auto-generated index, but my question is about indexes in general. For example, I can create an index with "CREATE UNIQUE INDEX index1 ON visit (user, date)". It seems no SQL command will show if my new index is UNIQUE or not. | PRAGMA INDEX_LIST('table_name'); Returns a table with 3 columns: seq Unique numeric ID of index name Name of the index unique Uniqueness flag (nonzero if UNIQUE index.) Edit Since SQLite 3.16.0 you can also use table-valued pragma functions which have the advantage that you can JOIN them to search for a specific table and column. See @mike-scotty's answer . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/157392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12534/"
]
} |
157,424 | I have a dictionary of 200,000 items (the keys are strings and the values are integers). What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)? a={ 'keyC':1, 'keyB':2, 'keyA':1 }b = a.items()b.sort( key=lambda a:a[0])b.sort( key=lambda a:a[1], reverse=True )print b>>>[('keyB', 2), ('keyA', 1), ('keyC', 1)] | You can't sort dictionaries. You have to sort the list of items. Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric. a = { 'key':1, 'another':2, 'key2':1 }b= a.items()b.sort( key=lambda a:(-a[1],a[0]) )print b Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option. def valueKeyCmp( a, b ): return cmp( (-a[1], a[0]), (-b[1], b[0] ) )b.sort( cmp= valueKeyCmp )print b The more general solution is actually two separate sorts b.sort( key=lambda a:a[1], reverse=True )b.sort( key=lambda a:a[0] )print b | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
157,429 | My team has been using SVN for a few years. We now have the option of switching to Perforce. What would be the benefits (and pitfalls) of making such a switch? | P4 keeps track of your working copy on the server. This means that Large working copies are processed much faster. I used to have a large SVN project and a simple update took 15 minutes because it had to create a tree of the local working copy (thousands of folders). File access is slow. P4 stores the information about the working copy in the database, so any operations were always near-instantaneous. If you mess around with your files and do not tell the server, you are in trouble! You cannot just delete a file - you have to delete a file with the P4 client so the server knows. Note that if you locally delete a file, it will not be downloaded again on successive updates because the server thinks you already have it! When lots of this happened and I ended up wildly out of sync, I usually had to resort to cleaning out my local copy and downloading it again, which could be time-consuming. You must be careful about this. The Explorer shell extension client (think TortoiseSVN) sucks and is completely unusable. There are two GUI client applications which offer the best functionality: P4Win and P4V, of which P4V is newer and more easy to use but not as feature-rich. There are Visual Studio and Eclipse plug-ins, which work relatively well, although they do not have many advanced features. Generally speaking, P4 offers much less features than SVN and is sometimes downright confusing. Working copy definitions were nice and flexible. I believe P4 is superior to SVN here: you can define masks for working copy folders and create all sorts of bizarre trees, so you download only what you want to exactly where you want, without having to manually futz with multiple checkouts. This came in very handy when I had gigabytes of stuff on the server and only wanted a specific subset of it. I used SVN in a similar situation with much more hassle. Branching under P4 is... odd. Branchsets and different kinds of branches and confusing UI. I do not remember much details about this, unfortunately. Other than that, it's pretty standard. I recommend you keep SVN unless you deal with huge codebases or hate the .svn folders littering up your filesystem. SVN+TortoiseSVN is far more confortable for most situations. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/157429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
]
} |
157,431 | I have created a Web Application in asp.net 2.0. which is working fine on my Local machine. However when trying to deploy it on sever that has windows 2003 sever, I get the error: Server Error in '/' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: The file '/MasterPage.master' does not exist. Source Error: Line 1: <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="LinkChecker Home " %>Line 2: <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">Line 3: Source File: /LinkChecker/Default.aspx Line : 1 Any idea how this can be fixed? | Is the folder on the web server (IIS presumably) marked as an ASP.NET application? If not, ~/ will point to the next application up, or the site root. It should have a cog icon in the IIS/MMC snap-in. Also ensure that it is running the right version of ASP.NET (v2.blah usually). In the IIS/MMC view, find the folder that is your project; right-click; Properties.Check it has an Application Name; if it doesn't, click Create. You might also want to tweak the app-pool if you want it to run in a different identity than default. Also check the ASP.NET tab - for example, it might be 2.0.50727. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6621/"
]
} |
157,480 | How can this line in Java be translated to Ruby: String className = "java.util.Vector"; ... Object o = Class.forName(className).newInstance(); Thanks! | Object::const_get('String').new() | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/157480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
157,511 | I have a Dictionary<string, someobject> . EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references in a loop but to update different values based on differnt threads need to update/get the data. I changed the loop to a method. I need to update items in my dictionary - one key at a time and i was wondering if there are any problems in using the lock on the .key value of my Dictionary object? private static Dictionary<string, MatrixElement> matrixElements = new Dictionary<string, MatrixElement>();//Pseudo-codepublic static void UpdateValue(string key){ KeyValuePair<string, MatrixElement> keyValuePair = matrixElements[key]; lock (keyValuePair.Key) { keyValuePair.Value = SomeMeanMethod(); }} Would that hold up in court or fail? I just want each value in the dictionary to be locked independantly so locking (and updating) one value does not lock the others. Also i'm aware the locking will be holding for a long time - but the data will be invalid untill updated fully. | Locking on an object that is accessible outside of the code locking it is a big risk. If any other code (anywhere) ever locks that object you could be in for some deadlocks that are hard to debug. Also note that you lock the object , not the reference, so if I gave you a dictionary, I may still hold references to the keys and lock on them - causing us to lock on the same object. If you completely encapsulate the dictionary, and generate the keys yourself (they aren't ever passed in, then you may be safe. However, try to stick to one rule - limit the visibility of the objects you lock on to the locking code itself whenever possible. That's why you see this: public class Something{ private readonly object lockObj = new object(); public SomethingReentrant() { lock(lockObj) // Line A { // ... } }} rather than seeing line A above replaced by lock(this) That way, a separate object is locked on, and the visibility is limited. Edit Jon Skeet correctly observed that lockObj above should be readonly. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11619/"
]
} |
157,546 | I have read that while plug-ins are not supported for SQL Server Management Studio, it can be done. Does anyone have any resources or advice on how to go about it using C#? A company that is currently offering plug-ins to Management Studio is Red Gate: http://www.red-gate.com/products/SQL_Refactor/index.htm | Here is a very good guide to creating a plugin for SQL Server Management Studio: http://blogs.microsoft.co.il/blogs/shair/archive/2008/07/28/how-to-create-sql-server-management-studio-addin.aspx Basically, it consists of the following: Create a Visual Studio add-in with certain settings. Subscribe to SSMS specific events Code The article includes a nice sample that you can use to skip some of the manual steps. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21829/"
]
} |
157,557 | In VB.Net, I can declare a variable in a function as Static, like this: Function EncodeForXml(ByVal data As String) As String Static badAmpersand As Regex = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&") ''// more processing return dataEnd Function Note that I need to use the keyword Static , rather than Shared , which is the normal way to express this in VB.Net. How can I do this in C#? I can't find its equivalent. | Ha! In posting the question, I found the answer! Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me. After applying that insight, I found this: http://weblogs.asp.net/psteele/articles/7717.aspx That article explains that it's not really supported by the CLR, and the VB compiler creates a static (shared) variable "under the hood" in the method's class. To do the same in C#, I have to create the variable myself. More than that, it uses the Monitor class to make sure the static member is thread-safe as well. Nice. As a side note: I'd expect to see this in C# sometime soon. The general tactic I've observed from MS is that it doesn't like VB.Net and C# to get too far apart feature-wise. If one language has a feature not supported by the other it tends to become a priority for the language team for the next version. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
157,600 | I would like to receive suggestions on the data generators that are available, for SQL server. If posting a response, please provide any features that you think are important. I have never used a application like this, so I am looking to be educated on the topic. Thank you. (My goal is to fill a database with 10,000+ records in each table, to test an application.) | I have used the data generator in the past. May be worth a look. 3rd party edit If you do not register you can only generate 100 rows. Below you can find a sample how the interface looks today (october 2016) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19854/"
]
} |
157,603 | I'm using VisualSVN Server to host an SVN repo, and for some automation work, I'd like to be able to get specific versions via the http[s] layer. I can get the HEAD version simply via an http[s] request to the server (httpd?) - but is there any ability to specify the revision, perhaps as a query-string? I can't seem to find it... I don't want to do a checkout unless I can help it, as there are a lot of files in the specific folder, and I don't want them all - just one or two. | Better late than never; https://entire/Path/To/Folder/file/?p=REV ?p=Rev specifies the revision | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/157603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23354/"
]
} |
157,646 | I was looking for a generic method in .Net to encode a string for use in an Xml element or attribute, and was surprised when I didn't immediately find one. So, before I go too much further, could I just be missing the built-in function? Assuming for a moment that it really doesn't exist, I'm putting together my own generic EncodeForXml(string data) method, and I'm thinking about the best way to do this. The data I'm using that prompted this whole thing could contain bad characters like &, <, ", etc. It could also contains on occasion the properly escaped entities: &, <, and ", which means just using a CDATA section may not be the best idea. That seems kinda klunky anyay; I'd much rather end up with a nice string value that can be used directly in the xml. I've used a regular expression in the past to just catch bad ampersands, and I'm thinking of using it to catch them in this case as well as the first step, and then doing a simple replace for other characters. So, could this be optimized further without making it too complex, and is there anything I'm missing? : Function EncodeForXml(ByVal data As String) As String Static badAmpersand As new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&") return data.Replace("<", "<").Replace("""", """).Replace(">", "gt;")End Function Sorry for all you C# -only folks-- I don't really care which language I use, but I wanted to make the Regex static and you can't do that in C# without declaring it outside the method, so this will be VB.Net Finally, we're still on .Net 2.0 where I work, but if someone could take the final product and turn it into an extension method for the string class, that'd be pretty cool too. Update The first few responses indicate that .Net does indeed have built-in ways of doing this. But now that I've started, I kind of want to finish my EncodeForXml() method just for the fun of it, so I'm still looking for ideas for improvement. Notably: a more complete list of characters that should be encoded as entities (perhaps stored in a list/map), and something that gets better performance than doing a .Replace() on immutable strings in serial. | Depending on how much you know about the input, you may have to take into account that not all Unicode characters are valid XML characters . Both Server.HtmlEncode and System.Security.SecurityElement.Escape seem to ignore illegal XML characters, while System.XML.XmlWriter.WriteString throws an ArgumentException when it encounters illegal characters (unless you disable that check in which case it ignores them). An overview of library functions is available here . Edit 2011/8/14: seeing that at least a few people have consulted this answer in the last couple years, I decided to completely rewrite the original code, which had numerous issues, including horribly mishandling UTF-16 . using System;using System.Collections.Generic;using System.IO;using System.Linq;/// <summary>/// Encodes data so that it can be safely embedded as text in XML documents./// </summary>public class XmlTextEncoder : TextReader { public static string Encode(string s) { using (var stream = new StringReader(s)) using (var encoder = new XmlTextEncoder(stream)) { return encoder.ReadToEnd(); } } /// <param name="source">The data to be encoded in UTF-16 format.</param> /// <param name="filterIllegalChars">It is illegal to encode certain /// characters in XML. If true, silently omit these characters from the /// output; if false, throw an error when encountered.</param> public XmlTextEncoder(TextReader source, bool filterIllegalChars=true) { _source = source; _filterIllegalChars = filterIllegalChars; } readonly Queue<char> _buf = new Queue<char>(); readonly bool _filterIllegalChars; readonly TextReader _source; public override int Peek() { PopulateBuffer(); if (_buf.Count == 0) return -1; return _buf.Peek(); } public override int Read() { PopulateBuffer(); if (_buf.Count == 0) return -1; return _buf.Dequeue(); } void PopulateBuffer() { const int endSentinel = -1; while (_buf.Count == 0 && _source.Peek() != endSentinel) { // Strings in .NET are assumed to be UTF-16 encoded [1]. var c = (char) _source.Read(); if (Entities.ContainsKey(c)) { // Encode all entities defined in the XML spec [2]. foreach (var i in Entities[c]) _buf.Enqueue(i); } else if (!(0x0 <= c && c <= 0x8) && !new[] { 0xB, 0xC }.Contains(c) && !(0xE <= c && c <= 0x1F) && !(0x7F <= c && c <= 0x84) && !(0x86 <= c && c <= 0x9F) && !(0xD800 <= c && c <= 0xDFFF) && !new[] { 0xFFFE, 0xFFFF }.Contains(c)) { // Allow if the Unicode codepoint is legal in XML [3]. _buf.Enqueue(c); } else if (char.IsHighSurrogate(c) && _source.Peek() != endSentinel && char.IsLowSurrogate((char) _source.Peek())) { // Allow well-formed surrogate pairs [1]. _buf.Enqueue(c); _buf.Enqueue((char) _source.Read()); } else if (!_filterIllegalChars) { // Note that we cannot encode illegal characters as entity // references due to the "Legal Character" constraint of // XML [4]. Nor are they allowed in CDATA sections [5]. throw new ArgumentException( String.Format("Illegal character: '{0:X}'", (int) c)); } } } static readonly Dictionary<char,string> Entities = new Dictionary<char,string> { { '"', """ }, { '&', "&"}, { '\'', "'" }, { '<', "<" }, { '>', ">" }, }; // References: // [1] http://en.wikipedia.org/wiki/UTF-16/UCS-2 // [2] http://www.w3.org/TR/xml11/#sec-predefined-ent // [3] http://www.w3.org/TR/xml11/#charsets // [4] http://www.w3.org/TR/xml11/#sec-references // [5] http://www.w3.org/TR/xml11/#sec-cdata-sect} Unit tests and full code can be found here . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/157646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
157,685 | I'm trying to change the background color of a single subplot in a MATLAB figure. It's clearly feasible since the UI allows it, but I cannot find the function to automate it. I've looked into whitebg , but it changes the color scheme of the whole figure, not just the current subplot. (I'm using MATLAB Version 6.1 by the way) | You can use the set command. set(subplot(2,2,1),'Color','Red') That will give you a red background in the subplot location 2,2,1. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8027/"
]
} |
157,717 | I'm a contract programmer with lots of experience. I'm used to being hired by a client to go in and do a software project of one form or another on my own, usually from nothing. That means a clean slate, almost every time. I can bring in libraries I've developed to get a quick start, but they're always optional. (and depend on getting the right IP clauses in the contract) Many times I can specify or even design the hardware platform... so we're talking serious freedom here. I can see uses for constructing automated tests for certain code: Libraries with more than trivial functionality, core functionality with a high number of references, etc. Basically, as the value of a piece of code goes up through heavy use, I can see it would be more and more valuable to automatically test that code so that I know I don't break it. However, in my situation , I find it hard to rationalize anything more than that. I'll adopt things as they prove useful, but I'm not about to blindly follow anything. I find many of the things I do in 'maintenance' are actually small design changes. In this case, the tests would not have saved me anything and now they'd have to change too. A highly iterative, stub-first design approach works very well for me. I can't see actually saving myself that much time with more extensive tests. Hobby projects are even harder to justify... they're usually anything from weekenders up to a say month long. Edge-case bugs rarely matter, it's all about playing with something. Reading questions such as this one , The most voted on response seems to say that in that poster's experience/opinion TDD actually wastes time if you've got less than 5 people (even assuming a certain level of competence/experience with TDD). However, that appears to be covering initial development time, not maintenance. It's not clear how TDD stacks up over the entire life cycle of a project. I think TDD could be a good step in the worthwhile goal of improving the quality of the products of our industry as a whole. Idealism on it's own is no longer all that effective at motivating me, though. I do think TDD would be a good approach in large teams, or any size team containing at least one unreliable programmer. That's not my question. Why would a sole developer with a good track record adopt TDD? I'd love to hear of any kind of metrics done (formally or not) on TDD... focusing on solo developers or very small teams. Failing that, anecdotes of your personal experiences would be nice, too. :) Please avoid stating opinion without experience to back it. Let's not make this an ideology war. Also the skip greater employment options argument. This is simply an efficiency question. | I'm not about to blindly follow anything. That's the right attitude. I use TDD all the time, but I don't adhere to it as strictly as some. The best argument (in my mind) in favor of TDD is that you get a set of tests you can run when you finally get to the refactoring and maintenance phases of your project. If this is your only reason for using TDD, then you can write the tests any time you want, instead of blindly following the methodology. The other reason I use TDD is that writing tests gets me thinking about my API up front. I'm forced to think about how I'm going to use a class before I write it. Getting my head into the project at this high level works for me. There are other ways to do this, and if you've found other methods (there are plenty) to do the same thing, then I'd say keep doing what works for you. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15896/"
]
} |
157,747 | I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script. For example, On Error Resume Next'Do Step 1'Do Step 2'Do Step 3 When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it? EDIT: Can I do something like this? On Error Resume myErrCatch'Do step 1'Do step 2'Do step 3myErrCatch:'log errorResume Next | VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation. On Error Resume NextDoStep1If Err.Number <> 0 Then WScript.Echo "Error in DoStep1: " & Err.Description Err.ClearEnd IfDoStep2If Err.Number <> 0 Then WScript.Echo "Error in DoStop2:" & Err.Description Err.ClearEnd If'If you no longer want to continue following an error after that block's completed,'call this.On Error Goto 0 The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/157747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6128/"
]
} |
157,759 | I have a program which needs to behave slightly differently on Tiger than on Leopard. Does anybody know of a system call which will allow me to accurately determine which version of Mac OS X I am running. I have found a number of macro definitions to determine the OS of the build machine, but nothing really good to determine the OS of the running machine. Thanks,Joe | See this article here But in short, if you're using carbon, use the Gestalt() call, and if you're using cocoa, there is a constant called NSAppKitVersionNumber which you can simply check against. Edit : For Mac OSX 10.8 and above, don't use Gestalt() anymore. See this answer for more details: How do I determine the OS version at runtime in OS X or iOS (without using Gestalt)? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7587/"
]
} |
157,770 | I'm trying to format a column in a <table/> using a <col/> element. I can set background-color , width , etc., but can't set the font-weight . Why doesn't it work? <table> <col style="font-weight:bold; background-color:#CCC;"> <col> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr></table> | As far as I know, you can only format the following using CSS on the <col> element: background-color border width visibility This page has more info. Herb is right - it's better to style the <td> 's directly. What I do is the following: <style type="text/css"> #mytable tr > td:first-child { color: red;} /* first column */ #mytable tr > td:first-child + td { color: green;} /* second column */ #mytable tr > td:first-child + td + td { color: blue;} /* third column */ </style> </head> <body> <table id="mytable"> <tr> <td>text 1</td> <td>text 2</td> <td>text 3</td> </tr> <tr> <td>text 4</td> <td>text 5</td> <td>text 6</td> </tr> </table> This won't work in IE however. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/157770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15788/"
]
} |
157,786 | I am looking for a way in LINQ to match the follow SQL Query. Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number Really looking for some help on this one. The above query gets the max uid of each Serial Number because of the Group By Syntax. | using (DataContext dc = new DataContext()) { var q = from t in dc.TableTests group t by t.SerialNumber into g select new { SerialNumber = g.Key, uid = (from t2 in g select t2.uid).Max() }; } | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/157786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
]
} |
157,807 | If you have an API, and you are a UK-based developer with a highly international audience, should your API be setColour() or setColor() (To take one word as a simple example.) UK-based engineers are often quite defensive about their 'correct' spellings but it could be argued that US spelling is more 'standard' in the international market. I guess the question is does it matter? Do developers in other locales struggle with GB spelling, or is it normally quite apparent what things mean? Should it all be US-English? | I would tend to use US-English as that has become the norm in other APIs. Speaking as an English programmer, I don't have any problem using "color", for example. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/157807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
]
} |
157,832 | This is sort of SQL newbie question, I think, but here goes. I have a SQL Query (SQL Server 2005) that I've put together based on an example user-defined function: SELECT CASEID, GetNoteText(CASEID)FROM ( SELECT CASEID FROM ATTACHMENTS GROUP BY CASEID ) iGO the UDF works great (it concatenates data from multiple rows in a related table, if that matters at all) but I'm confused about the "i" after the FROM clause. The query works fine with the i but fails without it. What is the significance of the "i"? EDIT: As Joel noted below, it's not a keyword | When you use a subquery in the FROM clause, you need to give the query a name. Since the name doesn't really matter to you, something simple like 'i' or 'a' is often chosen. But you could put any name there you wanted- there's no significance to 'i' all by itself, and it's certainly not a keyword. If you have a really complex query, you may need to join your sub query with other queries or tables. In that case the name becomes more important and you should choose something more meaningful. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8151/"
]
} |
157,873 | I'm having a test hang in our rails app can't figure out which one (since it hangs and doesn't get to the failure report). I found this blog post http://bmorearty.wordpress.com/2008/06/18/find-tests-more-easily-in-your-testlog/ which adds a setup hook to print the test name but when I try to do the same thing it gives me an error saying wrong number of arguments for setup (1 for 0). Any help at all would be appreciated. | If you run test using rake it will work: rake test:units TESTOPTS="-v" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/157873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3041/"
]
} |
157,924 | I've got a situation where I need to use LINQ's ExecuteCommand method to run an insert. Something like (simplified for purposes of this question): object[] oParams = { Guid.NewGuid(), rec.WebMethodID };TransLogDataContext.ExecuteCommand ("INSERT INTO dbo.Transaction_Log (ID, WebMethodID) VALUES ({0}, {1})",oParams); The question is if this is SQL injection proof in the same way parameterized queries are? | Did some research, and I found this: In my simple testing, it looks like the parameters passed in the ExecuteQuery and ExecuteCommand methods are automatically SQL encoded based on the value being supplied. So if you pass in a string with a ' character, it will automatically SQL escape it to ''. I believe a similar policy is used for other data types like DateTimes, Decimals, etc. http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx (You have scroll way down to find it) This seems a little odd to me - most other .Net tools know better than to "SQL escape" anything; they use real query parameters instead. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/157924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
]
} |
157,933 | I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object: public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>{ private readonly object syncRoot = new object(); private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>(); public object SyncRoot { get { return syncRoot; } } public void Add(TKey key, TValue value) { lock (syncRoot) { d.Add(key, value); } } // more IDictionary members...} I then lock on this SyncRoot object throughout my consumers (multiple threads): Example: lock (m_MySharedDictionary.SyncRoot){ m_MySharedDictionary.Add(...);} I was able to make it work, but this resulted in some ugly code. My question is, is there a better, more elegant way of implementing a thread-safe Dictionary? | The .NET 4.0 class that supports concurrency is named ConcurrentDictionary . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/157933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5563/"
]
} |
157,938 | I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? | Base64 encoding is in the standard library and will do to stop shoulder surfers: >>> import base64>>> print(base64.b64encode("password".encode("utf-8")))cGFzc3dvcmQ=>>> print(base64.b64decode("cGFzc3dvcmQ=").decode("utf-8"))password | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/157938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3056/"
]
} |
157,944 | Given an array of type Element[] : Element[] array = {new Element(1), new Element(2), new Element(3)}; How do I convert this array into an object of type ArrayList<Element> ? ArrayList<Element> arrayList = ???; | new ArrayList<>(Arrays.asList(array)); | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/157944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939/"
]
} |
157,959 | When I ssh into a remote production server I would like the colour scheme of my terminal window to change to something brigh and scary, preferably red, to warn me that I am touching a live scary server. How can I make it automatically detect that I have ssh'ed somewhere, and if that somewhere is on a specific list, change the colour scheme? I want to update the Scheme of Terminal.app, not know how I would do this in a pure linux/unix env | Put following script in ~/bin/ssh (ensure ~/bin/ is checked before /usr/bin/ in your PATH): #!/bin/shHOSTNAME=`echo $@ | sed s/.*@//`set_bg () { osascript -e "tell application \"Terminal\" to set background color of window 1 to $1"}on_exit () { set_bg "{0, 0, 0, 50000}"}trap on_exit EXITcase $HOSTNAME in production1|production2|production3) set_bg "{45000, 0, 0, 50000}" ;; *) set_bg "{0, 45000, 0, 50000}" ;;esac/usr/bin/ssh "$@" Remember to make the script executable by running chmod +x ~/bin/ssh The script above extracts host name from line "username@host" (it assumes you login to remote hosts with "ssh user@host"). Then depending on host name it either sets red background (for production servers) or green background (for all other). As a result all your ssh windows will be with colored background. I assume here your default background is black, so script reverts the background color back to black when you logout from remote server (see "trap on_exit"). Please, note however this script does not track chain of ssh logins from one host to another. As a result the background will be green in case you login to testing server first, then login to production from it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/157959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
]
} |
158,044 | How do I use the UNIX command find to search for files created on a specific date? | As pointed out by Max, you can't, but checking files modified or accessed is not all that hard. I wrote a tutorial about this, as late as today. The essence of which is to use -newerXY and ! -newerXY : Example: To find all files modified on the 7th of June, 2007: $ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08 To find all files accessed on the 29th of september, 2008: $ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30 Or, files which had their permission changed on the same day: $ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30 If you don't change permissions on the file, 'c' would normally correspond to the creation date, though. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/158044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/473/"
]
} |
158,055 | I am trying to use TemplateToolkit instead of good ole' variable interpolation and my server is giving me a lot of grief. Here are the errors I am getting: *** 'D:\Inetpub\gic\source\extjs_source.plx' error message at: 2008/09/30 15:27:37 failed to create context: failed to create context: failed to load Template/Stash/XS.pm: Couldn't load Template::Stash::XS 2.20:Can't load 'D:/Perl/site/lib/auto/Template/Stash/XS/XS.dll' for module Template::Stash::XS: load_file:The specified procedure could not be found at D:/Perl/lib/DynaLoader.pm line 230. at D:/Perl/site/lib/Template/Stash/XS.pm line 31BEGIN failed--compilation aborted at D:/Perl/site/lib/Template/Stash/XS.pm line 31. Compilation failed in require at D:/Perl/site/lib/Template/Config.pm line 82. The Platform is Windows Server 2003 and we are using ActiveState perl and PPM for the packages with IIS. | I figured this one out after a long time. Apparently the ActiveState people didn't check much into the package because it requires Template::Stash::XS, but that's not actually available in PPM. To fix this issue just edit the Template/Config.pm and change Template::Stash::XS to Template::Stash. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
]
} |
158,070 | I have a hidden DIV which contains a toolbar-like menu. I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them. Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like $(menu).position("topright", targetEl); | tl;dr: (try it here ) If you have the following HTML: <div id="menu" style="display: none;"> <!-- menu stuff in here --> <ul><li>Menu item</li></ul></div><div class="parent">Hover over me to show the menu here</div> then you can use the following JavaScript code: $(".parent").mouseover(function() { // .position() uses position relative to the offset parent, var pos = $(this).position(); // .outerWidth() takes into account border and padding. var width = $(this).outerWidth(); //show the menu directly over the placeholder $("#menu").css({ position: "absolute", top: pos.top + "px", left: (pos.left + width) + "px" }).show();}); But it doesn't work! This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the #menu element is, use: $(this).append($("#menu")); just before the line that positions the #menu element. But it still doesn't work! You might have some weird layout that doesn't work with this approach. In that case, just use jQuery.ui's position plugin (as mentioned in an answer below), which handles every conceivable eventuality. Note that you'll have to show() the menu element before calling position({...}) ; the plugin can't position hidden elements. Update notes 3 years later in 2012: (The original solution is archived here for posterity) So, it turns out that the original method I had here was far from ideal. In particular, it would fail if: the menu's offset parent is not the placeholder's offset parent the placeholder has a border/padding Luckily, jQuery introduced methods ( position() and outerWidth() ) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, append ing the menu element to the placeholder works (but will break CSS rules based on nesting). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/158070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11249/"
]
} |
158,124 | It's surprising how difficult it is to find a simple, concise answer to this question: I have a file, foo.zip, on my website What can I do to find out how many people have accessed this file? I could use Tomcat calls if necessary | Or you could parse the log file if you don't need the data in realtime. grep foo.zip /path/to/access.log | grep 200 | wc -l In reply to comment: The log file also contains bytes downloaded, but as someone else pointed out, this may not reflect the correct count if a user cancels the download on the client side. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197/"
]
} |
158,133 | They both seem to fulfill the same purpose. When would I chose one over the other? | Use the events when you've got a thread that is waiting on one of or all of a number of events to do something. Use the monitor if you want to restrict access to a data structure by limiting how many threads can access it. Monitors usually protect a resource, whereas events tell you something's happening, like the application shutting down. Also, events can be named (see the OpenExisting method), this allows them to be used for synchronization across different processes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
158,151 | Is there a one button way to save a screenshot directly to a file in Windows? TheSoftwareJedi accurately answered above question for Windows 8 and 10. Below original extra material remains for posterity. This is a very important question as the 316K views shows as of 2021.Asked in 2008, SO closed this question around 2015 as being off-topic,probably because of the last question below. In Windows XP, one can press Alt-PrintScreen to copy an image of theactive window, or Ctrl-PrintScreen to copy an image of the fulldesktop. This can then be pasted into applications that accept images:Photoshop, Microsoft Word, etc. I'm wondering: Is there a way to save the screenshot directly to afile? Do I really have to open an image program, likePaint.net or Photoshop, simply to paste an image, then save it? | You can code something pretty simple that will hook the PrintScreen and save the capture in a file. Here is something to start to capture and save to a file. You will just need to hook the key "Print screen". using System;using System.Drawing;using System.IO;using System.Drawing.Imaging;using System.Runtime.InteropServices;public class CaptureScreen{ static public void Main(string[] args) { try { Bitmap capture = CaptureScreen.GetDesktopImage(); string file = Path.Combine(Environment.CurrentDirectory, "screen.gif"); ImageFormat format = ImageFormat.Gif; capture.Save(file, format); } catch (Exception e) { Console.WriteLine(e); } } public static Bitmap GetDesktopImage() { WIN32_API.SIZE size; IntPtr hDC = WIN32_API.GetDC(WIN32_API.GetDesktopWindow()); IntPtr hMemDC = WIN32_API.CreateCompatibleDC(hDC); size.cx = WIN32_API.GetSystemMetrics(WIN32_API.SM_CXSCREEN); size.cy = WIN32_API.GetSystemMetrics(WIN32_API.SM_CYSCREEN); m_HBitmap = WIN32_API.CreateCompatibleBitmap(hDC, size.cx, size.cy); if (m_HBitmap!=IntPtr.Zero) { IntPtr hOld = (IntPtr) WIN32_API.SelectObject(hMemDC, m_HBitmap); WIN32_API.BitBlt(hMemDC, 0, 0,size.cx,size.cy, hDC, 0, 0, WIN32_API.SRCCOPY); WIN32_API.SelectObject(hMemDC, hOld); WIN32_API.DeleteDC(hMemDC); WIN32_API.ReleaseDC(WIN32_API.GetDesktopWindow(), hDC); return System.Drawing.Image.FromHbitmap(m_HBitmap); } return null; } protected static IntPtr m_HBitmap;}public class WIN32_API{ public struct SIZE { public int cx; public int cy; } public const int SRCCOPY = 13369376; public const int SM_CXSCREEN=0; public const int SM_CYSCREEN=1; [DllImport("gdi32.dll",EntryPoint="DeleteDC")] public static extern IntPtr DeleteDC(IntPtr hDc); [DllImport("gdi32.dll",EntryPoint="DeleteObject")] public static extern IntPtr DeleteObject(IntPtr hDc); [DllImport("gdi32.dll",EntryPoint="BitBlt")] public static extern bool BitBlt(IntPtr hdcDest,int xDest,int yDest,int wDest,int hDest,IntPtr hdcSource,int xSrc,int ySrc,int RasterOp); [DllImport ("gdi32.dll",EntryPoint="CreateCompatibleBitmap")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport ("gdi32.dll",EntryPoint="CreateCompatibleDC")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport ("gdi32.dll",EntryPoint="SelectObject")] public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp); [DllImport("user32.dll", EntryPoint="GetDesktopWindow")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll",EntryPoint="GetDC")] public static extern IntPtr GetDC(IntPtr ptr); [DllImport("user32.dll",EntryPoint="GetSystemMetrics")] public static extern int GetSystemMetrics(int abc); [DllImport("user32.dll",EntryPoint="GetWindowDC")] public static extern IntPtr GetWindowDC(Int32 ptr); [DllImport("user32.dll",EntryPoint="ReleaseDC")] public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDc);} Update Here is the code to hook the PrintScreen (and other key) from C#: Hook code | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/158151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197/"
]
} |
158,172 | I have some decimal data that I am pushing into a SharePoint list where it is to be viewed. I'd like to restrict the number of significant figures displayed in the result data based on my knowledge of the specific calculation. Sometimes it'll be 3, so 12345 will become 12300 and 0.012345 will become 0.0123. Occasionally it will be 4 or 5. Is there any convenient way to handle this? | See: RoundToSignificantFigures by "P Daddy". I've combined his method with another one I liked. Rounding to significant figures is a lot easier in TSQL where the rounding method is based on rounding position, not number of decimal places - which is the case with .Net math.round. You could round a number in TSQL to negative places, which would round at whole numbers - so the scaling isn't needed. Also see this other thread . Pyrolistical's method is good. The trailing zeros part of the problem seems like more of a string operation to me, so I included a ToString() extension method which will pad zeros if necessary. using System;using System.Globalization;public static class Precision{ // 2^-24 public const float FLOAT_EPSILON = 0.0000000596046448f; // 2^-53 public const double DOUBLE_EPSILON = 0.00000000000000011102230246251565d; public static bool AlmostEquals(this double a, double b, double epsilon = DOUBLE_EPSILON) { // ReSharper disable CompareOfFloatsByEqualityOperator if (a == b) { return true; } // ReSharper restore CompareOfFloatsByEqualityOperator return (System.Math.Abs(a - b) < epsilon); } public static bool AlmostEquals(this float a, float b, float epsilon = FLOAT_EPSILON) { // ReSharper disable CompareOfFloatsByEqualityOperator if (a == b) { return true; } // ReSharper restore CompareOfFloatsByEqualityOperator return (System.Math.Abs(a - b) < epsilon); }}public static class SignificantDigits{ public static double Round(this double value, int significantDigits) { int unneededRoundingPosition; return RoundSignificantDigits(value, significantDigits, out unneededRoundingPosition); } public static string ToString(this double value, int significantDigits) { // this method will round and then append zeros if needed. // i.e. if you round .002 to two significant figures, the resulting number should be .0020. var currentInfo = CultureInfo.CurrentCulture.NumberFormat; if (double.IsNaN(value)) { return currentInfo.NaNSymbol; } if (double.IsPositiveInfinity(value)) { return currentInfo.PositiveInfinitySymbol; } if (double.IsNegativeInfinity(value)) { return currentInfo.NegativeInfinitySymbol; } int roundingPosition; var roundedValue = RoundSignificantDigits(value, significantDigits, out roundingPosition); // when rounding causes a cascading round affecting digits of greater significance, // need to re-round to get a correct rounding position afterwards // this fixes a bug where rounding 9.96 to 2 figures yeilds 10.0 instead of 10 RoundSignificantDigits(roundedValue, significantDigits, out roundingPosition); if (Math.Abs(roundingPosition) > 9) { // use exponential notation format // ReSharper disable FormatStringProblem return string.Format(currentInfo, "{0:E" + (significantDigits - 1) + "}", roundedValue); // ReSharper restore FormatStringProblem } // string.format is only needed with decimal numbers (whole numbers won't need to be padded with zeros to the right.) // ReSharper disable FormatStringProblem return roundingPosition > 0 ? string.Format(currentInfo, "{0:F" + roundingPosition + "}", roundedValue) : roundedValue.ToString(currentInfo); // ReSharper restore FormatStringProblem } private static double RoundSignificantDigits(double value, int significantDigits, out int roundingPosition) { // this method will return a rounded double value at a number of signifigant figures. // the sigFigures parameter must be between 0 and 15, exclusive. roundingPosition = 0; if (value.AlmostEquals(0d)) { roundingPosition = significantDigits - 1; return 0d; } if (double.IsNaN(value)) { return double.NaN; } if (double.IsPositiveInfinity(value)) { return double.PositiveInfinity; } if (double.IsNegativeInfinity(value)) { return double.NegativeInfinity; } if (significantDigits < 1 || significantDigits > 15) { throw new ArgumentOutOfRangeException("significantDigits", value, "The significantDigits argument must be between 1 and 15."); } // The resulting rounding position will be negative for rounding at whole numbers, and positive for decimal places. roundingPosition = significantDigits - 1 - (int)(Math.Floor(Math.Log10(Math.Abs(value)))); // try to use a rounding position directly, if no scale is needed. // this is because the scale mutliplication after the rounding can introduce error, although // this only happens when you're dealing with really tiny numbers, i.e 9.9e-14. if (roundingPosition > 0 && roundingPosition < 16) { return Math.Round(value, roundingPosition, MidpointRounding.AwayFromZero); } // Shouldn't get here unless we need to scale it. // Set the scaling value, for rounding whole numbers or decimals past 15 places var scale = Math.Pow(10, Math.Ceiling(Math.Log10(Math.Abs(value)))); return Math.Round(value / scale, significantDigits, MidpointRounding.AwayFromZero) * scale; }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
]
} |
158,174 | I've been reading through a lot of the rookie Java questions on finalize() and find it kind of bewildering that no one has really made it plain that finalize() is an unreliable way to clean up resources. I saw someone comment that they use it to clean up Connections, which is really scary since the only way to come as close to a guarantee that a Connection is closed is to implement try (catch) finally. I was not schooled in CS, but I have been programming in Java professionally for close to a decade now and I have never seen anyone implement finalize() in a production system ever. This still doesn't mean that it doesn't have its uses, or that people I've worked with have been doing it right. So my question is, what use cases are there for implementing finalize() that cannot be handled more reliably via another process or syntax within the language? Please provide specific scenarios or your experience, simply repeating a Java text book, or finalize's intended use is not enough, as is not the intent of this question. | You could use it as a backstop for an object holding an external resource (socket, file, etc). Implement a close() method and document that it needs to be called. Implement finalize() to do the close() processing if you detect it hasn't been done. Maybe with something dumped to stderr to point out that you're cleaning up after a buggy caller. It provides extra safety in an exceptional/buggy situation. Not every caller is going to do the correct try {} finally {} stuff every time. Unfortunate, but true in most environments. I agree that it's rarely needed. And as commenters point out, it comes with GC overhead. Only use if you need that "belt and suspenders" safety in a long-running app. I see that as of Java 9, Object.finalize() is deprecated! They point us to java.lang.ref.Cleaner and java.lang.ref.PhantomReference as alternatives. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/158174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8528/"
]
} |
158,189 | This page mentions how to trunc a timestamp to minutes/hours/etc. in Oracle. How would you trunc a timestamp to seconds in the same manner? | Since the precision of DATE is to the second (and no fractions of seconds), there is no need to TRUNC at all. The data type TIMESTAMP allows for fractions of seconds. If you convert it to a DATE the fractional seconds will be removed - e.g. select cast(systimestamp as date) from dual; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
]
} |
158,209 | curious if anyone might have some insight in how I would do the following to a binary number: convert 01+0 -> 10+1 (+ as in regular expressions, one or more) 01 -> 10 10 -> 01 so, 1010100001010001110001010100101010100010 and to clarify that this isn't a simple inversion: 000000100000000000000001010000000000 I was thinking regex, but I'm working with binary numbers and want to stay that way. The bit twiddling hacks page hasn't given me any insight either. This clearly has some essence of cellular automata. So, anyone have a few bit operations that can take care of this? (no code is necessary, I know how to do that). | Let's say x is your variable. Then you'd have: unsigned myBitOperation(unsigned x){ return ((x<<1) | (x>>1)) & (~x);} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157/"
]
} |
158,232 | After following the instructions in INSTALL.W64 I have two problems: The code is still written to the "out32" folder. I need to be able to link to both 32-bit and 64-bit versions of the library on my workstation, so I don't want the 64-bit versions to clobber the 32-bit libs. The output is still 32-bit! This means that I get "unresolved external symbol" errors when trying to link to the libraries from an x64 app. | To compile the static libraries (both release and debug), this is what you need to do: Install Perl - www.activestate.com Run the "Visual Studio 2008 x64 Cross Tools Command Prompt" (Note: The regular command prompt WILL NOT WORK.) Configure withperl Configure VC-WIN64A no-shared no-idea Run: ms\do_win64a EDIT ms\nt.mak and change "32" to "64" in the output dirs: # The output directory for everything intersting OUT_D=out64.dbg # The output directory for all the temporary muck TMP_D=tmp64.dbg # The output directory for the header files INC_D=inc64 INCO_D=inc64\openssl EDIT ms\nt.mak and remove bufferoverflowu.lib from EX_LIBS if you get an error about it. Run: nmake -f ms\nt.mak EDIT the ms\do_win64a file and ADD "debug" to all lines, except the "ml64" and the last two lines Run: ms\do_win64a Repeat steps 4 and 5 EDIT the ms\nt.mak file and ADD /Zi to the CFLAG list! Run: nmake -f ms\nt.mak | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21784/"
]
} |
158,241 | What I want to do is to remove all accents and umlauts from a string, turning "lärm" into "larm" or "andré" into "andre". What I tried to do was to utf8_decode the string and then use strtr on it, but since my source file is saved as UTF-8 file, I can't enter the ISO-8859-15 characters for all umlauts - the editor inserts the UTF-8 characters. Obviously a solution for this would be to have an include that's an ISO-8859-15 file, but there must be a better way than to have another required include? echo strtr(utf8_decode($input), 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy'); UPDATE: Maybe I was a bit inaccurate with what I try to do: I do not actually want to remove the umlauts, but to replace them with their closest "one character ASCII" equivalent. | iconv("utf-8","ascii//TRANSLIT",$input); Extended example | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/158241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999/"
]
} |
158,268 | Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CPerson list of every one in the room. The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room. The problem is with the two modules importing each other I just get an import error on which ever is being imported second :( In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg: class CPerson;//forward declareclass CRoom{ std::set<CPerson*> People; ... Is there anyway to do this in python, other than placing both classes in the same module or something like that? edit: added python example showing problem using above classes error: Traceback (most recent call last): File "C:\Projects\python\test\main.py", line 1, in from room import CRoom File "C:\Projects\python\test\room.py", line 1, in from person import CPerson File "C:\Projects\python\test\person.py", line 1, in from room import CRoom ImportError: cannot import name CRoom room.py from person import CPersonclass CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] person.py from room import CRoomclass CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) | No need to import CRoom You don't use CRoom in person.py , so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time". If you actually do use CRoom in person.py , then change from room import CRoom to import room and use module-qualified form room.CRoom . See Effbot's Circular Imports for details. Sidenote: you probably have an error in Self.NextId += 1 line. It increments NextId of instance, not NextId of class. To increment class's counter use CRoom.NextId += 1 or Self.__class__.NextId += 1 . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
]
} |
158,319 | For all major browsers (except IE), the JavaScript onload event doesn’t fire when the page loads as a result of a back button operation — it only fires when the page is first loaded. Can someone point me at some sample cross-browser code (Firefox, Opera, Safari, IE, …) that solves this problem? I’m familiar with Firefox’s pageshow event but unfortunately neither Opera nor Safari implement this. | Guys, I found that JQuery has only one effect: the page is reloaded when the back button is pressed. This has nothing to do with " ready ". How does this work? Well, JQuery adds an onunload event listener. // http://code.jquery.com/jquery-latest.jsjQuery(window).bind("unload", function() { // ... By default, it does nothing. But somehow this seems to trigger a reload in Safari, Opera and Mozilla -- no matter what the event handler contains. [ edit(Nickolay) : here's why it works that way: webkit.org , developer.mozilla.org . Please read those articles (or my summary in a separate answer below) and consider whether you really need to do this and make your page load slower for your users.] Can't believe it? Try this: <body onunload=""><!-- This does the trick --><script type="text/javascript"> alert('first load / reload'); window.onload = function(){alert('onload')};</script><a href="http://stackoverflow.com">click me, then press the back button</a></body> You will see similar results when using JQuery. You may want to compare to this one without onunload <body><!-- Will not reload on back button --><script type="text/javascript"> alert('first load / reload'); window.onload = function(){alert('onload')};</script><a href="http://stackoverflow.com">click me, then press the back button</a></body> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/158319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24190/"
]
} |
158,336 | I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml. Is there a way to run a method/class only on Tomcat startup? | You could write a ServletContextListener which calls your method from the contextInitialized() method. You attach the listener to your webapp in web.xml, e.g. <listener> <listener-class>my.Listener</listener-class></listener> and package my;public class Listener implements javax.servlet.ServletContextListener { public void contextInitialized(ServletContext context) { MyOtherClass.callMe(); }} Strictly speaking, this is only run once on webapp startup, rather than Tomcat startup, but that may amount to the same thing. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/158336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23968/"
]
} |
158,371 | I have recently inherited a couple of applications that run as windows services, and I am having problems providing a gui (accessible from a context menu in system tray) with both of them. The reason why we need a gui for a windows service is in order to be able to re-configure the behaviour of the windows service(s) without resorting to stopping/re-starting. My code works fine in debug mode, and I get the context menu come up, and everything behaves correctly etc. When I install the service via "installutil" using a named account (i.e., not Local System Account), the service runs fine, but doesn't display the icon in the system tray (I know this is normal behavior because I don't have the "interact with desktop" option). Here is the problem though - when I choose the "LocalSystemAccount" option, and check the "interact with desktop" option, the service takes AGES to start up for no obvious reason, and I just keep getting Could not start the ... service on Local Computer. Error 1053: the service did not respond to the start or control request in a timely fashion. Incidentally, I increased the windows service timeout from the default 30 seconds to 2 minutes via a registry hack (see http://support.microsoft.com/kb/824344 , search for TimeoutPeriod in section 3), however the service start up still times out. My first question is - why might the "Local System Account" login takes SOOOOO MUCH LONGER than when the service logs in with the non-LocalSystemAccount, causing the windows service time-out? what's could the difference be between these two to cause such different behavior at start up? Secondly - taking a step back, all I'm trying to achieve, is simply a windows service that provides a gui for configuration - I'd be quite happy to run using the non-Local System Account (with named user/pwd), if I could get the service to interact with the desktop (that is, have a context menu available from the system tray). Is this possible, and if so how? Any pointers to the above questions would be appreciated! | After fighting this message for days, a friend told me that you MUST use the Release build. When I InstallUtil the Debug build, it gives this message. The Release build Starts fine. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24175/"
]
} |
158,375 | I want to clear the Firebug console of the JavaScript already sent. Does something like console.clear() exist and work? | console.clear(); works for me | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24197/"
]
} |
158,384 | If I use mod_rewrite to control all my 301 redirects, does this happen before my page is served? so if I also have a bunch of redirect rules in a php script that runs on my page, will the .htaccess kick in first? | When a request is made to the URI affected by the .htaccess file, then Apache will handle any rewrite rules before any of your PHP code executes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24200/"
]
} |
158,388 | I have a little program that I want to make open automatically when my mac is started up. Because this program accepts command line arguments, its not as simple as just going to System Prefs/Accounts/Login items and adding it there... From google, I read that I can create a .profile file in my user's home folder, and that will execute whatever I put in it... So I have a .profile page in ~ like this: -rw-r--r--@ 1 matt staff 27 27 Sep 13:36 .profile That contains this... /Applications/mousefix 3.5 But it doesn't execute on startup! If I enter "/Applications/mousefix 3.5" manually into the terminal, it does work. Any ideas? | From here and into the future, look into launchd for what you want to do. All other methods have been deprecated or are now unsupported. This is probably a bit more heavy-weight than what you want, though. It could also be a problem with your version of the bash shell not correctly executing your .profile . Try putting the command into .bashrc in your home directory, and see if that helps. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24109/"
]
} |
158,392 | I'm currently designing a brand new database. In school, we always learned to put a primary key in each table. I read a lot of articles/discussions/newsgroups posts saying that it's better to use unique constraint (aka unique index for some db) instead of PK. What's your point of view? | Can you provide references to these articles? I see no reason to change the tried and true methods. After all, Primary Keys are a fundamental design feature of relational databases. Using UNIQUE to serve the same purpose sounds really hackish to me. What is their rationale? Edit: My attention just got drawn back to this old answer. Perhaps the discussion that you read regarding PK vs. UNIQUE dealt with people making something a PK for the sole purpose of enforcing uniqueness on it. The answer to this is, If it IS a key, then make it key, otherwise make it UNIQUE. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17766/"
]
} |
158,457 | So I have a daemon running on a Linux system, and I want to have a record of its activities: a log. The question is, what is the "best" way to accomplish this? My first idea is to simply open a file and write to it. FILE* log = fopen("logfile.log", "w");/* daemon works...needs to write to log */fprintf(log, "foo%s\n", (char*)bar);/* ...all done, close the file */fclose(log); Is there anything inherently wrong with logging this way? Is there a better way, such as some framework built into Linux? | Unix has had for a long while a special logging framework called syslog . Type in your shell man 3 syslog and you'll get the help for the C interface to it. Some examples #include <stdio.h>#include <unistd.h>#include <syslog.h>int main(void) { openlog("slog", LOG_PID|LOG_CONS, LOG_USER); syslog(LOG_INFO, "A different kind of Hello world ... "); closelog(); return 0;} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/158457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12926/"
]
} |
158,474 | Supposedly, it is possible to get this from Google Maps or some such service. (US addresses only is not good enough.) | The term you're looking for is geocoding and yes Google does provide this service. New V3 API : http://code.google.com/apis/maps/documentation/geocoding/ Old V2 API: http://code.google.com/apis/maps/documentation/services.html#Geocoding | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/158474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18651/"
]
} |
158,479 | I have a PDF file, which contains data that we need to import into a database. The files seem to be pdf scans of printed alphanumeric text. Looks like 10 pt. Times New Roman. Are there any tools or components that can will allow me to recognize and parse this text? | I've used pdftohtml to successfully strip tables out of PDF into CSV. It's based on Xpdf , which is a more general purpose tool, that includes pdftotext . I just wrap it as a Process.Start call from C#. If you're looking for something a little more DIY, there's the iTextSharp library - a port of Java's iText - and PDFBox (yes, it says Java - but they have a .NET version by way of IKVM.NET ). Here's some CodeProject articles on using iTextSharp and PDFBox from C#. And, if you're really a masochist, you could call into Adobe's PDF IFilter with COM interop. The IFilter specs is pretty simple, but I would guess that the interop overhead would be significant. Edit: After re-reading the question and subsequent answers, it's become clear that the OP is dealing with images in his PDF. In that case, you'll need to extract the images (the PDF libraries above are able to do that fairly easily) and run it through an OCR engine. I've used MODI interactively before, with decent results. It's COM, so calling it from C# via interop is also doable and pretty simple : ' lifted from http://en.wikipedia.org/wiki/Microsoft_Office_Document_ImagingDim inputFile As String = "C:\test\multipage.tif"Dim strRecText As String = ""Dim Doc1 As MODI.DocumentDoc1 = New MODI.DocumentDoc1.Create(inputFile)Doc1.OCR() ' this will ocr all pages of a multi-page tiff fileDoc1.Save() ' this will save the deskewed reoriented images, and the OCR text, back to the inputFileFor imageCounter As Integer = 0 To (Doc1.Images.Count - 1) ' work your way through each page of results strRecText &= Doc1.Images(imageCounter).Layout.Text ' this puts the ocr results into a stringNextFile.AppendAllText("C:\test\testmodi.txt", strRecText) ' write the OCR file out to diskDoc1.Close() ' clean upDoc1 = Nothing Others like Tesseract , but I have direct experience with it. I've heard both good and bad things about it, so I imagine it greatly depends on your source quality. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24204/"
]
} |
158,514 | According to the manual , git dcommit “will create a revision in SVN for each commit in git.” But is there a way to avoid multiple Subversion revisions? That is, to have git merge all changes prior to performing the svn commit ? | If you work on a branch in git, you can git-merge --squash , which does that within git. You could then push that one squashed commit to SVN. Of course, lots of small commits are good, so why would you want to squash them? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446328/"
]
} |
158,539 | break line tag is not working in firefox, neither in chrome. When i see the source of my page i get: <p>Zugang zu Testaccount:</br></br>peter petrelli </br></br>sein Standardpwd.</br></br>peter.heroes.com</p> However when i do view selected source, i get: <p>Zugang zu Testaccount: peter petrelli sein Standardpwd. peter.heroes.com</p> It seems firefox is filtering break line tags out. It works in IE7 fine. | You're looking for <br /> instead of </br> Self closing tags such as br have the slash at the end of the tag. Here are the other self-closing tags in XHTML: What are all the valid self-closing tags in XHTML (as implemented by the major browsers)? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/158539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
} |
158,546 | I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up. What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option? | If you create a dictionary.py module, containing code which reads the file and builds a dictionary, this code will only be executed the first time it is imported. Further imports will return a reference to the existing module instance. As such, your classes can: import dictionarydictionary.words[whatever] where dictionary.py has: words = {}# read file and add to 'words' | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24208/"
]
} |
158,557 | I've seen that it's possible to get the latitude and longitude (geocoding, like in Google Maps API ) from a street address, but is it possible to do the reverse and get the street address when you know what the lat/long already is? The application would be an iPhone app (and why the app already knows lat/long), so anything from a web service to an iPhone API would work. | Google again http://nicogoeminne.googlepages.com/documentation.html http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
]
} |
158,568 | I have a temporary file with data that's returned as part of a SOAP response via a MTOM binary attachment. I would like to trash it as soon as the method call "ends" (i.e., finishes transferring). What's the best way for me to do this? The best way I can figure out how to do this is to delete them when the session is destroyed, but I'm not sure if there's a more 'immediate' way to do this. FYI, I'm NOT using Axis, I'm using jax-ws, if that matters. UPDATE: I'm not sure the answerers are really understanding the issue. I know how to delete a file in java. My problem is this: @javax.jws.WebService public class MyWebService {... @javax.jws.WebMethod public MyFileResult getSomeObject() { File mytempfile = new File("tempfile.txt"); MyFileResult result = new MyFileResult(); result.setFile(mytempfile); // sets mytempfile as MTOM attachment // mytempfile.delete() iS WRONG // can't delete mytempfile because it hasn't been returned to the web service client // yet. So how do I remove it? return result; }} | I ran into this same problem. The issue is that the JAX-WS stack manages the file. It is not possible to determine in your code when JAX-WS is done with the file so you do not know when to delete it. In my case, I am using a DataHandler on my object model rather than a file. MyFileResult would have the following field instead of a file field: private DataHandler handler; My solution was to create a customized version of FileDataSource. Instead of returning a FileInputStream to read the contents of the file, I return the following extension of FileInputStream: private class TemporaryFileInputStream extends FileInputStream { public TemporaryFileInputStream(File file) throws FileNotFoundException { super(file); } @Override public void close() throws IOException { super.close(); file.delete(); }} Essentially the datasource allows reading only once. After the stream is closed, the file is deleted. Since the JAX-WS stack only reads the file once, it works. The solution is a bit of a hack but seems to be the best option in this case. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12979/"
]
} |
158,574 | In several cases I want to add a toolbar to the top of the iPhone keyboard (as in iPhone Safari when you're navigating form elements, for example). Currently I am specifying the toolbar's rectangle with constants but because other elements of the interface are in flux - toolbars and nav bars at the top of the screen - every time we make a minor interface change, the toolbar goes out of alignment. Is there a way to programmatically determine the position of the keyboard in relation to the current view? | As of iOS 3.2 there's a new way to achieve this effect: UITextFields and UITextViews have an inputAccessoryView property, which you can set to any view, that is automatically displayed above and animated with the keyboard. Note that the view you use should neither be in the view hierarchy elsewhere, nor should you add it to some superview, this is done for you. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/158574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24213/"
]
} |
158,585 | I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at? I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this. | In Win32 : #include<windows.h>Sleep(milliseconds); In Unix : #include<unistd.h>unsigned int microsecond = 1000000;usleep(3 * microsecond);//sleeps for 3 second sleep() only takes a number of seconds which is often too long. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/158585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229/"
]
} |
158,633 | What VBA code is required to perform an HTTP POST from an Excel spreadsheet? | Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")URL = "http://www.somedomain.com"objHTTP.Open "POST", URL, FalseobjHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"objHTTP.send "" Alternatively, for greater control over the HTTP request you can use WinHttp.WinHttpRequest.5.1 in place of MSXML2.ServerXMLHTTP . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/158633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4023/"
]
} |
158,634 | Is it possible to do a cast within a LINQ query (for the compiler's sake)? The following code isn't terrible, but it would be nice to make it into one query: Content content = dataStore.RootControl as Controls.Content;List<TabSection> tabList = (from t in content.ChildControls select t).OfType<TabSection>().ToList();List<Paragraph> paragraphList = (from t in tabList from p in t.ChildControls select p).OfType<Paragraph>().ToList();List<Line> parentLineList = (from p in paragraphList from pl in p.ChildControls select pl).OfType<Line>().ToList(); The code continues on with a few more queries, but the gist is I have to create a List out of each query in order for the compiler to know that all of the objects in content.ChildControls are of type TabSection and all of the objects in t.ChildControls are of type Paragraph ...and so on and and so forth. Is there a way within the LINQ query to tell the compiler that t in from t in content.ChildControls is a TabSection ? | Try this: from TabSection t in content.ChildControls Also, even if this were not available (or for a different, future scenario you may encounter), you wouldn't be restricted to converting everything to Lists. Converting to a List causes query evaluation on the spot. But if you removing the ToList call, you could work with the IEnumerable type, which would continue to defer the execution of the query until you actually iterate or store in a real container. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12999/"
]
} |
158,664 | I have a lot of changes in a working folder, and something screwed up trying to do an update. Now when I issue an 'svn cleanup' I get: >svn cleanup .svn: In directory '.'svn: Error processing command 'modify-wcprop' in '.'svn: 'MemPoolTests.cpp' is not under version control MemPoolTests.cpp is a new file another developer added and was brought down in the update. It did not exist in my working folder before. Is there anything I can do to try and move forward without having to checkout a fresh copy of the repository? Clarification: Thanks for the suggestions about moving the directory out of the way and bringing down a new copy. I know that is an option, but it is one I'd like to avoid since there are many changes nested several directories deep (this should have been a branch...) I'm hoping for a more aggressive way of doing the cleanup, maybe someway of forcing the file SVN is having trouble with back into a known state (and I tried deleting the working copy of it ... that didn't help). | When starting all over is not an option... I deleted the log file in the .svn directory (I also deleted the offending file in .svn/props-base ), did a cleanup, and resumed my update. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/158664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3631/"
]
} |
158,665 | I want to delete all directories and subdirectories under a root directory that are contain "tmp" in their names. This should include any .svn files too. My first guess is to use <delete> <dirset dir="${root}"> <include name="**/*tmp*" /> </dirset></delete> This does not seem to work as you can't nest a dirset in a delete tag. Is this a correct approach, or should I be doing something else? ant version == 1.6.5. java version == 1.6.0_04 | Here's the answer that worked for me: <delete includeemptydirs="true"> <fileset dir="${root}" defaultexcludes="false"> <include name="**/*tmp*/**" /> </fileset></delete> I had an added complication I needed to remove .svn directories too. With defaultexcludes , .* files were being excluded, and so the empty directories weren't really empty, and so weren't getting removed. The attribute includeemptydirs (thanks, flicken, XL-Plüschhase) enables the trailing ** wildcard to match the an empty string. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737/"
]
} |
158,673 | I'd like to check if the current browser supports the onbeforeunload event.The common javascript way to do this does not seem to work: if (window.onbeforeunload) { alert('yes');}else { alert('no');} Actually, it only checks whether some handler has been attached to the event.Is there a way to detect if onbeforeunload is supported without detecting the particular browser name? | I wrote about a more-or-less reliable inference for detecting event support in modern browsers some time ago. You can see on a demo page that "beforeunload" is supported in at least Safari 4+, FF3.x+ and IE. Edit : This technique is now used in jQuery, Prototype.js, Modernizr, and likely other scripts and libraries. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12111/"
]
} |
158,674 | How long can I expect a client/server TCP connection to last in the wild? I want it to stay permanently connected, but things happen, so the client will have to reconnect. At what point do I say that there's a problem in the code rather than there's a problem with some external equipment? | I agree with Zan Lynx. There's no guarantee, but you can keep a connection alive almost indefinitely by sending data over it, assuming there are no connectivity or bandwidth issues. Generally I've gone for the application level keep-alive approach, although this has usually because it's been in the client spec so I've had to do it. But just send some short piece of data every minute or two, to which you expect some sort of acknowledgement. Whether you count one failure to acknowledge as the connection having failed is up to you. Generally this is what I have done in the past, although there was a case I had wait for three failed responses in a row to drop the connection because the app at the other end of the connection was extremely flaky about responding to "are you there?" requests. If the connection fails, which at some point it probably will, even with machines on the same network, then just try to reestablish it. If that fails a set number of times then you have a problem. If your connection persistently fails after it's been connected for a while then again, you have a problem. Most likely in both cases it's probably some network issue, rather than your code, or maybe a problem with the TCP/IP stack on your machine (has been known: I encountered issues with this on an old version of QNX--it'd just randomly fall over). Having said that you might have a software problem, and the only way to know for sure is often to attach a debugger, or to get some logging in there. E.g. if you can always connect successfully, but after a time you stop getting ACKs, even after reconnect, then maybe your server is deadlocking, or getting stuck in a loop or something. What's really useful is to set up a series of long-running tests under a variety of load conditions, from just sending the keep alive are you there?/ack requests and responses, to absolutely battering the server. This will generally give you more confidence about your software components, and can be really useful in shaking out some really weird problems which won't necessarily cause a problem with your connection, although they might result in problems with the transactions taking place. For example, I was once writing a telecoms application server that provided services such as number translation, and we'd just leave it running for days at a time. The thing was that when Saturday came round, for the whole day, it would reject every call request that came in, which amounted to millions of calls, and we had no idea why. It turned out to be because of a single typo in some date conversion code that only caused a problem on Saturdays. Hope that helps. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9516/"
]
} |
158,703 | Scott Hanselman says yes . Adding System.Web to your non-web project is a good way to get folks to panic. Another is adding a reference to Microsoft.VisualBasic in a C# application. Both are reasonable and darned useful things to do, though. MSDN says no . The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly. So what should I think? | I realize this question is old, but in the interest of helping anyone who finds this via search, its worth noting that .net v4 includes a new general purpose cache for this type of scenario. It's in the System.Runtime.Caching namespace: https://msdn.microsoft.com/en-us/library/dd997357(v=vs.110).aspx The static reference to the default cache instance is: MemoryCache.Default | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
]
} |
158,706 | I'm using the Excel interop in C# ( ApplicationClass ) and have placed the following code in my finally clause: while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }excelSheet = null;GC.Collect();GC.WaitForPendingFinalizers(); Although this kind of works, the Excel.exe process is still in the background even after I close Excel. It is only released once my application is manually closed. What am I doing wrong, or is there an alternative to ensure interop objects are properly disposed of? | Excel does not quit because your application is still holding references to COM objects. I guess you're invoking at least one member of a COM object without assigning it to a variable. For me it was the excelApp.Worksheets object which I directly used without assigning it to a variable: Worksheet sheet = excelApp.Worksheets.Open(...);...Marshal.ReleaseComObject(sheet); I didn't know that internally C# created a wrapper for the Worksheets COM object which didn't get released by my code (because I wasn't aware of it) and was the cause why Excel was not unloaded. I found the solution to my problem on this page , which also has a nice rule for the usage of COM objects in C#: Never use two dots with COM objects. So with this knowledge the right way of doing the above is: Worksheets sheets = excelApp.Worksheets; // <-- The important partWorksheet sheet = sheets.Open(...);...Marshal.ReleaseComObject(sheets);Marshal.ReleaseComObject(sheet); POST MORTEM UPDATE: I want every reader to read this answer by Hans Passant very carefully as it explains the trap I and lots of other developers stumbled into. When I wrote this answer years ago I didn't know about the effect the debugger has to the garbage collector and drew the wrong conclusions. I keep my answer unaltered for the sake of history but please read this link and don't go the way of "the two dots": Understanding garbage collection in .NET and Clean up Excel Interop Objects with IDisposable | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/158706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989/"
]
} |
158,716 | The question gives all necessary data: what is an efficient algorithm to generate a sequence of K non-repeating integers within a given interval [0,N-1] . The trivial algorithm (generating random numbers and, before adding them to the sequence, looking them up to see if they were already there) is very expensive if K is large and near enough to N . The algorithm provided in Efficiently selecting a set of random elements from a linked list seems more complicated than necessary, and requires some implementation. I've just found another algorithm that seems to do the job fine, as long as you know all the relevant parameters, in a single pass. | The random module from Python library makes it extremely easy and effective: from random import sampleprint sample(xrange(N), K) sample function returns a list of K unique elements chosen from the given sequence. xrange is a "list emulator", i.e. it behaves like a list of consecutive numbers without creating it in memory, which makes it super-fast for tasks like this one. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15472/"
]
} |
158,741 | What are some scenarios where MultiView would be a good choice? The MultiView control along with its View controls simply seem to extend the notion of Panels. Both Panels and MultiViews seem prone to abuse. If your UI concerns and biz logic concerns are properly separated, why lump views together in a single ASPX? | I have used MultiViews as a more flexible basis for a Wizard control. I do agree that lumping lots of views together is a code smell. In the case of a wizard there are often lots of pieces of state you want to share throughout the process. The multiview allows this state to be simply stored in the viewstate. Most of the time I make the contents of each view a single user control that it can encapsulate the logic related to that particular step. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
]
} |
158,750 | I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download? Update Oct 1, 2008: Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <div> relatively positioned. It would have been much easier to combine the images and create the effect on that single image. It then got me thinking about online image editors like Picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future? | I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page. <img id="img1" src="imgfile1.png"><img id="img2" src="imgfile2.png"><canvas id="canvas"></canvas><script type="text/javascript">var img1 = document.getElementById('img1');var img2 = document.getElementById('img2');var canvas = document.getElementById('canvas');var context = canvas.getContext('2d');canvas.width = img1.width;canvas.height = img1.height;context.globalAlpha = 1.0;context.drawImage(img1, 0, 0);context.globalAlpha = 0.5; //Remove if pngs have alphacontext.drawImage(img2, 0, 0);</script> Or, if you want to load the images on the fly: <canvas id="canvas"></canvas><script type="text/javascript">var canvas = document.getElementById('canvas');var context = canvas.getContext('2d');var img1 = new Image();var img2 = new Image();img1.onload = function() { canvas.width = img1.width; canvas.height = img1.height; img2.src = 'imgfile2.png';};img2.onload = function() { context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0);}; img1.src = 'imgfile1.png';</script> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415/"
]
} |
158,783 | I really want to be able to have a way to take an app that currently gets its settings using ConfigurationManager.AppSettings["mysettingkey"] to actually have those settings come from a centralized database instead of the app.config file. I can make a custom config section for handling this sort of thing, but I really don't want other developers on my team to have to change their code to use my new DbConfiguration custom section. I just want them to be able to call AppSettings the way they always have but have it be loaded from a central database. Any ideas? | If you don't mind hacking around the framework and you can reasonably assume the .net framework version the application is running on (i.e. it's a web application or an intranet application) then you could try something like this: using System;using System.Collections.Specialized;using System.Configuration;using System.Configuration.Internal;using System.Reflection;static class ConfigOverrideTest{ sealed class ConfigProxy:IInternalConfigSystem { readonly IInternalConfigSystem baseconf; public ConfigProxy(IInternalConfigSystem baseconf) { this.baseconf = baseconf; } object appsettings; public object GetSection(string configKey) { if(configKey == "appSettings" && this.appsettings != null) return this.appsettings; object o = baseconf.GetSection(configKey); if(configKey == "appSettings" && o is NameValueCollection) { // create a new collection because the underlying collection is read-only var cfg = new NameValueCollection((NameValueCollection)o); // add or replace your settings cfg["test"] = "Hello world"; o = this.appsettings = cfg; } return o; } public void RefreshConfig(string sectionName) { if(sectionName == "appSettings") appsettings = null; baseconf.RefreshConfig(sectionName); } public bool SupportsUserConfig { get { return baseconf.SupportsUserConfig; } } } static void Main() { // initialize the ConfigurationManager object o = ConfigurationManager.AppSettings; // hack your proxy IInternalConfigSystem into the ConfigurationManager FieldInfo s_configSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.Static | BindingFlags.NonPublic); s_configSystem.SetValue(null, new ConfigProxy((IInternalConfigSystem)s_configSystem.GetValue(null))); // test it Console.WriteLine(ConfigurationManager.AppSettings["test"] == "Hello world" ? "Success!" : "Failure!"); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
]
} |
158,804 | I've installed .NET Framework 3.5 SP1 on web server (Server 2008 Enterprise), so running IIS 7.0. I want to change the version of .NET Framework used by an existing site. So I right-click on appropriate Application Pool and selected Edit Application Pool. The .NET Framework dropdown does not include an explicit entry for framework 3.5, but just 2.0.50727. Is this just because the version of the core RTL in 3.5 is still 2.0? Or do I need to do something additional to get IIS to see version 3.5? (Did try restarting IIS). | The 3.5 framework still runs on top of the 2.0 CLR so what you are seeing is correct. Scott Hanselman has a nice blog post about the details of this: The marketing term ".NET Framework 3.5" refers to a few things. First, LINQ, which is huge, and includes new language compilers for C# and VB. Second, the REST support added to Windows Communication Foundation, as well as, third, the fact that ASP.NET AJAX is included, rather than a separate download as it was before in ASP.NET 2.0. There's a few other things in .NET 3.5, like SP1 of .NET 2.0 to fix bugs, but one way to get an idea of what's been added in .NET 3.5 is to look in c:\windows\assembly . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22357/"
]
} |
158,814 | What does it indicate to see a query that has a low cost in the explain plan but a high consistent gets count in autotrace? In this case the cost was in the 100's and the CR's were in the millions. | The 3.5 framework still runs on top of the 2.0 CLR so what you are seeing is correct. Scott Hanselman has a nice blog post about the details of this: The marketing term ".NET Framework 3.5" refers to a few things. First, LINQ, which is huge, and includes new language compilers for C# and VB. Second, the REST support added to Windows Communication Foundation, as well as, third, the fact that ASP.NET AJAX is included, rather than a separate download as it was before in ASP.NET 2.0. There's a few other things in .NET 3.5, like SP1 of .NET 2.0 to fix bugs, but one way to get an idea of what's been added in .NET 3.5 is to look in c:\windows\assembly . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
158,818 | First off, let me start off that I am not a .net developer. The reason why I am asking this question is that we rolled out our REST-API and one of our first integration partners is a .net shop. So basically we assumed that .net would provide some sort of wrapper to create JSON, but the developer in question created the string by hand. I've researched this topic a bit and I couldn't really find anything, though I believe .net provides something. :) 'current code Dim data As Stringdata = "[hello, world]" In PHP I would do the following (assuming ext/json is available ;): <?php$json = array('hello', 'world');$json = json_encode($json); I am also interested in what you use to decode the json into an array/object structure. Help is very appreciated. | There are a couple first-party and third-party options. Rick Strahl has a good overview. JSON.net is the most popular third-party option. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2859/"
]
} |
158,836 | what is a good way to select a random element from a map? C++. It is my understanding that maps don't have random access iterators. The key is a long long and the map is sparsely populated. | map<...> MyMap;iterator item = MyMap.begin();std::advance( item, random_0_to_n(MyMap.size()) ); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8264/"
]
} |
158,889 | I'm writing an application which reads large arrays of floats and performs some simple operations with them. I'm using floats, because I thought it'd be faster than doubles, but after doing some research I've found that there's some confusion about this topic. Can anyone elaborate on this? | The short answer is, "use whichever precision is required for acceptable results." Your one guarantee is that operations performed on floating point data are done in at least the highest precision member of the expression. So multiplying two float 's is done with at least the precision of float , and multiplying a float and a double would be done with at least double precision. The standard states that "[floating-point] operations may be performed with higher precision than the result type of the operation." Given that the JIT for .NET attempts to leave your floating point operations in the precision requested, we can take a look at documentation from Intel for speeding up our operations. On the Intel platform your floating point operations may be done in an intermediate precision of 80 bits, and converted down to the precision requested. From Intel's guide to C++ Floating-point Operations 1 (sorry only have dead tree), they mention: Use a single precision type (for example, float) unless the extra precision obtained through double or long double is required. Greater precision types increase memory size and bandwidth requirements. ... Avoid mixed data type arithmetic expressions That last point is important as you can slow yourself down with unnecessary casts to/from float and double , which result in JIT'd code which requests the x87 to cast away from its 80-bit intermediate format in between operations! 1. Yes, it says C++, but the C# standard plus knowledge of the CLR lets us know the information for C++ should be applicable in this instance. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/158889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7839/"
]
} |
158,895 | What needs to be done to have your .NET application show up in Window's system tray as icon? And how do you handle mousebutton clicks on said icon? | First, add a NotifyIcon control to the Form. Then wire up the Notify Icon to do what you want. If you want it to hide to tray on minimize, try this. Private Sub frmMain_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize If Me.WindowState = FormWindowState.Minimized Then Me.ShowInTaskbar = False Else Me.ShowInTaskbar = True End IfEnd SubPrivate Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick Me.WindowState = FormWindowState.NormalEnd Sub I'll occasionally use the Balloon Text in order to notify a user - that is done as such: Me.NotifyIcon1.ShowBalloonTip(3000, "This is a notification title!!", "This is notification text.", ToolTipIcon.Info) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
]
} |
158,914 | I've got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a UIImage and return a small, square representation of an image, similar to what's seen in the album view of the Photos app. (I know I could use a UIImageView and adjust the crop mode to achieve the same results, but these images are sometimes displayed in UIWebViews ). I've started to notice some crashes in this code and I'm a bit stumped. I've got two different theories and I'm wondering if either is on-base. Theory 1) I achieve the cropping by drawing into an offscreen image context of my target size. Since I want the center portion of the image, I set the CGRect argument passed to drawInRect to something that's larger than the bounds of my image context. I was hoping this was Kosher, but am I instead attempting to draw over other memory that I shouldn't be touching? Theory 2) I'm doing all of this in a background thread. I know there are portions of UIKit that are restricted to the main thread. I was assuming / hoping that drawing to an offscreen view wasn't one of these. Am I wrong? (Oh, how I miss NSImage's drawInRect:fromRect:operation:fraction: method.) | Update 2014-05-28: I wrote this when iOS 3 or so was the hot new thing, I'm certain there are better ways to do this by now, possibly built-in. As many people have mentioned, this method doesn't take rotation into account; read some additional answers and spread some upvote love around to keep the responses to this question helpful for everyone. Original response: I'm going to copy/paste my response to the same question elsewhere: There isn't a simple class method to do this, but there is a function that you can use to get the desired results: CGImageCreateWithImageInRect(CGImageRef, CGRect) will help you out. Here's a short example using it: CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);// or use the UIImage wherever you like[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; CGImageRelease(imageRef); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/158914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24168/"
]
} |
158,966 | I'm thinking floats. For the record I'm also using NHibernate. | decimal You won't lose precision due to rounding. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/158966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122/"
]
} |
158,968 | Could someone explain to me in simple terms the easiest way to change the indentation behavior of Vim based on the file type? For instance, if I open a Python file it should indent with 2 spaces, but if I open a Powershell script it should use 4 spaces. | You can add .vim files to be executed whenever vim switches to a particular filetype. For example, I have a file ~/.vim/after/ftplugin/html.vim with this contents: setlocal shiftwidth=2setlocal tabstop=2 Which causes vim to use tabs with a width of 2 characters for indenting (the noexpandtab option is set globally elsewhere in my configuration). This is described here: http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4 , scroll down to the section on filetype plugins. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/158968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358/"
]
} |
158,975 | I'm making a request from an UpdatePanel that takes more then 90 seconds. I'm getting this timeout error: Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerTimeoutException: The server request timed out. Does anyone know if there is a way to increase the amount of time before the call times out? | There is a property on the ScriptManager which allows you to set the time-out in seconds. The default value is 90 seconds. AsyncPostBackTimeout="300" | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/158975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
]
} |
158,986 | I am very new to the entity framework, so please bear with me... How can I relate two objects from different contexts together? The example below throws the following exception: System.InvalidOperationException: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects. void MyFunction(){ using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123); er.Roles = GetDefaultRole(); model.SaveChanges(); }}private static Roles GetDefaultRole(){ Roles r = null; using (TCPSEntities model = new TCPSEntities()) { r = model.Roles.First(p => p.RoleId == 1); } return r;} Using one context is not an option because we are using the EF in an ASP.NET application. | You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity. EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs. You could simply pass the context.. IE: void MyFunction(){ using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123); er.Roles = GetDefaultRole(model); model.SaveChanges(); }}private static Roles GetDefaultRole(TCPSEntities model){ Roles r = null; r = model.Roles.First(p => p.RoleId == 1); return r;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/158986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.