source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
122,067
I have a site using a custom favicon.ico. The favicon displays as expected in all browsers except IE. When trying to display the favicon in IE, I get the big red x; when displaying the favicon in another browser, it displays just fine. The page source includes and it does work in other browsers. Thanks for your thoughts. EDIT: SOLVED: The source of the issue was the file was a jpg renamed to ico. I created the file as an ico and it is working as expected. Thanks for your input.
Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to check: Is the code like this: <link rel="icon" href="http://www.example.com/favicon.ico" type="image/x-icon" /><link rel="shortcut icon" href="http://www.example.com/favicon.ico" type="image/x-icon" /> Is it in the <head> ? Is the image a real ico file? (renaming a bitmap is not a real .ico! Mildly different format) Does it work when you add the page as a bookmark?
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/122067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13465/" ] }
122,102
What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's non-standard and only supported by Firefox . I've done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency. I've also seen recursive copying functions with various flaws. I'm surprised no canonical solution exists.
Native deep cloning There's now a JS standard called "structured cloning" , that works experimentally in Node 11 and later, will land in browsers, and which has polyfills for existing systems . structuredClone(value) If needed, loading the polyfill first: import structuredClone from '@ungap/structured-clone'; See this answer for more details. Older answers Fast cloning with data loss - JSON.parse/stringify If you do not use Date s, functions, undefined , Infinity , RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is: JSON.parse(JSON.stringify(object)) const a = { string: 'string', number: 123, bool: false, nul: null, date: new Date(), // stringified undef: undefined, // lost inf: Infinity, // forced to 'null' re: /.*/, // lost}console.log(a);console.log(typeof a.date); // Date objectconst clone = JSON.parse(JSON.stringify(a));console.log(clone);console.log(typeof clone.date); // result of .toISOString() See Corban's answer for benchmarks. Reliable cloning using a library Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. Don't reinvent the wheel - if you're already using a library, check if it has an object cloning function. For example, lodash - cloneDeep ; can be imported separately via the lodash.clonedeep module and is probably your best choice if you're not already using a library that provides a deep cloning function AngularJS - angular.copy jQuery - jQuery.extend(true, { }, oldObject) ; .clone() only clones DOM elements just library - just-clone ; Part of a library of zero-dependency npm modules that do just do one thing.Guilt-free utilities for every occasion.
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/122102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12694/" ] }
122,105
I want to filter a java.util.Collection based on a predicate.
Java 8 ( 2014 ) solves this problem using streams and lambdas in one line of code: List<Person> beerDrinkers = persons.stream() .filter(p -> p.getAge() > 16).collect(Collectors.toList()); Here's a tutorial . Use Collection#removeIf to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate): persons.removeIf(p -> p.getAge() <= 16); lambdaj allows filtering collections without writing loops or inner classes: List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(), greaterThan(16))); Can you imagine something more readable? Disclaimer: I am a contributor on lambdaj
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/122105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ] }
122,107
"It is not possible to check out a single file. The finest level of checkouts you can do is at the directory level." How do I get around this issue when using Subversion? We have this folder in Subversion where we keep all our images. I just want to check out one file (image) from that. This folder is really big and has ton of other stuff which I don't need now.
The simple answer is that you svn export the file instead of checking it out. But that might not be what you want. You might want to work on the file and check it back in, without having to download GB of junk you don't need. If you have Subversion 1.5+, then do a sparse checkout: svn checkout <url_of_big_dir> <target> --depth emptycd <target>svn up <file_you_want> For an older version of SVN, you might benefit from the following: Checkout the directory using a revision back in the distant past, when it was less full of junk you don't need. Update the file you want, to create a mixed revision. This works even if the file didn't exist in the revision you checked out. Profit! An alternative (for instance if the directory has too much junk right from the revision in which it was created) is to do a URL->URL copy of the file you want into a new place in the repository (effectively this is a working branch of the file). Check out that directory and do your modifications. I'm not sure whether you can then merge your modified copy back entirely in the repository without a working copy of the target - I've never needed to. If so then do that. If not then unfortunately you may have to find someone else who does have the whole directory checked out and get them to do it. Or maybe by the time you've made your modifications, the rest of it will have finished downloading...
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/122107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175964/" ] }
122,109
My client has a multi-page PDF file. They need it split by page. Does anyone know of a way to do this - preferably in C#.
PDFSharp is an open source library which may be what you're after: Key Features Creates PDF documents on the fly from any .Net language Easy to understand object model to compose documents One source code for drawing on a PDF page as well as in a window or on the printer Modify, merge, and split existing PDF files This sample shows how to convert a PDF document with n pages into n documents with one page each.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ] }
122,154
I'm using Team Foundation Build but we aren't yet using TFS for problem tracking, so I would like to disable the work item creation on a failed build. Is there any way to do this? I tried commenting out the work item info in the TFSBuild.proj file for the build type but that didn't do the trick.
Try adding this inside the PropertyGroup in your TFSBuild.proj: <SkipWorkItemCreation>true</SkipWorkItemCreation> If you are curious as to how this works, Microsoft.TeamFoundation.Build.targets contians the following: <Target Name="CoreCreateWorkItem" Condition=" '$(SkipWorkItemCreation)'!='true' and '$(IsDesktopBuild)'!='true' " DependsOnTargets="$(CoreCreateWorkItemDependsOn)"> <PropertyGroup> <WorkItemTitle>$(WorkItemTitle) $(BuildNumber)</WorkItemTitle> <BuildLogText>$(BuildlogText) &lt;a href='file:///$(DropLocation)\$(BuildNumber)\BuildLog.txt'&gt;$(DropLocation)\$(BuildNumber)\BuildLog.txt&lt;/a &gt;.</BuildLogText> <ErrorWarningLogText Condition="!Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')"></ErrorWarningLogText> <ErrorWarningLogText Condition="Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')">$(ErrorWarningLogText) &lt;a href='file:///$(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt'&gt;$(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt&lt;/a &gt;.</ErrorWarningLogText> <WorkItemDescription>$(DescriptionText) %3CBR%2F%3E $(BuildlogText) %3CBR%2F%3E $(ErrorWarningLogText)</WorkItemDescription> </PropertyGroup> <CreateNewWorkItem TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" BuildNumber="$(BuildNumber)" Description="$(WorkItemDescription)" TeamProject="$(TeamProject)" Title="$(WorkItemTitle)" WorkItemFieldValues="$(WorkItemFieldValues)" WorkItemType="$(WorkItemType)" ContinueOnError="true" /> </Target> You can override any of this functionality in your own build script, but Microsoft provide the handy SkipWorkItemCreation condition at the top, which you can use to cancel execution of the whole target.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ] }
122,160
I'm a big fan of the way Visual Studio will give you the comment documentation / parameter names when completing code that you have written and ALSO code that you are referencing (various libraries/assemblies). Is there an easy way to get inline javadoc/parameter names in Eclipse when doing code complete or hovering over methods? Via plugin? Via some setting? It's extremely annoying to use a lot of libraries (as happens often in Java) and then have to go to the website or local javadoc location to lookup information when you have it in the source jars right there!
Short answer would be yes. You can attach source using the properties for a project. Go to Properties (for the Project) -> Java Build Path -> Libraries Select the Library you want to attach source/javadoc for and then expand it, you'll see a list like so: Source Attachment: (none)Javadoc location: (none)Native library location: (none)Access rules: (No restrictions) Select Javadoc location and then click Edit on the right hahnd side. It should be quite straight forward from there. Good luck :)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/122160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5885/" ] }
122,205
I was wondering if there is a good way to hook into the Application_Start of a SharePoint 2007 site when developing a feature? I know I can directly edit the Global.asax file in the site root, but is there a way to do this so that it gets deployed with the feature? Thanks!
This is actually possible, but it doesn't involve the Global.asax file. Many of Microsoft's examples demonstrate wiring code in via the Global.asax, but this is not a best-practices approach when it comes to SharePoint. Ideally, your code should get packaged as a Feature and deployed via WSP (as you already know). The key lies in implementing the code in question as an HttpModule (i.e., a type that implements the IHttpModule interface) and wiring it into the ASP.NET pipeline servicing your SharePoint application. Roughly speaking, these are the steps: Create a class that implements the IHttpModule interface. Implement the Init method in your HttpModule; this is called when the HttpApplication (in this case, the SPHttpApplication) is setup, and it gives you an opportunity to carry out processing, wire-up event delegates for other pipeline events, etc. Create an SPFeatureReceiver that will add and remove your HttpModule from target web.config files on activation and deactivation, respectively. This is carried out using the SPWebConfigModification type to update the <httpModules> node in target web.config files. Package all as a Feature and deploy via WSP. For more information on HttpModule development, see http://msdn.microsoft.com/en-us/library/ms227673.aspx . For some additional detail on the SPWebConfigModification type, see http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spwebconfigmodification.aspx . Result: a class that can handle application startup and is deployable via Feature. No manual file hacking required. I've successfully used this in a number of scenarios -- most recently with a custom caching provider (IVaryByCustomHandler) that needed to register itself for callbacks with the SPHttpApplication when it started. Though your question is a bit older, I hope this helps!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10893/" ] }
122,208
In C++, what's the easiest way to get the local computer's IP address and subnet mask? I want to be able to detect the local machine's IP address in my local network. In my particular case, I have a network with a subnet mask of 255.255.255.0 and my computer's IP address is 192.168.0.5. I need to get these had two values programmatically in order to send a broadcast message to my network (in the form 192.168.0.255, for my particular case) Edit: Many answers were not giving the results I expected because I had two different network IP's. Torial 's code did the trick (it gave me both IP addresses). Edit 2: Thanks to Brian R. Bondy for the info about the subnet mask.
The question is trickier than it appears, because in many cases there isn't "an IP address for the local computer" so much as a number of different IP addresses. For example, the Mac I'm typing on right now (which is a pretty basic, standard Mac setup) has the following IP addresses associated with it: fe80::1%lo0 127.0.0.1 ::1 fe80::21f:5bff:fe3f:1b36%en1 10.0.0.138 172.16.175.1192.168.27.1 ... and it's not just a matter of figuring out which of the above is "the real IP address", either... they are all "real" and useful; some more useful than others depending on what you are going to use the addresses for. In my experience often the best way to get "an IP address" for your local computer is not to query the local computer at all, but rather to ask the computer your program is talking to what it sees your computer's IP address as. e.g. if you are writing a client program, send a message to the server asking the server to send back as data the IP address that your request came from. That way you will know what the relevant IP address is, given the context of the computer you are communicating with. That said, that trick may not be appropriate for some purposes (e.g. when you're not communicating with a particular computer) so sometimes you just need to gather the list of all the IP addresses associated with your machine. The best way to do that under Unix/Mac (AFAIK) is by calling getifaddrs() and iterating over the results. Under Windows, try GetAdaptersAddresses() to get similar functionality. For example usages of both, see the GetNetworkInterfaceInfos() function in this file .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4880/" ] }
122,238
JSF is setting the ID of an input field to search_form:expression . I need to specify some styling on that element, but that colon looks like the beginning of a pseudo-element to the browser so it gets marked invalid and ignored. Is there anyway to escape the colon or something? input#search_form:expression { ///...}
Backslash: input#search_form\:expression { ///...} See also Using Namespaces with CSS (MSDN)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/122238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ] }
122,254
I have a class that defines the names of various session attributes, e.g. class Constants { public static final String ATTR_CURRENT_USER = "current.user";} I would like to use these constants within a JSP to test for the presence of these attributes, something like: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ page import="com.example.Constants" %><c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}"> <%-- Do somthing --%></c:if> But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with <c:set> , but again I'm struggling to find the correct syntax. UPDATE: Further to the suggestion below, I tried: <c:set var="nullUser" scope="session"value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" /> which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered <c:set var="nullUser" scope="session"value="${sessionScope['current.user'] eq null}" /><%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %> This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help.....
It's not working in your example because the ATTR_CURRENT_USER constant is not visible to the JSTL tags, which expect properties to be exposed by getter functions. I haven't tried it, but the cleanest way to expose your constants appears to be the unstandard tag library . ETA: Old link I gave didn't work. New links can be found in this answer: Java constants in JSP Code snippets to clarify the behavior you're seeing:Sample class: package com.example;public class Constants{ // attribute, visible to the scriptlet public static final String ATTR_CURRENT_USER = "current.user"; // getter function; // name modified to make it clear, later on, // that I am calling this function // and not accessing the constant public String getATTR_CURRENT_USER_FUNC() { return ATTR_CURRENT_USER; }} Snippet of the JSP page, showing sample usage: <%-- Set up the current user --%><% session.setAttribute("current.user", "Me");%><%-- scriptlets --%><%@ page import="com.example.Constants" %><h1>Using scriptlets</h1><h3>Constants.ATTR_CURRENT_USER</h3><%=Constants.ATTR_CURRENT_USER%> <br /><h3>Session[Constants.ATTR_CURRENT_USER]</h3><%=session.getAttribute(Constants.ATTR_CURRENT_USER)%><%-- JSTL --%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><jsp:useBean id="cons" class="com.example.Constants" scope="session"/><h1>Using JSTL</h1><h3>Constants.getATTR_CURRENT_USER_FUNC()</h3><c:out value="${cons.ATTR_CURRENT_USER_FUNC}"/><h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3><c:out value="${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}"/><h3>Constants.ATTR_CURRENT_USER</h3><c:out value="${sessionScope[Constants.ATTR_CURRENT_USER]}"/><%--Commented out, because otherwise will error:The class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.<h3>cons.ATTR_CURRENT_USER</h3><c:out value="${sessionScope[cons.ATTR_CURRENT_USER]}"/>--%><hr /> This outputs: Using scriptlets Constants.ATTR_CURRENT_USER current.user Session[Constants.ATTR_CURRENT_USER] Me Using JSTL Constants.getATTR_CURRENT_USER_FUNC() current.user Session[Constants.getATTR_CURRENT_USER_FUNC()] Me Constants.ATTR_CURRENT_USER
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ] }
122,267
(using the IMAP commands, not with the assistance of any other mail package)
I'm not sure how well-versed you are in imap-speak, but basically after login, "SELECT" the source mailbox, "COPY" the messages, and "EXPUNGE" the messages (or "DELETE" the old mailbox if it is empty now :-). a login a sb select sourcec copy 1 othermboxd store 1 +flags (\Deleted)e expunge would be an example of messages to send. ( Note : imap messages require a uniqe prefix before each command, thus the "a b c" in front) See RFC 2060 for details.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ] }
122,273
Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container? I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.
You can use poor-man's dependency injection: public ProductController() : this( new Foo() ){ //the framework calls this}public ProductController(IFoo foo){ _foo = foo;}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17902/" ] }
122,282
I have a Java application that monitors a folder for incoming XML files. When a new file is detected I need to test the file that it is not currently being updated and is closed. My thought is to use File.canWrite() to test this. Is there any issue with doing this? Is this a good way to test that a file has been completely written? Other ideas I am throwing around are: Parse the incoming XML file and testthat the closing tag is there. Check for the EoF character. I just am not sure that any of these methods will handle all scenarios.
No, canWrite is not suitable for this purpose. In general the file will be writable even if another process is writing. You need a higher level protocol to coordinate the locking. If you plan to use this code on a single platform, you may be able to use NIO's FileLock facility . But read the documentation carefully, and note that on many platforms, the lock is only advisory. Another approach is to have one process write the file with a name that your process won't recognize, then rename the file to a recognizable name when the write is complete. On most platforms, the rename operation is atomic if the source and destination are the same file system volume. The name change might use a different file extension, or even moving the file from one directory to another (on the same volume). Since in this case you are working exclusively with XML, looking for a close tag would work, but it isn't foolproof—what if there are comments after the final markup, or the writer or simply doesn't write valid XML? Looking for the EOF will not work. There will always be an EOF, even when the writer has just opened the file and hasn't written anything yet. If this weren't so, the easiest thing would be to allow the reader to start parsing as soon as the file showed up; it would simply block until the writer closed the file. But the file system doesn't work this way. Every file has an end, even if some process is currently moving it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387361/" ] }
122,298
As far as I understand, CouchDB indexes are updated when a view is queried. Assuming there are more reads than writes, isn't this bad for scaling? How would I configure CouchDB to update indexes on writes, or better yet, on a schedule?
CouchDB does regenerate views on update, but only on what has changed since the last read access to the view. Assuming your read volume greatly outweighs your write volume, this shouldn't be a problem. When you're changing large numbers of documents at once this could lead to the possibility of the first read requests taking a noticeable amount of time. To alleviate this a few different possibilities have been suggested. Most rely on registering with CouchDB's update notifications and triggering reads automatically. An example script for doing exactly that is available on the CouchDB wiki at [1]. [1] http://wiki.apache.org/couchdb/RegeneratingViewsOnUpdate
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12887/" ] }
122,313
I'm getting confused with the include/exclude jargon, and my actual SVN client doesn't seem to have (or I've been unable to find it easily) a simple option to add or remove a certain type of files for version control. Let's say for example I've added the entire Visual Studio folder, with its solutions, projects, debug files, etc., but I only want to version the actual source files. What would be the simplest way to do that?
You're probably safest excluding particular filetypes, rather than picking those you want to include, as you could then add a new type and not realize it wasn't versioned. On a per-directory basis, you can edit the svn:ignore property. Run svn propedit svn:ignore . for each relevant directory to bring up an editor with a list of patterns to ignore. Then put a pattern on each line corresponding to the filetype you'd like to ignore: *.user*.exe*.dll and what have you. Alternatively, as has been suggested, you can add those patterns to the global-ignores property in your ~/.subversion/config file (or "%APPDATA%\Subversion\config" on Windows - see Configuration Area Layout in the red bean book for more information ). In that case, separate the patterns with spaces. Here's mine. # at the beginning of the line introduces a comment. I've ignored Ankh .Load files and all *.resharper.user files: ### Set global-ignores to a set of whitespace-delimited globs### which Subversion will ignore in its 'status' output, and### while importing or adding files and directories.# global-ignores = *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Storeglobal-ignores = Ankh.Load *.resharper.user
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/122313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ] }
122,316
In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints: interface IFoo{}class Foo<T> where T : IFoo{}class Bar : IFoo{}class Simpson{}class Program{ static void Main(string[] args) { Foo<Bar> a = new Foo<Bar>(); Foo<Simpson> b = new Foo<Simpson>(); // error CS0309 }} Is there a way we can impose constraints for template parameters in C++. C++0x has native support for this but I am talking about current standard C++.
As someone else has mentioned, C++0x is getting this built into the language. Until then, I'd recommend Bjarne Stroustrup 's suggestions for template constraints . Edit: Boost also has an alternative of its own . Edit2: Looks like concepts have been removed from C++0x .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ] }
122,327
How do I find the location of my site-packages directory?
There are two types of site-packages directories, global and per user . Global site-packages (" dist-packages ") directories are listed in sys.path when you run: python -m site For a more concise list run getsitepackages from the site module in Python code: python -c 'import site; print(site.getsitepackages())' Caution: In virtual environments getsitepackages is not available with older versions of virtualenv , sys.path from above will list the virtualenv's site-packages directory correctly, though. In Python 3, you may use the sysconfig module instead: python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])' The per user site-packages directory ( PEP 370 ) is where Python installs your local packages: python -m site --user-site If this points to a non-existing directory check the exit status of Python and see python -m site --help for explanations. Hint: Running pip list --user or pip freeze --user gives you a list of all installed per user site-packages. Practical Tips <package>.__path__ lets you identify the location(s) of a specific package: ( details ) $ python -c "import setuptools as _; print(_.__path__)" ['/usr/lib/python2.7/dist-packages/setuptools'] <module>.__file__ lets you identify the location of a specific module: ( difference ) $ python3 -c "import os as _; print(_.__file__)" /usr/lib/python3.6/os.py Run pip show <package> to show Debian-style package information: $ pip show pytest Name: pytest Version: 3.8.2 Summary: pytest: simple powerful testing with Python Home-page: https://docs.pytest.org/en/latest/ Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others Author-email: None License: MIT license Location: /home/peter/.local/lib/python3.4/site-packages Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/122327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ] }
122,348
I have a command which includes an includegraphics command - I can pass an image to my command, and it will do some standard formatting for me before actually including the image. Some of the images that I'm including via this command are smaller than \textwidth, while some are larger. I'd like to scale the larger images down to \textwidth, while not scaling the smaller images up - this means I can't just do \includegraphics[width=\textwidth]{img} Is there a way to specify a maxwidth? Or, can I get the width of the image somehow so I can do something like \ifthenelse{\imagewidth > \textwidth}{% \includegraphics[width=\textwidth]{img}}{% \includegraphics{img}}
To get the width of the image you can use this code: \newlength{\imgwidth}\settowidth{\imgwidth}{\includegraphics{img}} You could use this in the document preamble to create a new command to automatically set the width: \usepackage{graphicx}\usepackage{calc}\newlength{\imgwidth}\newcommand\scalegraphics[1]{% \settowidth{\imgwidth}{\includegraphics{#1}}% \setlength{\imgwidth}{\minof{\imgwidth}{\textwidth}}% \includegraphics[width=\imgwidth]{#1}%} and then, in your document: \scalegraphics{img} I hope this helps!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1322/" ] }
122,388
I don't develop too many desktop / Windows Forms applications, but it had occurred to me that there may be some benefit to using the MVC (Model View Controller) pattern for Windows Forms .NET development. Has anyone implemented MVC in Windows Forms? If so, do you have any tips on the design?
What I've done in the past is use something similar, Model-View-Presenter . [NOTE: This article used to be available on the web. To see it now, you'll need to download the CHM, and then view the file properties and click Unblock. Then you can open the CHM and find the article. Thanks a million, Microsoft! sigh ] The form is the view, and I have an IView interface for it. All the processing happens in the presenter, which is just a class. The form creates a new presenter, and passes itself as the presenter's IView. This way for testing you can pass in a fake IView instead, and then send commands to it from the presenter and detect the results. If I were to use a full-fledged Model-View-Controller, I guess I'd do it this way: The form is the view . It sends commands to the model, raises events which the controller can subscribe to, and subscribes to events from the model. The controller is a class that subscribes to the view's events and sends commands to the view and to the model. The model raises events that the view subscribes to. This would fit with the classic MVC diagram . The biggest disadvantage is that with events, it can be hard to tell who's subscribing to what. The MVP pattern uses methods instead of events (at least the way I've implemented it). When the form/view raises an event (e.g. someButton.Click), the form simply calls a method on the presenter to run the logic for it. The view and model don't have any direct connection at all; they both have to go through the presenter.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ] }
122,400
I'm not asking about general syntactic rules for file names. I mean gotchas that jump out of nowhere and bite you. For example, trying to name a file "COM<n>" on Windows?
From: http://www.grouplogic.com/knowledge/index.cfm/fuseaction/view_Info/docID/111 . The following characters are invalid as file or folder names on Windows using NTFS: / ? < > \ : * | " and any character you can type with the Ctrl key. In addition to the above illegal characters the caret ^ is also not permitted under Windows Operating Systems using the FAT file system. Under Windows using the FAT file system file and folder names may be up to 255 characters long. Under Windows using the NTFS file system file and folder names may be up to 256 characters long. Under Window the length of a full path under both systems is 260 characters. In addition to these characters, the following conventions are also illegal: Placing a space at the end of the name Placing a period at the end of the name The following file names are also reserved under Windows: aux , com1 , com2 , ... com9 , lpt1 , lpt2 , ... lpt9 , con , nul , prn
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3474/" ] }
122,404
I used to often find myself coping a piece of code from a website/Word document etc only to discover that when doing Paste I would end up with the desired code plus some extra HTML tags/text, basically extra formatting information. To get rid of that extra ballast I would paste the text to the Notepad and then copy it again and then paste to the desired destination. Pretty recently I discovered a simple and free tool for Windows called PureText that allows me to cut the Notepad step. It basically adds an extra keyboard shortcut e.g WinKey + V that will do the Paste action without formatting; just pure text. I find it very handy. I was wondering what approach would you use yourselves? Are they any better/easier to use tools around?
Just to summarize the available options: Tools PureText - free tool for Windows Use AutoHotkey and write your own macroas suggested by Dean Browsers To copy plain text from a browser: Copy As Plain Text or CopyPlainText (suggested by cori ) - Firefox extensions To paste without formatting to a browser (Firefox/Chrome at least): CTRL + ⇧ Shift + V on Windows/Linux, see below for Mac OS X. Other Under Mac OS X , you can ⇧ Shift + ⌥ Alt + ⌘ Command + V to paste with the "current" format ( Edit -> Paste and Match Style ); or ⌘ Command + ⇧ Shift + V to paste without formatting (by Kamafeather ) Paste to Notepad (or other text editor), and then copy from Notepad and paste again For single-line text: paste to any non-rich text field (browser URL, textarea, search/find inputs, etc.) Please feel free to edit/add new items
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/122404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3241/" ] }
122,407
I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?
Anonymous inner class Say you want to have a function passed in with a String param that returns an int . First you have to define an interface with the function as its only member, if you can't reuse an existing one. interface StringFunction { int func(String param);} A method that takes the pointer would just accept StringFunction instance like so: public void takingMethod(StringFunction sf) { int i = sf.func("my string"); // do whatever ...} And would be called like so: ref.takingMethod(new StringFunction() { public int func(String param) { // body }}); EDIT: In Java 8, you could call it with a lambda expression: ref.takingMethod(param -> bodyExpression);
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/122407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ] }
122,424
Right now, we are using Perforce for version control. It has the handy feature of a strictly increasing change number that we can use to refer to builds, eg "you'll get the bugfix if your build is at least 44902". I'd like to switch over to using a distributed system (probably git) to make it easier to branch and to work from home. (Both of which are perfectly possible with Perforce, but the git workflow has some advantages.) So although "tributary development" would be distributed and not refer to a common revision sequencing, we'd still maintain a master git repo that all changes would need to feed into before a build was created. What's the best way to preserve strictly increasing build ids? The most straightforward way I can think of is to have some sort of post-commit hook that fires off whenever the master repo gets updated, and it registers (the hash of) the new tree object (or commit object? I'm new to git) with a centralized database that hands out ids. (I say "database", but I'd probably do it with git tags, and just look for the next available tag number or something. So the "database" would really be .git/refs/tags/build-id/.) This is workable, but I'm wondering if there is an easier, or already-implemented, or standard/"best practice" way of accomplishing this.
I second the suggestion of using git describe . Provided that you have a sane versioning policy, and you don't do any crazy stuff with your repository, git describe will always be monotonic (at least as monotonic as you can be, when your revision history is a DAG instead of a tree) and unique. A little demonstration: git initgit commit --allow-empty -m'Commit One.'git tag -a -m'Tag One.' 1.2.3git describe # => 1.2.3git commit --allow-empty -m'Commit Two.'git describe # => 1.2.3-1-gaac161dgit commit --allow-empty -m'Commit Three.'git describe # => 1.2.3-2-g462715dgit tag -a -m'Tag Two.' 2.0.0git describe # => 2.0.0 The output of git describe consists of the following components: The newest tag reachable from the commit you are asking to describe The number of commits between the commit and the tag (if non-zero) The (abbreviated) id of the commit (if #2 is non-zero) #2 is what makes the output monotonic, #3 is what makes it unique. #2 and #3 are omitted, when the commit is the tag, making git describe also suitable for production releases.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14528/" ] }
122,455
Do any C++ GNU standalone classes exist which handle paths cross platform? My applications build on Windows and LInux. Our configuration files refer to another file in a seperate directory. I'd like to be able to read the path for the other configuration file into a class which would work on both Linux or Windows. Which class would offer the smallest footprint to translate paths to use on either system? Thanks
Unless you're using absolute paths, there's no need to translate at all - Windows automatically converts forward slashes into backslashes, so if you use relative paths with forward slash path separators, you'll be golden. You should really avoid absolute paths if at all possible.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16496/" ] }
122,463
I have an XML file that starts like this: <Elements name="Entities" xmlns="XS-GenerationToolElements"> I'll have to open a lot of these files. Each of these have a different namespace but will only have one namespace at a time (I'll never find two namespaces defined in one xml file). Using XPath I'd like to have an automatic way to add the given namespace to the namespace manager. So far, i could only get the namespace by parsing the xml file but I have a XPathNavigator instance and it should have a nice and clean way to get the namespaces, right? -- OR -- Given that I only have one namespace, somehow make XPath use the only one that is present in the xml, thus avoiding cluttering the code by always appending the namespace.
There are a few techniques that you might try; which you use will depend on exactly what information you need to get out of the document, how rigorous you want to be, and how conformant the XPath implementation you're using is. One way to get the namespace URI associated with a particular prefix is using the namespace:: axis. This will give you a namespace node whose name is the prefix and whose value is the namespace URI. For example, you could get the default namespace URI on the document element using the path: /*/namespace::*[name()=''] You might be able to use that to set up the namespace associations for your XPathNavigator. Be warned, though, that the namespace:: axis is one of those corners of XPath 1.0 that isn't always implemented. A second way of getting that namespace URI is to use the namespace-uri() function on the document element (which you've said will always be in that namespace). The expression: namespace-uri(/*) will give you that namespace. An alternative would be to forget about associating a prefix with that namespace, and just make your path namespace-free. You can do this by using the local-name() function whenever you need to refer to an element whose namespace you don't know. For example: //*[local-name() = 'Element'] You could go one step further and test the namespace URI of the element against the one of the document element, if you really wanted: //*[local-name() = 'Element' and namespace-uri() = namespace-uri(/*)] A final option, given that the namespace seems to mean nothing to you, would be to run your XML through a filter that strips out the namespaces. Then you won't have to worry about them in your XPath at all. The easiest way to do that would be simply to remove the xmlns attribute with a regular expression, but you could do something more complex if you needed to do other tidying at the same time.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/122463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20335/" ] }
122,483
In crontab, I can use an asterisk to mean every value, or "*/2" to mean every even value. Is there a way to specify every odd value? (Would something like "1+*/2" work?)
Depending on your version of cron, you should be able to do (for hours, say): 1-23/2 Going by the EXTENSIONS section in the crontab(5) manpage: Ranges can include "steps", so "1-9/2" is the same as "1,3,5,7,9". For a more portable solution, I suspect you just have to use the simple list: 1,3,5,7,9,11,13,15,17,19,21,23 But it might be easier to wrap your command in a shell script that will immediately exit if it's not called in an odd minute.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/122483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4465/" ] }
122,523
Howdy, I have a DataRow pulled out of a DataTable from a DataSet. I am accessing a column that is defined in SQL as a float datatype. I am trying to assign that value to a local variable (c# float datatype) but am getting an InvalidCastExecption DataRow exercise = _exerciseDataSet.Exercise.FindByExerciseID(65);_AccelLimit = (float)exercise["DefaultAccelLimit"]; Now, playing around with this I did make it work but it did not make any sense and it didn't feel right. _AccelLimit = (float)(double)exercise["DefaultAccelLimit"]; Can anyone explain what I am missing here?
A SQL float is a double according to the documentation for SQLDbType .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/122523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ] }
122,533
Is there any way to down-format a Subversion repository to avoid messages like this: svn: Expected format '3' of repository; found format '5' This happens when you access repositories from more than one machine, and you aren't able to use a consistent version of Subversion across all of those machines. Worse still, there are multiple repositories with various formats on different servers, and I'm not at liberty to upgrade some of these servers.~~~
If you can't use the same version of Subversion across all machines, then you should set up a server process (either svnserve or Apache) and access the repository only through the server. The server can mediate between different versions of Subversion; it's only when you're using direct repository access that you run into this issue. If the server will be an older version than the current repository format (which I don't recommend), then you'll need to export the repository using the newer version and import it using the older version.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7255/" ] }
122,571
Right now I'm making an extremely simple website- about 5 pages. Question is if it's overkill and worth the time to integrate some sort of database mapping solution or if it would be better to just use plain old JNDI. I'll have maybe a dozen things I need to read/write from the database. I guess I have a basic understanding of these technologies but it would still take a lot of referring to the documentation. Anyone else faced with the decision before? EDIT: Sorry, I should've specified JNDI to lookup the DB connection and JDBC to perform the operations.
Short answer: It depends on the complexity you want to support. Long answer: First of all, ORM ( object relational mapping - database mapping as you call it - ) and JNDI ( Java Naming and Directory Interfaces ) are two different things. The first as you already know, is used to map the Database tables to classes and objects. The second is to provide a lookup mechanism for resources, they may be DataSources, Ejb, Queues or others. Maybe your mean "JDBC". Now as for your question: If it is that simple may be it wouldn't be necessary to implement an ORM. The number tables would be around 5 - 10 at most, and the operations really simple, I guess. Probably using plain JDBC would be enough. If you use the DAO pattern you may change it later to support the ORM strategy if needed. Like this:Say you have the Employee table You create the Employee.java with all the fields of the DB by hand ( it should not take too long ) and a EmployeeDaO.java with methods like: +findById( id ): Employee+insert( Employee ) +update( Employee )+delete( Employee ) +findAll():List<Employee> And the implementation is quite straight forward: select * from employee where id = ?insert into employee ( bla, bla, bla ) values ( ? , ? , ? )update etc. etc When ( and If ) your application becomes too complex you may change the DAO implementation . For instance in the "select" method you change the code to use the ORM object that performs the operation. public Employee selectById( int id ) { // Commenting out the previous implementation... // String query = select * from employee where id = ? // execute( query ) // Using the ORM solution Session session = getSession(); Employee e = ( Employee ) session.get( Employee.clas, id ); return e;} This is just an example, in real life you may let the abstact factory create the ORM DAO, but that is offtopic. The point is you may start simple and by using the desing patterns you may change the implementation later if needed. Of course if you want to learn the technology you may start rigth away with even 1 table. The choice of one or another ( ORM solution that is ) depend basically on the technology you're using. For instance for JBoss or other opensource products Hibernate is great. It is opensource, there's a lot of resources where to learn from. But if you're using something that already has Toplink ( like the oracle application server ) or if the base is already built on Toplink you should stay with that framework. By the way, since Oracle bought BEA, they said they're replacing Kodo ( weblogic peresistence framework ) with toplink in the now called "Oracle Weblogic Application Server". I leave you some resources where you can get more info about this: In this "Patterns of Enterprise Application Architecture" book, Martin Fowler, explains where to use one or another, here is the catalog. Take a look at Data Source Architectural Patterns vs. Object-Relational Behavioral Patterns: PEAA Catalog DAO ( Data Access Object ) is part of the core J2EE patterns catalog: The DAO pattern This is a starter tutorial for Hibernate: Hibernate The official page of Toplink: Toplink Finally I "think" the good think of JPA is that you may change providers lately. Start simple and then evolve. I hope this helps.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17614/" ] }
122,583
Microsoft has chosen to not release a 64-bit version of Jet, their database driver for Access. Does anyone know of a good alternative? Here are the specific features that Jet supports that I need: Multiple users can connect to database over a network. Users can use Windows Explorer to copy the database while it is open without risking corruption. Access currently does this with enough reliability for what my customers need. Works well in C++ without requiring .Net. Alternatives I've considered that I do not think could work (though my understanding could be incorrect): SQLite: If multiple users connect to the database over a network, it will become corrupted. Firebird: Copying a database that is in use can corrupt the original database. SQL Server: Files in use are locked and cannot be copied. VistaDB: This appears to be .Net specific. Compile in 32-bit and use WOW64: There is another dependency that requires us to compile in 64-bit, even though we don't use any 64-bit functionality.
Luckily, things have changed in the past two years: Since Office 2010 is available in a 64-bit version, Microsoft had to create a 64-bit version of their Jet Engine. According to the Microsoft Customer Service blog , the Microsoft Access Database Engine 2010 Redistributable contains a 64-bit driver, which is able to access recent versions of the Microsoft Access database format.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21098/" ] }
122,595
I need your help in determining the best approach for analyzing industry-specific sentences (i.e. movie reviews) for "positive" vs "negative". I've seen libraries such as OpenNLP before, but it's too low-level - it just gives me the basic sentence composition; what I need is a higher-level structure:- hopefully with wordlists- hopefully trainable on my set of data Thanks!
What you are looking for is commonly dubbed Sentiment Analysis . Typically, sentiment analysis is not able to handle delicate subtleties, like sarcasm or irony, but it fares pretty well if you throw a large set of data at it. Sentiment analysis usually needs quite a bit of pre-processing. At least tokenization, sentence boundary detection and part-of-speech tagging. Sometimes, syntactic parsing can be important. Doing it properly is an entire branch of research in computational linguistics, and I wouldn't advise you with coming up with your own solution unless you take your time to study the field first. OpenNLP has some tools to aid sentiment analysis, but if you want something more serious, you should look into the LingPipe toolkit. It has some built-in SA-functionality and a nice tutorial . And you can train it on your own set of data, but don't think that it is entirely trivial :-). Googling for the term will probably also give you some resources to work with. If you have any more specific question, just ask, I'm watching the nlp-tag closely ;-)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ] }
122,607
I need to consume an external web service from my VB6 program. I want to be able to deploy my program without the SOAP toolkit, if possible, but that's not a requirement. I do not have the web service source and I didn't create it. It is a vendor-provided service. So outside of the SOAP toolkit, what is the best way to consume a web service from VB6?
I use this function to get data from a web service. Private Function HttpGetRequest(url As String) As DOMDocument Dim req As XMLHTTP60 Set req = New XMLHTTP60 req.Open "GET", url, False req.send "" Dim resp As DOMDocument If req.responseText <> vbNullString Then Set resp = New DOMDocument60 resp.loadXML req.responseText Else Set resp = req.responseXML End If Set HttpGetRequest = respEnd Function
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7565/" ] }
122,616
Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution.
If you can modify the string: // Note: This function returns a pointer to a substring of the original string.// If the given string was allocated dynamically, the caller must not overwrite// that pointer with the returned value, since the original pointer must be// deallocated using the same allocator with which it was allocated. The return// value must NOT be deallocated using free() etc.char *trimwhitespace(char *str){ char *end; // Trim leading space while(isspace((unsigned char)*str)) str++; if(*str == 0) // All spaces? return str; // Trim trailing space end = str + strlen(str) - 1; while(end > str && isspace((unsigned char)*end)) end--; // Write new null terminator character end[1] = '\0'; return str;} If you can't modify the string, then you can use basically the same method: // Stores the trimmed input string into the given output buffer, which must be// large enough to store the result. If it is too small, the output is// truncated.size_t trimwhitespace(char *out, size_t len, const char *str){ if(len == 0) return 0; const char *end; size_t out_size; // Trim leading space while(isspace((unsigned char)*str)) str++; if(*str == 0) // All spaces? { *out = 0; return 1; } // Trim trailing space end = str + strlen(str) - 1; while(end > str && isspace((unsigned char)*end)) end--; end++; // Set output size to minimum of trimmed string length and buffer size minus 1 out_size = (end - str) < len-1 ? (end - str) : len-1; // Copy trimmed string and add null terminator memcpy(out, str, out_size); out[out_size] = 0; return out_size;}
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/122616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14463/" ] }
122,641
I have email addresses encoded with HTML character entities. Is there anything in .NET that can convert them to plain strings?
You can use HttpUtility.HtmlDecode If you are using .NET 4.0+ you can also use WebUtility.HtmlDecode which does not require an extra assembly reference as it is available in the System.Net namespace.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/122641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ] }
122,685
That's the question: Which library can help me to access data available via WebDAV in my Java-programs? OpenSource is preferred.
The now deprecated Apache Jakarta Slide project includes a Java WebDAV client library - but this project is retired due to the lack of a developer community. Apache Jackrabbit is mentioned as alternative to Slide. You might want to check if its WebDAV library can be used instead. If you just want to access files from a WebDAV repository, you can simply use a HTTP library as WebDAV builds upon HTTP. You only need a WebDAV client library if you want to use WebDAV features like locking, directory listings or access to properties (meta-data).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ] }
122,690
I've been too lax with performing DB backups on our internal servers. Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript?
To backup a single database from the command line, use osql or sqlcmd . "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\osql.exe" -E -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak' WITH FORMAT" You'll also want to read the documentation on BACKUP and RESTORE and general procedures .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/122690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ] }
122,752
I've seen Best tools for working with DocBook XML documents , but my question is slightly different. Which is the currently recommended formatting toolchain - as opposed to editing tool - for XML DocBook? In Eric Raymond's 'The Art of Unix Programming' from 2003 (an excellent book!), the suggestion is XML-FO (XML Formatting Objects), but I've since seen suggestions here that indicated that XML-FO is no longer under development (though I can no longer find that question on StackOverflow, so maybe it was erroneous). Assume I'm primarily interested in Unix/Linux (including MacOS X), but I wouldn't automatically ignore Windows-only solutions. Is Apache's FOP the best way to go? Are there any alternatives?
I've been doing some manual writing with DocBook, under cygwin, to produce One Page HTML, Many Pages HTML, CHM and PDF. I installed the following: The docbook stylesheets (xsl) repository. xmllint, to test if the xml is correct. xsltproc, to process the xml with the stylesheets. Apache's fop , to produce PDF's.I make sure to add the installed folder to the PATH. Microsoft's HTML Help Workshop , to produce CHM's. I make sure to add the installed folder to the PATH. Edit : In the below code I'm using more than the 2 files. If someone wants a cleaned up version of the scripts and the folder structure, please contact me: guscarreno (squiggly/at) googlemail (period/dot) com I then use a configure.in: AC_INIT(Makefile.in)FOP=fop.shHHC=hhcXSLTPROC=xsltprocAC_ARG_WITH(fop, [ --with-fop Where to find Apache FOP],[ if test "x$withval" != "xno"; then FOP="$withval" fi])AC_PATH_PROG(FOP, $FOP)AC_ARG_WITH(hhc, [ --with-hhc Where to find Microsoft Help Compiler],[ if test "x$withval" != "xno"; then HHC="$withval" fi])AC_PATH_PROG(HHC, $HHC)AC_ARG_WITH(xsltproc, [ --with-xsltproc Where to find xsltproc],[ if test "x$withval" != "xno"; then XSLTPROC="$withval" fi])AC_PATH_PROG(XSLTPROC, $XSLTPROC)AC_SUBST(FOP)AC_SUBST(HHC)AC_SUBST(XSLTPROC)HERE=`pwd`AC_SUBST(HERE)AC_OUTPUT(Makefile)cat > config.nice <<EOT#!/bin/sh./configure \ --with-fop='$FOP' \ --with-hhc='$HHC' \ --with-xsltproc='$XSLTPROC' \EOTchmod +x config.nice and a Makefile.in: FOP=@FOP@HHC=@HHC@XSLTPROC=@XSLTPROC@HERE=@HERE@# Subdirs that contain docsDOCS=appendixes chapters reference XML_CATALOG_FILES=./build/docbook-xsl-1.71.0/catalog.xmlexport XML_CATALOG_FILESall: entities.ent manual.xml htmlclean:@echo -e "\n=== Cleaning\n"@-rm -f html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm entities.ent .ent@echo -e "Done.\n"dist-clean:@echo -e "\n=== Restoring defaults\n"@-rm -rf .ent autom4te.cache config.* configure Makefile html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm build/docbook-xsl-1.71.0@echo -e "Done.\n"entities.ent: ./build/mkentities.sh $(DOCS)@echo -e "\n=== Creating entities\n"@./build/mkentities.sh $(DOCS) > .ent@if [ ! -f entities.ent ] || [ ! cmp entities.ent .ent ]; then mv .ent entities.ent ; fi@echo -e "Done.\n"# Build the docs in chm formatchm: chm/htmlhelp.hpp@echo -e "\n=== Creating CHM\n"@echo logo.png >> chm/htmlhelp.hhp@echo arrow.gif >> chm/htmlhelp.hhp@-cd chm && "$(HHC)" htmlhelp.hhp@echo -e "Done.\n"chm/htmlhelp.hpp: entities.ent build/docbook-xsl manual.xml build/chm.xsl@echo -e "\n=== Creating input for CHM\n"@"$(XSLTPROC)" --output ./chm/index.html ./build/chm.xsl manual.xml# Build the docs in HTML formathtml: html/index.htmlhtml/index.html: entities.ent build/docbook-xsl manual.xml build/html.xsl@echo -e "\n=== Creating HTML\n"@"$(XSLTPROC)" --output ./html/index.html ./build/html.xsl manual.xml@echo -e "Done.\n"# Build the docs in PDF formatpdf: pdf/manual.fo@echo -e "\n=== Creating PDF\n"@"$(FOP)" ./pdf/manual.fo ./pdf/manual.pdf@echo -e "Done.\n"pdf/manual.fo: entities.ent build/docbook-xsl manual.xml build/pdf.xsl@echo -e "\n=== Creating input for PDF\n"@"$(XSLTPROC)" --output ./pdf/manual.fo ./build/pdf.xsl manual.xmlcheck: manual.xml@echo -e "\n=== Checking correctness of manual\n"@xmllint --valid --noout --postvalid manual.xml@echo -e "Done.\n"# need to touch the dir because the timestamp in the tarball# is older than that of the tarball :)build/docbook-xsl: build/docbook-xsl-1.71.0.tar.gz@echo -e "\n=== Un-taring docbook-xsl\n"@cd build && tar xzf docbook-xsl-1.71.0.tar.gz && touch docbook-xsl-1.71.0 to automate the production of the above mentioned file outputs. I prefer to use a nix approach to the scripting just because the toolset is more easy to find and use, not to mention easier to chain.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15168/" ] }
122,772
When I try to display the contents of a LOB (large object) column in SQL*Plus, it is truncated. How do I display the whole thing?
SQL> set long 30000SQL> show longlong 30000
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/122772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2391/" ] }
122,782
I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines: boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
I read (well scanned) through the development list discussion . There's no easy solution. To sum up: Wrapping header files in a namespace declaration namespace boost_1_36_0 { #include <boost_1_36_0/boost/regex.hpp>}namespace boost_1_35_0 { #include <boost_1_35_0/boost/shared_ptr.hpp>} Requires modifying source files Doesn't allow for both versions to be included in the same translation unit, due to the fact that macros do not respect namespaces. Defining boost before including headers #define boost boost_1_36_0 #include <boost_1_36_0/boost/regex.hpp>#undef boost#define boost boost_1_35_0 #include <boost_1_35_0/boost/shared_ptr.hpp>#undef boost Source files can simply be compiled with -Dboost=boost_1_36_0 Still doesn't address macro conflicts in a single translation unit. Some internal header file inclusions may be messed up, since this sort of thing does happen. #if defined(SOME_CONDITION)# define HEADER <boost/some/header.hpp>#else# define HEADER <boost/some/other/header.hpp>#endif But it may be easy enough to work around those cases. Modifying the entire boost library to replace namespace boost {..} with namespace boost_1_36_0 {...} and then providing a namespace alias. Replace all BOOST_XYZ macros and their uses with BOOST_1_36_0_XYZ macros. This would likely work if you were willing to put into the effort.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8701/" ] }
122,799
There is no summary available of the big O notation for operations on the most common data structures including arrays, linked lists, hash tables etc.
Information on this topic is now available on Wikipedia at: Search data structure +----------------------+----------+------------+----------+--------------+| | Insert | Delete | Search | Space Usage |+----------------------+----------+------------+----------+--------------+| Unsorted array | O(1) | O(1) | O(n) | O(n) || Value-indexed array | O(1) | O(1) | O(1) | O(n) || Sorted array | O(n) | O(n) | O(log n) | O(n) || Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) || Sorted linked list | O(n)* | O(1)* | O(n) | O(n) || Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) || Heap | O(log n) | O(log n)** | O(n) | O(n) || Hash table | O(1) | O(1) | O(1) | O(n) |+----------------------+----------+------------+----------+--------------+ * The cost to add or delete an element into a known location in the list (i.e. if you have an iterator to the location) is O(1). If you don't know the location, then you need to traverse the list to the location of deletion/insertion, which takes O(n) time. ** The deletion cost is O(log n) for the minimum or maximum, O(n) for an arbitrary element.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340748/" ] }
122,815
I'm looking for a groovy equivalent on .NET http://boo.codehaus.org/ So far Boo looks interesting, but it is statically typed, yet does include some of the metaprogramming features I'd be looking for. Can anyone comment on the experience of using Boo and is it worth looking into for more than hobby purposes at a 1.0 Version? Edit : Changed BOO to Boo
Information on this topic is now available on Wikipedia at: Search data structure +----------------------+----------+------------+----------+--------------+| | Insert | Delete | Search | Space Usage |+----------------------+----------+------------+----------+--------------+| Unsorted array | O(1) | O(1) | O(n) | O(n) || Value-indexed array | O(1) | O(1) | O(1) | O(n) || Sorted array | O(n) | O(n) | O(log n) | O(n) || Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) || Sorted linked list | O(n)* | O(1)* | O(n) | O(n) || Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) || Heap | O(log n) | O(log n)** | O(n) | O(n) || Hash table | O(1) | O(1) | O(1) | O(n) |+----------------------+----------+------------+----------+--------------+ * The cost to add or delete an element into a known location in the list (i.e. if you have an iterator to the location) is O(1). If you don't know the location, then you need to traverse the list to the location of deletion/insertion, which takes O(n) time. ** The deletion cost is O(log n) for the minimum or maximum, O(n) for an arbitrary element.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/122815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129162/" ] }
122,853
I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?
Yes, assuming the HTTP server you're talking to supports/allows this: public long GetFileSize(string url){ long result = -1; System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.Method = "HEAD"; using (System.Net.WebResponse resp = req.GetResponse()) { if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength)) { result = ContentLength; } } return result;} If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/122853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
122,855
Anyone know if it is possible to write an app that uses the Java Sound API on a system that doesn't actually have a hardware sound device? I have some code I've written based on the API that manipulates some audio and plays the result but I am now trying to run this in a server environment, where the audio will be recorded to a file instead of played to line out. The server I'm running on has no sound card, and I seem to be running into roadblocks with Java Sound not being able to allocate any lines if there is not a Mixer that supports it. (And with no hardware devices I'm getting no Mixers.) Any info would be much appreciated - thanks.
Yes, assuming the HTTP server you're talking to supports/allows this: public long GetFileSize(string url){ long result = -1; System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.Method = "HEAD"; using (System.Net.WebResponse resp = req.GetResponse()) { if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength)) { result = ContentLength; } } return result;} If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/122855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8063/" ] }
122,877
So I've got some C code: #include <stdio.h>#include <string.h>/* putting one of the "char*"s here causes a segfault */void main() { char* path = "/temp"; char* temp; strcpy(temp, path);} This compiles, runs, and behaves as it looks. However, if one or both of the character pointers is declared as global variable, strcpy results in a segmentation fault. Why does this happen? Evidently there's an error in my understanding of scope.
As other posters mentioned, the root of the problem is that temp is uninitialized. When declared as an automatic variable on the stack it will contain whatever garbage happens to be in that memory location. Apparently for the compiler+CPU+OS you are running, the garbage at that location is a valid pointer. The strcpy "succeeds" in that it does not segfault, but really it copied a string to some arbitrary location elsewhere in memory. This kind of memory corruption problem strikes fear into the hearts of C programmers everywhere as it is extraordinarily difficult to debug. When you move the temp variable declaration to global scope, it is placed in the BSS section and automatically zeroed. Attempts to dereference *temp then result in a segfault. When you move *path to global scope, then *temp moves up one location on the stack. The garbage at that location is apparently not a valid pointer, and so dereferencing *temp results in a segfault.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12926/" ] }
122,882
What is the proper technique to have ThreadA signal ThreadB of some event, without having ThreadB sit blocked waiting for an event to happen? i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up. i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne(). i considered having a delegate callback, but a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, andb) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against. i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls Timer.Enabled = true; but that seems like a hack. In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms. i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem. What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen?
Here's a code sample for the System.ComponentModel.BackgroundWorker class. private static BackgroundWorker worker = new BackgroundWorker(); static void Main(string[] args) { worker.DoWork += worker_DoWork; worker.RunWorkerCompleted += worker_RunWorkerCompleted; worker.ProgressChanged += worker_ProgressChanged; worker.WorkerReportsProgress = true; Console.WriteLine("Starting application."); worker.RunWorkerAsync(); Console.ReadKey(); } static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { Console.WriteLine("Progress."); } static void worker_DoWork(object sender, DoWorkEventArgs e) { Console.WriteLine("Starting doing some work now."); for (int i = 0; i < 5; i++) { Thread.Sleep(1000); worker.ReportProgress(i); } } static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { Console.WriteLine("Done now."); }
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ] }
122,883
Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them. I am talking about interfaces in a context of interfaces vs. abstract classes.
Interfaces allow you to program against a "description" instead of a type, which allows you to more-loosely associate elements of your software. Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says "is that USB?" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB. In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this: public void Paint(Car car, System.Drawing.Color color)... This would work until your client said "now I want to paint trucks" so you could do this: public void Paint (Vehicle vehicle, System.Drawing.Color color)... this would broaden your app... until your client said "now I want to paint houses!" What you could have done from the very beginning is created an interface: public interface IPaintable{ void Paint(System.Drawing.Color color);} ...and passed that to your routine: public void Paint(IPaintable item, System.Drawing.Color color){ item.Paint(color);} Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/122883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16820/" ] }
122,909
I have a file. I want to get its contents into a blob column in my oracle database or into a blob variable in my PL/SQL program. What is the best way to do that?
To do it entirely in PL/SQL, the file would need to be on the server, located in a directory which you'd need to define in the database. Create the following objects: CREATE OR REPLACE DIRECTORY BLOB_DIR AS '/oracle/base/lobs'/CREATE OR REPLACE PROCEDURE BLOB_LOADAS lBlob BLOB; lFile BFILE := BFILENAME('BLOB_DIR', 'filename');BEGIN INSERT INTO table (id, your_blob) VALUES (xxx, empty_blob()) RETURNING your_blob INTO lBlob; DBMS_LOB.OPEN(lFile, DBMS_LOB.LOB_READONLY); DBMS_LOB.OPEN(lBlob, DBMS_LOB.LOB_READWRITE); DBMS_LOB.LOADFROMFILE(DEST_LOB => lBlob, SRC_LOB => lFile, AMOUNT => DBMS_LOB.GETLENGTH(lFile)); DBMS_LOB.CLOSE(lFile); DBMS_LOB.CLOSE(lBlob); COMMIT;END;/
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13693/" ] }
122,942
I have a table UserAliases ( UserId, Alias ) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column. Example: UserId/Alias 1/MrX 1/MrY 1/MrA 2/Abc 2/Xyz I want the query result in the following format: UserId/Alias 1/ MrX, MrY, MrA 2/ Abc, Xyz Thank you. I'm using SQL Server 2005. p.s. actual T-SQL query would be appreciated :)
You can use a function with COALESCE. CREATE FUNCTION [dbo].[GetAliasesById]( @userID int)RETURNS varchar(max)ASBEGIN declare @output varchar(max) select @output = COALESCE(@output + ', ', '') + alias from UserAliases where userid = @userID return @outputENDGOSELECT UserID, dbo.GetAliasesByID(UserID)FROM UserAliasesGROUP BY UserIDGO
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/122942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3661/" ] }
122,982
Which checksum algorithm can you recommend in the following use case? I want to generate checksums of small JPEG files (~8 kB each) to check if the content changed. Using the filesystem's date modified is unfortunately not an option. The checksum need not be cryptographically strong but it should robustly indicate changes of any size. The second criterion is speed since it should be possible to process at least hundreds of images per second (on a modern CPU). The calculation will be done on a server with several clients. The clients send the images over Gigabit TCP to the server. So there's no disk I/O as bottleneck.
If you have many small files, your bottleneck is going to be file I/O and probably not a checksum algorithm. A list of hash functions (which can be thought of as a checksum) can be found here . Is there any reason you can't use the filesystem's date modified to determine if a file has changed? That would probably be faster.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/122982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ] }
123,012
Pros. and cons? how long do you use it? What about jambi?
I've used Qt on a couple of projects I did in c++ on several platforms over a period of seven years. I think it works pretty well and definitely was quicker for me to develop a decent GUI app on the Mac than plodding through a language I didn't know (Objective-C) at the time. I think the signal/slot mechanism is a bit funky but isn't horrible. Once you're use it for a bit, it's not a show stopper. The connection stuff is easy to bungle up (or at least it was) and it's always good to check the return on those because your app will go merrily on its way and not tell you that it didn't work. I've never used jambi.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
123,057
I have been having some issues with LINQ-To-SQL around memory usage. I'm using it in a Windows Service to do some processing, and I'm looping through a large amount of data that I'm pulling back from the context. Yes - I know I could do this with a stored procedure but there are reasons why that would be a less than ideal solution. Anyway, what I see basically is memory is not being released even after I call context.SubmitChanges() . So I end up having to do all sorts of weird things like only pull back 100 records at time, or create several contexts and have them all do separate tasks. If I keep the same DataContext and use it later for other calls, it just eats up more and more memory. Even if I call Clear() on the " var tableRows " array that the query returns to me, set it to null, and call SYstem.GC.Collect() - it still doesn't release the memory. Now I've read some about how you should use DataContexts quickly and dispose of them quickly, but it seems like their ought to be a way to force the context to dump all its data (or all its tracking data for a particular table) at a certain point to guarantee the memory is free. Anyone know what steps guarantee that the memory is released?
A DataContext tracks all the objects it ever fetched. It won't release this until it is garbage collected. Also, as it implements IDisposable , you must call Dispose or use the using statement. This is the right way to go: using(DataContext myDC = new DataContext){ // Do stuff} //DataContext is disposed
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146/" ] }
123,078
On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?
You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters. For example: class Booking < ActiveRecord::Base has_many :booking_payments .... def destroy raise "Cannot delete booking with payments" unless booking_payments.count == 0 # ... ok, go ahead and destroy super endend Alternatively you can use the before_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead. def before_destroy return true if booking_payments.count == 0 errors.add :base, "Cannot delete booking with payments" # or errors.add_to_base in Rails 2 false # Rails 5 throw(:abort)end myBooking.destroy will now return false, and myBooking.errors will be populated on return.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/123078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21317/" ] }
123,080
I know that this is somewhat subjective, but I wonder if there is a generally accepted standard for naming assemblies which contain some "core" functions. Let's say you got a larger Projects, with Assemblies like Company.Product.WebControls.dll Company.Product.Net.dll Company.Product.UserPages.dll and you have a Bunch of "Core" classes, like the Global Error Handler, the global Logging functionality etc. How would such an assembly generally named? Here are some things I had in mind: Company.Product.dll Company.Product.Core.dll Company.Product.Global.dll Company.Product.Administration.dll Now, while "just pick one and go on" will not cause Armageddon, I'd still like to know if there is an "accepted" way to name those assemblies.
With .Net this is relatively easy to change, so I'd go with convenience. Fewer, larger, assemblies compile quicker than many small ones, so I'd start with your 'core' stuff as a namespace inside Company.Product.dll, and split it out later if you need to.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
123,088
C#6 Update In C#6 ?. is now a language feature : // C#1-5propertyValue1 = myObject != null ? myObject.StringProperty : null; // C#6propertyValue1 = myObject?.StringProperty; The question below still applies to older versions, but if developing a new application using the new ?. operator is far better practice. Original Question: I regularly want to access properties on possibly null objects: string propertyValue1 = null;if( myObject1 != null ) propertyValue1 = myObject1.StringProperty;int propertyValue2 = 0;if( myObject2 != null ) propertyValue2 = myObject2.IntProperty; And so on... I use this so often that I have a snippet for it. You can shorten this to some extent with an inline if: propertyValue1 = myObject != null ? myObject.StringProperty : null; However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance: propertyValue1 = myObject != null ? (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null; What I really want is ?? style syntax, which works great for directly null types: int? i = SomeFunctionWhichMightReturnNull();propertyValue2 = i ?? 0; So I came up with the following: public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action, TResult valueIfNull ) where T : class{ if ( input != null ) return action( input ); else return valueIfNull;}//lets us have a null default if the type is nullablepublic static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action ) where T : class where TResult : class{ return input.IfNotNull( action, null ); } This lets me us this syntax: propertyValue1 = myObject1.IfNotNull( x => x.StringProperty );propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);//or one with multiple levelspropertyValue1 = myObject.IfNotNull( o => o.ObjectProp.IfNotNull( p => p.StringProperty ) ); This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace. This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties: if( ( obj1 == null && obj2 == null ) || ( obj1 != null && obj2 != null && obj1.Property == obj2.Property ) ) ...//becomesif( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property ) ... What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions? I guess what I really want here is a compiler/language extension: propertyValue1 = myObject != null ? myObject.StringProperty : null;//becomespropertyValue1 = myObject?StringProperty; This would make the complex case far easier: propertyValue1 = myObject != null ? (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null//becomespropertyValue1 = myObject?ObjectProp?StringProperty; This would only work for value types, but you could return nullable equivalents: int? propertyValue2 = myObject?ObjectProp?IntProperty;//orint propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;
We independently came up with the exact same extension method name and implementation: Null-propagating extension method . So we don't think it's confusing or an abuse of extension methods. I would write your "multiple levels" example with chaining as follows: propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty); There's a now-closed bug on Microsoft Connect that proposed "?." as a new C# operator that would perform this null propagation. Mads Torgersen (from the C# language team) briefly explained why they won't implement it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ] }
123,198
How do I copy a file in Python?
shutil has many methods you can use. One of which is: import shutilshutil.copyfile(src, dst)# 2nd optionshutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp Copy the contents of the file named src to a file named dst . Both src and dst need to be the entire filename of the files, including path. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. With copy , src and dst are path names given as str s. Another shutil method to look at is shutil.copy2() . It's similar but preserves more metadata (e.g. time stamps). If you use os.path operations, use copy rather than copyfile . copyfile will only accept strings.
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/123198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ] }
123,234
Ideally something that will work with Oracle, MS SQL Server, MySQL and Posgress.
if you mean common lisp by lisp, then there's cl-rdbms . it is heavily tested on postgres (uses postmodern as the backend lib), it has a toy sqlite backend and it also has an OCI based oracle backend. it supports abstracting away the different sql dialects, has an sql quasi-quote syntax extension installable on e.g. the [] characters. i'm not sure if it's the best, and i'm biased anyway... :) but we ended up rolling our own lib after using clsql for a while, which is i think the most widely used sql lib for cl. see cliki page about sql for a further reference.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7780/" ] }
123,235
I was trying to remove all the lines of a file except the last line but the following command did not work, although file.txt is not empty. $cat file.txt |tail -1 > file.txt$cat file.txt Why is it so?
Redirecting from a file through a pipeline back to the same file is unsafe; if file.txt is overwritten by the shell when setting up the last stage of the pipeline before tail starts reading off the first stage, you end up with empty output. Do the following instead: tail -1 file.txt >file.txt.new && mv file.txt.new file.txt ...well, actually, don't do that in production code; particularly if you're in a security-sensitive environment and running as root, the following is more appropriate: tempfile="$(mktemp file.txt.XXXXXX)"chown --reference=file.txt -- "$tempfile"chmod --reference=file.txt -- "$tempfile"tail -1 file.txt >"$tempfile" && mv -- "$tempfile" file.txt Another approach (avoiding temporary files, unless <<< implicitly creates them on your platform) is the following: lastline="$(tail -1 file.txt)"; cat >file.txt <<<"$lastline" (The above implementation is bash-specific, but works in cases where echo does not -- such as when the last line contains "--version", for instance). Finally, one can use sponge from moreutils : tail -1 file.txt | sponge file.txt
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
123,263
I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?
string[] formats = {"yyyyMMdd", "MM/dd/yy"};var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None); or DateTime result;string[] formats = {"yyyyMMdd", "MM/dd/yy"};DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result); More info in the MSDN documentation on ParseExact and TryParseExact .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/123263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20625/" ] }
123,295
Do you always follow the convention of putting branches, tags and trunk directories at the top level of your Subversion repository? Lately, I have stopped bothering and nothing bad has happened (yet)! It should be possible to move directory trees around if there's ever a need to create them. Am I building up trouble for later?
Have you tried branching or tagging yet? Until then, there's no problem. However, an added benefit of using the branches,tags,trunk convention is that it's exactly that -- a convention. People expect to see that, so they know what to do when they need to fork.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7255/" ] }
123,323
How many messages does the queue for a standard window hold? What happens when the queue overflows? The documentation for GetMessage and relatives doesn't say anything about this, and PeekMessage only gives you a yes/no for certain classes of messages, not a message count. This page says that the queues are implemented using memory-mapped files, and that there is no message count limit, but that page is about WinCE. Does this apply to desktop Win32 as well?
10000 by default, but it can be adjusted via the registry. If queue overflows, PostMessage fails. Documentation here: PostMessage function on MSDN
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1319/" ] }
123,335
what configuration needs to be tweaked, and where does it live, in order to increase the maximum allowed post size?
Apache Tomcat by default sets a limit on the maximum size of HTTP POST requests it accepts. In Tomcat 5, this limit is set to 2 MB. When you try to upload files larger than 2 MB, this error can occur. The solution is to reconfigure Tomcat to accept larger POST requests, either by increasing the limit, or by disabling it. This can be done by editing [TOMCAT_DIR]/conf/server.xml. Set the Tomcat configuration parameter maxPostSize for the HTTPConnector to a larger value (in bytes) to increase the limit. Setting it to 0 in will disable the size check. See the Tomcat Configuration Reference for more information.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/123335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13973/" ] }
123,336
How can you strip non-ASCII characters from a string? (in C#)
string s = "søme string";s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty);
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/123336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3784/" ] }
123,337
Do I have to restart IIS if I drop a new DLL in the bin of my virtual directory?
No you do not have to, the application will recycle, but an IISReset is NOT needed
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11907/" ] }
123,378
Is there a good command-line UNIX charting / graphing / plotting tool out there? I'm looking for something that will plot xy points on an ASCII graph. Just to clarify, I'm looking for something that will output a graph in ASCII (like ascii-art style), so I can use it over an interactive shell session without needing X.
Try gnuplot . It has very powerful graphing possibilities. It can output to your terminal in the following way: gnuplot> set terminal dumbTerminal type set to 'dumb'Options are 'feed 79 24'gnuplot> plot sin(x) 1 ++----------------**---------------+----**-----------+--------**-----++ + *+ * + * * + sin(x) ****** + 0.8 ++ * * * * * * ++ | * * * * * * | 0.6 ++ * * * * * * ++ * * * * * * * | 0.4 +* * * * * * * ++ |* * * * * * * | 0.2 +* * * * * * * ++ | * * * * * * * | 0 ++* * * * * * *++ | * * * * * * *|-0.2 ++ * * * * * * *+ | * * * * * * *|-0.4 ++ * * * * * * *+ | * * * * * * *-0.6 ++ * * * * * * ++ | * * * * * * |-0.8 ++ * * * * * * ++ + * * + * * + * * + -1 ++-----**---------+----------**----+---------------**+---------------++ -10 -5 0 5 10
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/123378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21339/" ] }
123,391
I would like to know how to unload an assembly that is loaded into the main AppDomain. I have the following code: var assembly = Assembly.LoadFrom( FilePathHere ); I need/want to be able to unload this assembly when I am done. Thanks for your help.
For .net versions core 3.0 and later: You can now unload assemblies. Note that appdomains are no longer available in .net core. Instead, you can create one or more AssemblyLoadContext, load your assemblies via that context, then unload that context. See AssemblyLoadContext , or this tutorial that simulates loading a plugin then unloading it . For .net versions before .net core 3, including netframework 4 and lower You can not unload an assembly from an appdomain. You can destroy appdomains, but once an assembly is loaded into an appdomain, it's there for the life of the appdomain. See Jason Zander's explanation of Why isn't there an Assembly.Unload method? If you are using 3.5, you can use the AddIn Framework to make it easier to manage/call into different AppDomains (which you can unload, unloading all the assemblies). If you are using versions before that, you need to create a new appdomain yourself to unload it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14164/" ] }
123,401
Using jQuery, how do you bind a click event to a table cell (below, class="expand" ) that will change the image src (which is in the clicked cell - original will be plus.gif, alternating with minus.gif) and hide/show the row immediately below it based on whether that row has a class of hide . (show it if it has a class of "hide" and hide if it does not have a class of "hide"). I am flexible with changing ids and classes in the markup. Thanks Table rows <tr> <td class="expand"><img src="plus.gif"/></td> <td>Data1</td><td>Data2</td><td>Data3</td></tr><tr class="show hide"> <td> </td> <td>Data4</td><td>Data5</td><td>Data6</td></tr>
You don't need the show and hide tags: $(document).ready(function(){ $('.expand').click(function() { if( $(this).hasClass('hidden') ) $('img', this).attr("src", "plus.jpg"); else $('img', this).attr("src", "minus.jpg"); $(this).toggleClass('hidden'); $(this).parent().next().toggle(); });}); edit: Okay, I added the code for changing the image. That's just one way to do it. I added a class to the expand attribute as a tag when the row that follows is hidden and removed it when the row was shown.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ] }
123,462
Does anyone know of a good tool for debugging JSPs from within Eclipse? I'd like to be able to set and watch breakpoints, step through the Java code/tags, etc within Eclipse while the app is running (under JBoss in my case). Presumably, it's reasonably straightforward to debug the servlet class that's generated from a JSP, but it's also fairly unappealing.
If you have WTP installed, you can set breakpoints within a JSP and they work fine in a regular "remote debug" session. However, once you've stopped on a breakpoint, stepping through the code is nigh on impossible and finding whatever it is that you wish to inspect takes a lot of digging around in the "Variables" view.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ] }
123,499
I've got the directive <VirtualHost *> <Location /> AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET> Require valid-user </Limit> </Location> WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some.example.org</VirtualHost> I'd like to know in the /some/script.wsgi def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/plain'), ]) return ['Hello'] What user is logged in. How do I do that?
add WSGIPassAuthorization On : <VirtualHost *> <Location /> AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET> Require valid-user </Limit> </Location> WSGIPassAuthorization On WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some.example.org</VirtualHost> Then just read environ['REMOTE_USER'] : def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/plain'), ]) return ['Hello %s' % environ['REMOTE_USER']] More information at mod_wsgi documentation .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19435/" ] }
123,503
I'm writing an iPhone app with Cocoa in xcode. I can't find any tutorials or sample code that shows how to take photos with the built in camera. How do I do this? Where can I find good info? Thanks!
Just Copy and paste following code into your project to get fully implemented functionality. where takePhoto and chooseFromLibrary are my own method names which will be called on button touch. Make sure to reference outlets of appropriate buttons to these methods. -(IBAction)takePhoto :(id)sender{ UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera]; } // image picker needs a delegate, [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES];}-(IBAction)chooseFromLibrary:(id)sender{ UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; // image picker needs a delegate so we can respond to its messages [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES];}//delegate methode will be called after picking photo either from camera or library- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ [self dismissModalViewControllerAnimated:YES]; UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; [myImageView setImage:image]; // "myImageView" name of any UIImageView.}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
123,504
In wxWidgets, how can you find the pixels per inch on a wxDC? I'd like to be able to scale things by a real world number like inches. That often makes it easier to use the same code for printing to the screen and the printer.
Just Copy and paste following code into your project to get fully implemented functionality. where takePhoto and chooseFromLibrary are my own method names which will be called on button touch. Make sure to reference outlets of appropriate buttons to these methods. -(IBAction)takePhoto :(id)sender{ UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera]; } // image picker needs a delegate, [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES];}-(IBAction)chooseFromLibrary:(id)sender{ UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; // image picker needs a delegate so we can respond to its messages [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES];}//delegate methode will be called after picking photo either from camera or library- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ [self dismissModalViewControllerAnimated:YES]; UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; [myImageView setImage:image]; // "myImageView" name of any UIImageView.}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ] }
123,529
A site I'm working on has Flash headers (using swfobject to embed them). Now I'm required to code in a bit of HTML that's supposed to overlap the Flash movie. I've tried setting z-index on the Flash element's container and the (absolutely positioned) div but it keeps "vanishing" behind the Flash movie. I'm hoping for a CSS solution, but if there's a bit of JS magic that will do the trick, I'm up for it. Update: Thanks, setting wmode to "transparent" mostly fixed it. Only Safari/Mac still hid the div behind the flash on first show. When I'd switch to another app and back it would be in front. I was able to fix this by setting the div's initial styles to display: none; and make it visible via JS half a second after the page has loaded.
Make sure the FlashVar "wmode" is set to "transparent" or "opaque," but NOT the default, "windowed"... then you should be able to use CSS z-index
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9438/" ] }
123,557
I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 step?
Oh ye of little faith: SELECT *, IDENTITY( int ) AS idcol INTO #newtable FROM oldtable http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/123557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19305/" ] }
123,558
Is it possible to disable a trigger for a batch of commands and then enable it when the batch is done? I'm sure I could drop the trigger and re-add it but I was wondering if there was another way.
DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }ON { object_name | DATABASE | ALL SERVER } [ ; ] http://msdn.microsoft.com/en-us/library/ms189748(SQL.90).aspx followed by the inverse: ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }ON { object_name | DATABASE | ALL SERVER } [ ; ] http://msdn.microsoft.com/en-us/library/ms182706(SQL.90).aspx
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/123558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4068/" ] }
123,559
I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following: 1-234-567-8901 1-234-567-8901 x1234 1-234-567-8901 ext1234 1 (234) 567-8901 1.234.567.8901 1/234/567/8901 12345678901 I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.
Better option... just strip all non-digit characters on input (except 'x' and leading '+' signs), taking care because of the British tendency to write numbers in the non-standard form +44 (0) ... when asked to use the international prefix (in that specific case, you should discard the (0) entirely). Then, you end up with values like: 12345678901 12345678901x1234 345678901x1234 12344678901 12345678901 12345678901 12345678901 +4112345678 +441234567890 Then when you display, reformat to your hearts content. e.g. 1 (234) 567-8901 1 (234) 567-8901 x1234
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/123559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765/" ] }
123,598
I have an Enum called Status defined as such: public enum Status { VALID("valid"), OLD("old"); private final String val; Status(String val) { this.val = val; } public String getStatus() { return val; }} I would like to access the value of VALID from a JSTL tag. Specifically the test attribute of the <c:when> tag. E.g. <c:when test="${dp.status eq Status.VALID"> I'm not sure if this is possible.
A simple comparison against string works: <c:when test="${someModel.status == 'OLD'}">
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/123598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17337/" ] }
123,657
I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype. I don't know if it depends on the technologies used, but I'll use Tomcat 5.5 I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)
I think what you're looking for here is request, session or application data. In a servlet you can add an object as an attribute to the request object, session object or servlet context object: protected void doGet(HttpServletRequest request, HttpServletResponse response) { String shared = "shared"; request.setAttribute("sharedId", shared); // add to request request.getSession().setAttribute("sharedId", shared); // add to session this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context request.getRequestDispatcher("/URLofOtherServlet").forward(request, response);} If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished: request.getAttribute("sharedId"); If you put it in the session it will be available to all the servlets going forward but the value will be tied to the user: request.getSession().getAttribute("sharedId"); Until the session expires based on inactivity from the user. Is reset by you: request.getSession().invalidate(); Or one servlet removes it from scope: request.getSession().removeAttribute("sharedId"); If you put it in the servlet context it will be available while the application is running: this.getServletConfig().getServletContext().getAttribute("sharedId"); Until you remove it: this.getServletConfig().getServletContext().removeAttribute("sharedId");
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/123657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19689/" ] }
123,661
Consider a hypothetical method of an object that does stuff for you: public class DoesStuff{ BackgroundWorker _worker = new BackgroundWorker(); ... public void CancelDoingStuff() { _worker.CancelAsync(); //todo: Figure out a way to wait for BackgroundWorker to be cancelled. }} How can one wait for a BackgroundWorker to be done? In the past people have tried: while (_worker.IsBusy){ Sleep(100);} But this deadlocks , because IsBusy is not cleared until after the RunWorkerCompleted event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.) Others have add suggested kludging it into: while (_worker.IsBusy){ Application.DoEvents();} The problem with that is that is Application.DoEvents() causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant). I would hope to use some solution involving Event synchronization objects, where the code waits for an event - that the worker's RunWorkerCompleted event handlers sets. Something like: Event _workerDoneEvent = new WaitHandle();public void CancelDoingStuff(){ _worker.CancelAsync(); _workerDoneEvent.WaitOne();}private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e){ _workerDoneEvent.SetEvent();} But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event. So how can you wait for an BackgroundWorker to finish? Update People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as: BackgroundWorker worker = new BackgroundWorker();worker.DoWork += MyWork;worker.RunWorkerAsync();WaitForWorkerToFinish(worker); That is not it, that is not what I'm doing, and that is not what is being asked here. If that were the case, there would be no point in using a background worker.
If I understand your requirement right, you could do something like this (code not tested, but shows the general idea): private BackgroundWorker worker = new BackgroundWorker();private AutoResetEvent _resetEvent = new AutoResetEvent(false);public Form1(){ InitializeComponent(); worker.DoWork += worker_DoWork;}public void Cancel(){ worker.CancelAsync(); _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made}void worker_DoWork(object sender, DoWorkEventArgs e){ while(!e.Cancel) { // do something } _resetEvent.Set(); // signal that worker is done}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/123661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ] }
123,718
How can i check to see if a static class has been declared?exGiven the class class bob { function yippie() { echo "skippie"; }} later in code how do i check: if(is_a_valid_static_object(bob)) { bob::yippie();} so i don't get:Fatal error: Class 'bob' not found in file.php on line 3
You can also check for existence of a specific method, even without instantiating the class echo method_exists( bob, 'yippie' ) ? 'yes' : 'no'; If you want to go one step further and verify that "yippie" is actually static, use the Reflection API (PHP5 only) try { $method = new ReflectionMethod( 'bob::yippie' ); if ( $method->isStatic() ) { // verified that bob::yippie is defined AND static, proceed }}catch ( ReflectionException $e ){ // method does not exist echo $e->getMessage();} or, you could combine the two approaches if ( method_exists( bob, 'yippie' ) ){ $method = new ReflectionMethod( 'bob::yippie' ); if ( $method->isStatic() ) { // verified that bob::yippie is defined AND static, proceed }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ] }
123,726
How to disable standard ASP.NET handling of 401 response code (redirecting to login page) for AJAX/JSON requests? For web-pages it's okay, but for AJAX I need to get right 401 error code instead of good looking 302/200 for login page. Update :There are several solutions from Phil Haack, PM of ASP.NET MVC - http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx
The ASP.NET runtime is developed so that it always will redirect the user if the HttpResponse.StatusCode is set to 401, but only if the <authentication /> section of the Web.config is found. Removing the authentication section will require you to implement the redirection to the login page in your attribute, but this shouldn't be a big deal.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12045/" ] }
123,758
Let's say I have the following class X where I want to return access to an internal member: class Z{ // details};class X{ std::vector<Z> vecZ;public: Z& Z(size_t index) { // massive amounts of code for validating index Z& ret = vecZ[index]; // even more code for determining that the Z instance // at index is *exactly* the right sort of Z (a process // which involves calculating leap years in which // religious holidays fall on Tuesdays for // the next thousand years or so) return ret; } const Z& Z(size_t index) const { // identical to non-const X::Z(), except printed in // a lighter shade of gray since // we're running low on toner by this point }}; The two member functions X::Z() and X::Z() const have identical code inside the braces. This is duplicate code and can cause maintenance problems for long functions with complex logic . Is there a way to avoid this code duplication?
For a detailed explanation, please see the heading "Avoid Duplication in const and Non- const Member Function," on p. 23, in Item 3 "Use const whenever possible," in Effective C++ , 3d ed by Scott Meyers, ISBN-13: 9780321334879. Here's Meyers' solution (simplified): struct C { const char & get() const { return c; } char & get() { return const_cast<char &>(static_cast<const C &>(*this).get()); } char c;}; The two casts and function call may be ugly, but it's correct in a non- const method as that implies the object was not const to begin with. (Meyers has a thorough discussion of this.)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/123758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ] }
123,773
I will choose Java as an example, most people know it, though every other OO language was working as well. Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation. However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation. Now there was this article, saying it's better to inherit interfaces than implementations , you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the fragile base class problem . So far this makes all a lot of sense and many other things said in the article make a lot of sense to me. What bugs me about this, is that implementation inheritance means code reuse , one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then? E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class. How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world? Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here. Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like public void move() { abstractCarObject.move();} ? Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?
Short answer: Yes it is possible. But you have to do it on purpose and no by chance ( using final, abstract and design with inheritance in mind, etc. ) Long answer: Well, inheritance is not actually for "code re-use", it is for class "specialization", I think this is a misinterpretation. For instance is it a very bad idea to create a Stack from a Vector, just because they are alike. Or properties from HashTable just because they store values. See [Effective]. The "code reuse" was more a "business view" of the OO characteristics, meaning that you objects were easily distributable among nodes; and were portable and didn't not have the problems of previous programming languages generation. This has been proved half rigth. We now have libraries that can be easily distributed; for instance in java the jar files can be used in any project saving thousands of hours of development. OO still has some problems with portability and things like that, that is the reason now WebServices are so popular ( as before it was CORBA ) but that's another thread. This is one aspect of "code reuse". The other is effectively, the one that has to do with programming. But in this case is not just to "save" lines of code and creating fragile monsters, but designing with inheritance in mind. This is the item 17 in the book previously mentioned; Item 17: Design and document for inheritance or else prohibit it. See [Effective] Of course you may have a Car class and tons of subclasses. And yes, the approach you mention about Car interface, AbstractCar and CarImplementation is a correct way to go. You define the "contract" the Car should adhere and say these are the methods I would expect to have when talking about cars. The abstract car that has the base functionality that every car but leaving and documenting the methods the subclasses are responsible to handle. In java you do this by marking the method as abstract. When you proceed this way, there is not a problem with the "fragile" class ( or at least the designer is conscious or the threat ) and the subclasses do complete only those parts the designer allow them. Inheritance is more to "specialize" the classes, in the same fashion a Truck is an specialized version of Car, and MosterTruck an specialized version of Truck. It does not make sanse to create a "ComputerMouse" subclase from a Car just because it has a Wheel ( scroll wheel ) like a car, it moves, and has a wheel below just to save lines of code. It belongs to a different domain, and it will be used for other purposes. The way to prevent "implementation" inheritance is in the programming language since the beginning, you should use the final keyword on the class declaration and this way you are prohibiting subclasses. Subclassing is not evil if it's done on purpose. If it's done uncarefully it may become a nightmare. I would say that you should start as private and "final" as possible and if needed make things more public and extend-able. This is also widely explained in the presentation"How to design good API's and why it matters" See [Good API] Keep reading articles and with time and practice ( and a lot of patience ) this thing will come clearer. Although sometime you just need to do the work and copy/paste some code :P . This is ok, as long you try to do it well first. Here are the references both from Joshua Bloch ( formerly working in Sun at the core of java now working for Google ) [Effective]Effective Java. Definitely the best java book a non beginner should learn, understand and practice. A must have. Effective Java [Good API]Presentation that talks on API's design, reusability and related topics.It is a little lengthy but it worth every minute. How To Design A Good API and Why it Matters Regards. Update: Take a look at minute 42 of the video link I sent you. It talks about this topic: "When you have two classes in a public API and you think to make one a subclass of another, like Foo is a subclass of Bar, ask your self , is Every Foo a Bar?... " And in the minute previous it talks about "code reuse" while talking about TimeTask.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15809/" ] }
123,781
Is there a way to tell SQL Server 2008 Express to log every query (including each and every SELECT Query!) into a file? It's a Development machine, so the negative side effects of logging Select-Queries are not an issue. Before someone suggests using the SQL Profiler: This is not available in Express (does anyone know if it's available in the Web Edition?) and i'm looking for a way to log queries even when I am away.
SQL Server Profiler: File → New Trace The "General" Tab is displayed. Here you can choose "Save to file:" so its logged to a file. View the "Event Selection" Tab Select the items you want to log. TSQL → SQL:BatchStarting will get you sql selects Stored Procedures → RPC:Completed will get you Stored Procedures. More information from Microsoft: SQL Server 2008 Books Online - Using SQL Server Profiler Update - SQL Express Edition: A comment was made that MS SQL Server Profiler is not available for the express edition. There does appear to be a free alternative: Profiler for Microsoft SQL Server 2005 Express Edition
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/123781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
123,792
I have built an application in C# that I would like to be optimized for multiple cores. I have some threads, should I do more? Updated for more detail C# 2.0 Run on Windows Vista and Windows Server 2003 Updated again This code is running as a service I do not want to have the complete code... my goal here is to get your experience and how to start. Like I say, I have already use threads. What more can I do?
I'd generalize that writing a highly optimized multi-threaded process is a lot harder than just throwing some threads in the mix. I recommend starting with the following steps: Split up your workloads into discrete parallel executable units Measure and characterize workload types - Network intensive, I/O intensive, CPU intensive etc - these become the basis for your worker pooling strategies. e.g. you can have pretty large pools of workers for network intensive applications, but it doesn't make sense having more workers than hardware-threads for CPU intensive tasks. Think about queuing/array or ThreadWorkerPool to manage pools of threads. Former more finegrain controlled than latter. Learn to prefer async I/O patterns over sync patterns if you can - frees more CPU time to perform other tasks. Work to eliminate or atleast reduce serialization around contended resources such as disk. Minimize I/O, acquire and hold minimum level of locks for minimum period possible. (Reader/Writer locks are your friend) 5.Comb through that code to ensure that resources are locked in consistent sequence to minimize deadly embrace. Test like crazy - race conditions and bugs in multithreaded applications are hellish to troubleshoot - often you only see the forensic aftermath of the massacre. Bear in mind that it is entirely possible that a multi-threaded version could perform worse than a single-threaded version of the same app. There is no excuse for good engineering measurement.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/123792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14441/" ] }
123,803
I am using Visual Studio 2005 with Team Foundation Server. When I right click a file under the source control and choose "compare" VS appears to freeze until I hit escape. My guess is that the window that is supposed to be popping up is somewhere I can't get to. I tried minimizing all the windows that I can and it is nowhere to be found.
Try the keyboard shortcut to get to the window's main menu () then hit 'M' for move and hit an arrow key to attach the window to the mouse - then at the next move of the mouse it should jump to it. Experiment with a window you can see first.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21367/" ] }
123,838
Our clients will be uploading images to be printed on their documents and we have been asked to come up with a way to get the resolution of the image in order to warn them if the image has too low of a resolution and will look pixalated in the end-product If it comes to it we could also go with the dimensions if anyone knows how to get those but the resolution would be preferred Thank you
System.Drawing.Image Image newImage = Image.FromFile("SampImag.jpg");newImage.HorizontalResolution
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ] }
123,886
What are the best places to find out everything there is to know about Domain-Driven Design, from beginner to advanced. Books Websites Mailing lists User groups Conferences etc
Here are some interesting sources: the DDD book by Eric Evans the free DDD Quickly book the DDD newsgroup
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8739/" ] }
123,900
I've seen a few sites that list related searches when you perform a search, namely they suggest other search queries you may be interested in. I'm wondering the best way to model this in a medium-sized site (not enough traffic to rely on visitor stats to infer relationships). My initial thought is to store the top 10 results for each unique query, then when a new search is performed to find all the historical searches that match some amount of the top 10 results but ideally not matching all of them (matching all of them might suggest an equivalent search and hence not that useful as a suggestion). I imagine that some people have done this functionality before and may be able to provide some ideas of different ways to do this. I'm not necessarily looking for one winning idea since the solution will no doubt vary substantially depending on the size and nature of the site.
Here are some interesting sources: the DDD book by Eric Evans the free DDD Quickly book the DDD newsgroup
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15687/" ] }
123,927
I'm writing a setup program to install an application to a USB drive. The application is meant to be used only from USB drives, so it would save an extra step for the user by automatically selecting USB drive to install to. I might explore using Nullsoft or MSI for install, but since I'm mostly familiar with .NET I initially plan to try either custom .NET installer or setup component on .NET. Is it possible to determine the drive letter of a USB flash drive on Windows using .NET? How?
You could use: from driveInfo in DriveInfo.GetDrives()where driveInfo.DriveType == DriveType.Removable && driveInfo.IsReadyselect driveInfo.RootDirectory.FullName
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124/" ] }
123,936
Some of my colleagues use special comments on their bug fixes, for example: // 2008-09-23 John Doe - bug 12345// <short description> Does this make sense? Do you comment bug fixes in a special way? Please let me know.
I don't put in comments like that, the source control system already maintains that history and I am already able to log the history of a file. I do put in comments that describe why something non-obvious is being done though. So if the bug fix makes the code less predictable and clear, then I explain why.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/123936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ] }
123,945
I have a Excel macro that generates a this error whenever it gets input of a specific format. Does anyone knows in general what an advise flag is OR where can I find information on this type of error? Thanks Runtime error -2147221503 (80040001): Automation error, Invalid advise flags
I don't put in comments like that, the source control system already maintains that history and I am already able to log the history of a file. I do put in comments that describe why something non-obvious is being done though. So if the bug fix makes the code less predictable and clear, then I explain why.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/123945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ] }
123,958
In python is it possible to get or set a logical directory (as opposed to an absolute one). For example if I have: /real/path/to/dir and I have /linked/path/to/dir linked to the same directory. using os.getcwd and os.chdir will always use the absolute path >>> import os>>> os.chdir('/linked/path/to/dir')>>> print os.getcwd()/real/path/to/dir The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.
The underlying operational system / shell reports real paths to python. So, there really is no way around it, since os.getcwd() is a wrapped call to C Library getcwd() function. There are some workarounds in the spirit of the one that you already know which is launching pwd . Another one would involve using os.environ['PWD'] . If that environmnent variable is set you can make some getcwd function that respects it. The solution below combines both: import osfrom subprocess import Popen, PIPEclass CwdKeeper(object): def __init__(self): self._cwd = os.environ.get("PWD") if self._cwd is None: # no environment. fall back to calling pwd on shell self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip() self._os_getcwd = os.getcwd self._os_chdir = os.chdir def chdir(self, path): if not self._cwd: return self._os_chdir(path) p = os.path.normpath(os.path.join(self._cwd, path)) result = self._os_chdir(p) self._cwd = p os.environ["PWD"] = p return result def getcwd(self): if not self._cwd: return self._os_getcwd() return self._cwdcwd = CwdKeeper()print cwd.getcwd()# use only cwd.chdir and cwd.getcwd from now on. # monkeypatch os if you want:os.chdir = cwd.chdiros.getcwd = cwd.getcwd# now you can use os.chdir and os.getcwd as normal.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3051/" ] }
123,986
I need my program to work only with certain USB Flash drives (from a single manufacturer) and ignore all other USB Flash drives (from any other manufacturers). is it possible to check that specific USB card is inserted on windows using .NET 2.0? how? if I find it through WMI, can I somehow determine which drive letter the USB drive is on?
EDIT: Added code to print drive letter. Check if this example works for you. It uses WMI. Console.WriteLine("Manufacturer: {0}", queryObj["Manufacturer"]);...Console.WriteLine(" Name: {0}", c["Name"]); // here it will print drive letter The full code sample: namespace WMISample{ using System; using System.Management; public class MyWMIQuery { public static void Main() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive"); foreach (ManagementObject queryObj in searcher.Get()) { Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]); Console.WriteLine("PNPDeviceID: {0}", queryObj["PNPDeviceID"]); Console.WriteLine("Manufacturer: {0}", queryObj["Manufacturer"]); Console.WriteLine("Model: {0}", queryObj["Model"]); foreach (ManagementObject b in queryObj.GetRelated("Win32_DiskPartition")) { Console.WriteLine(" Name: {0}", b["Name"]); foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk")) { Console.WriteLine(" Name: {0}", c["Name"]); // here it will print drive letter } } // ... Console.WriteLine("--------------------------------------------"); } } catch (ManagementException e) { Console.WriteLine(e.StackTrace); } Console.ReadLine(); } }} I think those properties should help you distinguish genuine USB drives from the others. Test with several pen drives to check if the values are the same. See full reference for Win32_DiskDrive properties here: http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx Check if this article is also of any help to you: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/48a9758c-d4db-4144-bad1-e87f2e9fc979
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124/" ] }
123,994
I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle this server side? Example: http://localhost:3399/Base64.aspx?VLTrap=VkxUcmFwIHNldCB0byAiRkRTQT8+PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg== Produces: VkxUcmFwIHNldCB0byAiRkRTQT8 PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg== People have suggested URLEncoding the querystring: System.Web.HttpUtility.UrlEncode(yourString) I can't do that as I have no control over the calling routine (which is working fine with other languages). There was also the suggestion of replacing spaces with a plus sign: Request.QueryString["VLTrap"].Replace(" ", "+"); I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what other characters might be malformed in addition to the plus sign. My main goal is to intercept the QueryString before it is run through the decoder. To this end I tried looking at Request.QueryString.toString() but this contained the same malformed information. Is there any way to look at the raw QueryString before it is URLDecoded? After further testing it appears that .Net expects everything coming in from the QuerString to be URL encoded but the browser does not automatically URL encode GET requests.
You could manually replace the value ( argument.Replace(' ', '+') ) or consult the HttpRequest.ServerVariables["QUERY_STRING"] (even better the HttpRequest.Url.Query) and parse it yourself. You should however try to solve the problem where the URL is given; a plus sign needs to get encoded as "%2B" in the URL because a plus otherwise represents a space. If you don't control the inbound URLs, the first option would be preferred as you avoid the most errors this way.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/123994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7819/" ] }
123,999
Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport )? (The question refers to Firefox.)
Now most browsers support getBoundingClientRect method, which has become the best practice. Using an old answer is very slow, not accurate and has several bugs . The solution selected as correct is almost never precise . This solution was tested on Internet Explorer 7 (and later), iOS 5 (and later) Safari, Android 2.0 (Eclair) and later, BlackBerry, Opera Mobile, and Internet Explorer Mobile 9 . function isElementInViewport (el) { // Special bonus for those using jQuery if (typeof jQuery === "function" && el instanceof jQuery) { el = el[0]; } var rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */ rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ );} How to use: You can be sure that the function given above returns correct answer at the moment of time when it is called, but what about tracking element's visibility as an event? Place the following code at the bottom of your <body> tag: function onVisibilityChange(el, callback) { var old_visible; return function () { var visible = isElementInViewport(el); if (visible != old_visible) { old_visible = visible; if (typeof callback == 'function') { callback(); } } }}var handler = onVisibilityChange(el, function() { /* Your code go here */});// jQuery$(window).on('DOMContentLoaded load resize scroll', handler);/* // Non-jQueryif (window.addEventListener) { addEventListener('DOMContentLoaded', handler, false); addEventListener('load', handler, false); addEventListener('scroll', handler, false); addEventListener('resize', handler, false);} else if (window.attachEvent) { attachEvent('onDOMContentLoaded', handler); // Internet Explorer 9+ :( attachEvent('onload', handler); attachEvent('onscroll', handler); attachEvent('onresize', handler);}*/ If you do any DOM modifications, they can change your element's visibility of course. Guidelines and common pitfalls: Maybe you need to track page zoom / mobile device pinch? jQuery should handle zoom/pinch cross browser, otherwise first or second link should help you. If you modify DOM , it can affect the element's visibility. You should take control over that and call handler() manually. Unfortunately, we don't have any cross browser onrepaint event. On the other hand that allows us to make optimizations and perform re-check only on DOM modifications that can change an element's visibility. Never Ever use it inside jQuery $(document).ready() only, because there is no warranty CSS has been applied in this moment. Your code can work locally with your CSS on a hard drive, but once put on a remote server it will fail. After DOMContentLoaded is fired, styles are applied , but the images are not loaded yet . So, we should add window.onload event listener. We can't catch zoom/pinch event yet. The last resort could be the following code: /* TODO: this looks like a very bad code */setInterval(handler, 600); You can use the awesome feature pageVisibiliy of the HTML5 API if you care if the tab with your web page is active and visible. TODO: this method does not handle two situations: Overlapping using z-index . Using overflow-scroll in element's container. Try something new - The Intersection Observer API explained .
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/123999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21290/" ] }
124,031
Using MS SQL Server Management Studio 2005 - To Restore a Database: Restore Database (*) From Device: Click " ... " Button Backup media: File Click " Add " Button Popup Window: " Locate Backup File " That window Defaults to C:\Program Files\Microsoft SQL Server\MSSQL.1\Backup How do I configure MS SQL Server Management Studio to look in D:\data\databases\ instead of looking in C:\Program Files\Microsoft SQL Server\MSSQL.1\Backup ?
In the registry, edit the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer\BackupDirectory value to point to d:\data\databases
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/124031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12923/" ] }
124,040
Possible Duplicate: Choosing between MEF and MAF (System.AddIn) Is the Managed Extensibility Framework a replacement for System.Addin? Or are they complementary?
It is touched in the MSDN Forums here: Comparison to the AddIn libraries? And also by Krzysztof Cwalina in his blog on the release of MEF: Managed Extensibility Framework Summary : they live side by side.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/124040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3289/" ] }
124,067
In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# System.Text.StringBuilder and Java java.lang.StringBuilder . Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available?
No, there is no type of stringbuilder class in PHP, since strings are mutable. That being said, there are different ways of building a string, depending on what you're doing. echo, for example, will accept comma-separated tokens for output. // This...echo 'one', 'two';// Is the same as thisecho 'one';echo 'two'; What this means is that you can output a complex string without actually using concatenation, which would be slower // This...echo 'one', 'two';// Is faster than this...echo 'one' . 'two'; If you need to capture this output in a variable, you can do that with the output buffering functions . Also, PHP's array performance is really good. If you want to do something like a comma-separated list of values, just use implode() $values = array( 'one', 'two', 'three' );$valueList = implode( ', ', $values ); Lastly, make sure you familiarize yourself with PHP's string type and it's different delimiters, and the implications of each.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/124067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21388/" ] }
124,143
I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions. What is the main reason of the difference between Java and C# in throwing exceptions? In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.
In the article The Trouble with Checked Exceptions and in Anders Hejlsberg's (designer of the C# language) own voice, there are three main reasons for C# not supporting checked exceptions as they are found and verified in Java: Neutral on Checked Exceptions “C# is basically silent on the checkedexceptions issue. Once a bettersolution is known—and trust me wecontinue to think about it—we can goback and actually put something inplace.” Versioning with Checked Exceptions “Adding a new exception to a throwsclause in a new version breaks clientcode. It's like adding a method to aninterface. After you publish aninterface, it is for all practicalpurposes immutable, …” “It is funny how people think that theimportant thing about exceptions ishandling them. That is not theimportant thing about exceptions. In awell-written application there's aratio of ten to one, in my opinion, oftry finally to try catch. Or in C#, using statements, which arelike try finally.” Scalability of Checked Exceptions “In the small, checked exceptions arevery enticing…The troublebegins when you start building bigsystems where you're talking to fouror five different subsystems. Eachsubsystem throws four to tenexceptions. Now, each time you walk upthe ladder of aggregation, you havethis exponential hierarchy below youof exceptions you have to deal with.You end up having to declare 40exceptions that you might throw.…It just balloons out of control.” In his article, “ Why doesn't C# have exception specifications? ”, Anson Horton (Visual C# Program Manager) also lists the following reasons (see the article for details on each point): Versioning Productivity and code quality Impracticality of having class author differentiate between checked and unchecked exceptions Difficulty of determining the correct exceptions for interfaces. It is interesting to note that C# does, nonetheless, support documentation of exceptions thrown by a given method via the <exception> tag and the compiler even takes the trouble to verify that the referenced exception type does indeed exist. There is, however, no check made at the call sites or usage of the method. You may also want to look into the Exception Hunter , which is a commerical tool by Red Gate Software , that uses static analysis to determine and report exceptions thrown by a method and which may potentially go uncaught: Exception Hunter is a new analysistool that finds and reports the set ofpossible exceptions your functionsmight throw – before you even ship.With it, you can locate unhandledexceptions easily and quickly, down tothe line of code that is throwing theexceptions. Once you have the results,you can decide which exceptions needto be handled (with some exceptionhandling code) before you release yourapplication into the wild. Finally, Bruce Eckel , author of Thinking in Java , has an article called, “ Does Java need Checked Exceptions? ”, that may be worth reading up as well because the question of why checked exceptions are not there in C# usually takes root in comparisons to Java.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/124143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68336/" ] }
124,148
Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue: int i = 4;...if (i == 10) doStuff(); Later on you figure that you want the variable i to be either defined or undefined, so you change the above instantiation to: Integer i = null; Now the equality check fails. Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?
Using the boxed types does have both performance and memory issues. When doing comparisons (eg (i == 10) ), java has to unbox the type before doing the comparison. Even using i.equals(TEN) uses a method call, which is costlier and (IMO) uglier than the == syntax. Re memory, the object has to be stored on the heap (which also takes a hit on performance) as well as storing the value itself. A sneaky gotcha? i.equals(j) when i is null . I always use the primitives, except when it may be null , but always check for null before comparison in those cases.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/124148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ] }