Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
On our web application, the search results are displayed in sortable tables. The user can click on any column and sort the result. The problem is some times, the user does a broad search and gets a lot of data returned. To make the sortable part work, you probably need all the results, which takes a long time. Or I can... | Using sorting paging at the database level is the correct answer. If your query returns 1000 rows, but you're only going to show the user 10 of them, there is no need for the other 990 to be sent across the network.
Here is a mysql example. Say you need 10 rows, 21-30, from the 'people' table:
```
SELECT * FROM peopl... | You should be doing paging back on the database server. E.g. on SQL 2005 and SQL 2008 there are paging techniques. I'd suggest looking at paging options for whatever system you're looking at. | Best approach for sortable table with a lot of data | [
"",
"javascript",
"database",
"jquery-ui-sortable",
""
] |
In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this? | In SQL 2005, You can use the following:
```
select convert(varchar(8), dateadd(second, [SecondsColumn], 0), 108)
```
Which first converts the seconds into a date after 1900-01-01, and then gets the hh:mm:ss part.
If the column is more than 24 hours, this will roll over, if you want days and then hours in that c... | Every database does it differently. I use PostgreSQL and it does it like so:
```
select to_char(my_date - my_other_date, 'HH:MM:SS');
```
You'll have to consult the manual for the database you are using. | How to convert in SQL the number of seconds into a human-readable duration? | [
"",
"sql",
"int",
"duration",
""
] |
Is there a good method for writing C / C++ function headers with default parameters that are function calls?
I have some header with the function:
```
int foo(int x, int y = 0);
```
I am working in a large code base where many functions call this function and depend on this default value. This default value now need... | Go figure! It does work. [Default arguments in C++ functions](http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr237.htm) | I would use two overloaded functions:
`int foo(int x, int y);`
`int foo(int x){return foo(x,bar);}`
If you allow the forwarding function to be inlined, then the performance penalty is likely to small to zero. If you keep the body of it out of line in a non-header file there may be a performance cost (likely to be sm... | Can the result of a function call be used as a default parameter value? | [
"",
"c++",
"parameters",
"default-value",
""
] |
How do I generate a range of consecutive numbers (one per line) from a MySQL query so that I can insert them into a table?
For example:
```
nr
1
2
3
4
5
```
I would like to use only MySQL for this (not PHP or other languages). | If you need the records in a table and you want to avoid concurrency issues, here's how to do it.
First you create a table in which to store your records
```
CREATE TABLE `incr` (
`Id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`Id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
```
Secondly create a stored procedu... | Here is one way to do it set-based without loops. This can also be made into a view for re-use. The example shows the generation of a sequence from 0 through 999, but of course, it may be modified to suit.
```
INSERT INTO
myTable
(
nr
)
SELECT
SEQ.SeqValue
FROM
(
SELECT
(HUNDREDS.SeqValue + TEN... | Generating a range of numbers in MySQL | [
"",
"sql",
"mysql",
""
] |
Is SQL case sensitive? I've used [MySQL](https://en.wikipedia.org/wiki/MySQL) and [SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server) which both seem to be case insensitive. Is this always the case? Does the standard define case-sensitivity? | The SQL keywords are case insensitive (`SELECT`, `FROM`, `WHERE`, etc), but they are often written in all caps. However, in some setups, table and column names are case sensitive.
MySQL has a configuration option to enable/disable it. Usually case sensitive table and column names are the default on Linux [MySQL](https... | This isn't strictly SQL language, but in SQL Server if your database collation is case-sensitive, then all table names are case-sensitive. | Is SQL syntax case sensitive? | [
"",
"sql",
"case-sensitive",
""
] |
What would you consider best practice for organizing JUnit tests in a project, and why? For example, do you keep your tests next to the classes they test? Do you put them in a separate but parallel package structure? Do you use a different organization strategy entirely? | I use a separate but parallel package structure for several reasons.
1. It keeps tests organized the same way as the application code.- I can easily build just the application files for distribution.- Test code still has access to my application code.- It's not as cluttered as having test code mixed with application c... | I put my tests in a seperate but similar/parallel package structure. This is how Maven likes things and it works well with IDEs too. I like it this way because I don't have my test code mixed up with my application code, yet I can still access package-private things for the purpose of mocking and state-verification. | Organization of JUnit tests in projects | [
"",
"java",
"junit",
""
] |
Why do I get compiler errors with this Java code?
```
1 public List<? extends Foo> getFoos()
2 {
3 List<? extends Foo> foos = new ArrayList<? extends Foo>();
4 foos.add(new SubFoo());
5 return foos;
6 }
```
Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.
Errors I get with... | Use this instead:
```
1 public List<? extends Foo> getFoos()
2 {
3 List<Foo> foos = new ArrayList<Foo>(); /* Or List<SubFoo> */
4 foos.add(new SubFoo());
5 return foos;
6 }
```
Once you declare foos as `List<? extends Foo>`, the compiler doesn't know that it's safe to add a SubFoo. What if an `ArrayList<A... | Just thought I'd add to this old thread, by summarising the properties of List parameters instantiated with types or wildcards....
When a method has a parameter/result which is a List, the use of type instantiation or wildcards determines
1. Types of List which can be passed to the method as an argument
2. Types of L... | How can elements be added to a wildcard generic collection? | [
"",
"java",
"generics",
""
] |
I've got a relatively large .Net system that consists of a number of different applications. Rather than having lots of different app.config files, I would like to share a single configuration file between all the apps.
I would also like to have one version when developing on my machine, one version for someone else d... | For large amounts of configuration which is needed by multiple applications, I would put this configuration into a central repository, e.g. a database, file in a common location.
To use different versions of a configuration file for different environments, create a build configuration for each of the different environ... | You could use a Post-build event (Properties -> Build Events) on your "child" projects to copy a config file from a master project to others, like this:
```
copy /Y c:\path\to\master\project\app.config $(TargetPath).config
exit 0
```
(The "exit 0" as the last line prevents a build error).
To have separate config fil... | How can I share application configuration in a .net application? | [
"",
"c#",
".net",
"app-config",
""
] |
I'm building a form with php/mysql. I've got a table with a list of locations and sublocations. Each sublocation has a parent location. A column "parentid" references another locationid in the same table. I now want to load these values into a dropdown in the following manner:
```
--Location 1
----Sublocation 1
----Su... | NOTE: This is only psuedo-code.. I didn't try running it, though you should be able to adjust the concepts to what you need.
```
$parentsql = "SELECT parentid, parentname FROM table";
$result = mysql_query($parentsql);
print "<select>";
while($row = mysql_fetch_assoc($result)){
$childsql = "SELECT childID, chi... | Are you looking for something like the [OPTGROUP](http://www.w3schools.com/TAGS/tag_optgroup.asp) tag? | Nested dropdown | [
"",
"php",
"mysql",
"html",
"forms",
""
] |
Java has some very good open source static analysis tools such as [FindBugs](http://findbugs.sf.net/), [Checkstyle](http://checkstyle.sf.net/) and [PMD](http://pmd.sf.net/). Those tools are easy to use, very helpful, runs on multiple operating systems and *free*.
Commercial C++ static analysis products are available. ... | Oink is a tool built on top of the Elsa C++ front-end. Mozilla's Pork is a fork of Elsa/Oink.
See: <http://danielwilkerson.com/oink/index.html> | [CppCheck](http://sourceforge.net/p/cppcheck/wiki/Home/) is open source and cross-platform.
Mac OSX:
```
brew install cppcheck
``` | What open source C++ static analysis tools are available? | [
"",
"c++",
"static-analysis",
""
] |
From the MSDN article on STAThread:
> Indicates that the COM threading model for an application is single-threaded apartment (STA).
(For reference, that's [the entire article](http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx).)
Single-threaded apartment... OK, that went over my head. Also, I re... | Apartment threading is a COM concept; if you're not using COM, and none of the APIs you call use COM "under the covers", then you don't need to worry about apartments.
If you do need to be aware of apartments, then the details can get [a little complicated](http://msdn.microsoft.com/en-us/library/ms693344(VS.85).aspx)... | What that does it it ensures that `CoInitialize` is called specifying COINIT\_APARTMENTTHREADED as the parameter. If you do not use any COM components or ActiveX controls it will have no effect on you at all. If you do then it's kind of crucial.
Controls that are apartment threaded are effectively single threaded, cal... | STAThread and multithreading | [
"",
"c#",
".net",
"multithreading",
"sta",
""
] |
### What are some methods of utilising Eclipse for Dependency Management? | I really like the [The Maven Integration for Eclipse (m2eclipse, Eclipse m2e)](http://maven.apache.org/eclipse-plugin.html). I use it purely for the dependency management feature. It's great not having to go out and download a bunch of new jars new each time I set up a project. | A simpler way to go is the [Maven Eclipse plugin](http://maven.apache.org/plugins/maven-eclipse-plugin/) (as opposed to a Maven plugin for Eclipse). It's simply a maven plugin that generates the .project and .classpath file based on the contents of the pom, you just run `mvn eclipse:eclipse` and you're done. It uses a ... | Eclipse: Dependency Management | [
"",
"java",
"eclipse",
"maven-2",
"eclipse-plugin",
"dependencies",
""
] |
In Windows, is there an easy way to tell if a folder has a subfile that has changed?
I verified, and the last modified date on the folder does not get updated when a subfile changes.
Is there a registry entry I can set that will modify this behavior?
If it matters, I am using an NTFS volume.
I would ultimately like... | This [article](http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx) should help. Basically, you create one or more notification object such as:
```
HANDLE dwChangeHandles[2];
dwChangeHandles[0] = FindFirstChangeNotification(
lpDir, // directory to watch
FALSE, ... | This is perhaps overkill, but the [IFS kit](http://www.microsoft.com/whdc/devtools/ifskit/default.mspx) from MS or the [FDDK](http://www.osr.com/toolkits_fddk.shtml) from OSR might be an alternative. Create your own filesystem filter driver with simple monitoring of all changes to the filesystem. | How to see if a subfile of a directory has changed | [
"",
"c++",
"windows",
"filesystems",
"ntfs",
""
] |
In our application, we are using RMI for client-server communication in very different ways:
1. Pushing data from the server to the client to be displayed.
2. Sending control information from the client to the server.
3. Callbacks from those control messages code paths that reach back from the server to the client (si... | You can do this with a custom RMI Socket Factory.
The socket factories create the sockets for RMI to use at both the client and server end so if you write your own you've got full control over the ports used. The client factories are created on the server, Serialized and then sent down to the client which is pretty ne... | You don't need socket factories for this, or even multiple ports. If you're starting the Registry from your server JVM you can use port 1099 for everything, and indeed that is what will happen by default. If you're not starting the registry at all, as in a client callback object, you can provide port 1099 when exportin... | How do I ensure that RMI uses only a specific set of ports? | [
"",
"java",
"rmi",
""
] |
I've worked on many projects where I've been given code by others to update. More often than not I compile it and get about 1,000+ compiler warnings. When I see compiler warnings they make me feel dirty, so my first task is to clean up the code and remove them all. Typically I find about a dozen problems like uninitial... | I would clean up any warning.
Even the ones that you know are harmless (if such a thing exists) will give a bad impression of you to whoever will compile the code.
It one of the "smelly" signs I would look for if I had to work on someone else code.
If not real errors or potential future issues, it would be a sign of ... | Clean 'em up, even if they don't indicate a real problem. Otherwise, if a warning that **does** indicate a real problem shows up, you won't see it through all the noise. | C / C++ compiler warnings: do you clean up all your code to remove them or leave them in? | [
"",
"c++",
"c",
"compiler-construction",
"warnings",
""
] |
I have two collections which have property `Email` in both collections. I need to get a list of the items in the first list where `Email` does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?
So far I have a join, like...
```
var matches = f... | I don't know if this will help you but..
```
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
foreach (var c in q... | You want the Except operator.
```
var answer = list1.Except(list2);
```
Better explanation here: <https://learn.microsoft.com/archive/blogs/charlie/linq-farm-more-on-set-operators>
**NOTE:** This technique works best for primitive types only, since you have to implement an [IEqualityComparer](https://learn.microsoft... | How would you do a "not in" query with LINQ? | [
"",
"c#",
"linq",
""
] |
Coming from a C# background the naming convention for variables and methods are usually either camelCase or PascalCase:
```
// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()
```
In Python, I have seen the above but I have also seen snake\_case being used:
```
# python example
this_is_my_variab... | See Python [PEP 8: Function and Variable Names](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names):
> Function names should be [lowercase, with words separated by underscores](https://en.wikipedia.org/wiki/Snake_case) as necessary to improve readability.
>
> Variable names follow the same conventio... | The [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html#316-naming) has the following convention:
> `module_name`, `package_name`, `ClassName`, `method_name`, `ExceptionName`, `function_name`, `GLOBAL_CONSTANT_NAME`, `global_var_name`, `instance_var_name`, `function_parameter_name`, `local_var... | What is the naming convention in Python for variables and functions? | [
"",
"python",
"naming-conventions",
"camelcasing",
"pascalcasing",
"snakecasing",
""
] |
I intend to develop a system that is entirely based on modules. The system base should have support for finding out about plugins, starting them up and being able to provide ways for those modules to communicate. Ideally, one should be able to put in new modules and yank out unused modules at will, and modules should b... | You should definitely look at [OSGi](http://www2.osgi.org/Specifications/HomePage). It aims at being *the* component/plugin mechanism for Java. It allows you to modularize your code (in so-called bundles) and update bundles at runtime. You can also completely hide implementation packages from unwanted access by other b... | Another option is the [ServiceLoader](http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html) added in Java 1.6. | How should I start when developing a system based on modules or plugins? | [
"",
"java",
"events",
"plugins",
"module",
""
] |
How can I send an email from C++? Is there a good cross-platform (MS Windows, Linux etc) library that I can use? I'm using GCC (cygwin on MS Windows). | Check out jwSMTP - a cross-platform SMTP class.
<http://johnwiggins.net/jwsmtp/> | Check out [C-Client](http://www.washington.edu/imap/)
* Apache license
* Very established library ( makers of Pine email reader, UW-IMAP Server, etc. )
* Supports IMAP, POP, SMTP, and NNTP
* Unix and Windows | How to send Email through a C++ program? | [
"",
"c++",
"email",
"gcc",
""
] |
In a C++ file, I have code like this:
```
#if ACTIVATE
# pragma message( "Activated" )
#else
# pragma message( "Not Activated")
#endif
```
I want to set this ACTIVE define to 1 with the MSBuild command line.
It tried this, but it doesn't work:
```
msbuild /p:DefineConstants="ACTIVATE=1"
```
How can I do it? | The answer to ponder is: ***you cannot*** | Our solution was to use an environment variable with `/D` defines in it, combined with the *Additional Options* box in Visual Studio.
1. In Visual Studio, add an environment variable macro, `$(ExternalCompilerOptions)`, to the Additional Options under project options → *C/C++* → *Command Line* (remember both *Debug* a... | MSBuild: set a specific preprocessor #define in the command line | [
"",
"c++",
"visual-studio",
"msbuild",
""
] |
I use `public boolean mouseDown(Event ev, int x, int y)` to detect a click of the mouse.
I can distinguish between the right mouse button (ev.metaDown() is true) and the left and middle.
How can i differentiate the left from the middle button?
Or if it is impossible with mouseDown, what should i use? | Try using [ALT\_MASK](http://java.sun.com/javase/6/docs/api/java/awt/Event.html#ALT_MASK):
> This flag indicates that the Alt key was down when the event occurred. For mouse events, this flag indicates that the middle mouse button was pressed or released.
So your code might be:
```
if (ev.modifiers & Event.ALT_MASK ... | [mouseDown](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#mouseDown%28java.awt.Event,%20int,%20int%29) is deprecated. All you need is accessible by the MouseEvent.[getButton](http://java.sun.com/javase/6/docs/api/java/awt/event/MouseEvent.html#getButton()). Track BUTTON3. | How to fetch the middle mouse button in java? | [
"",
"java",
"events",
"mouse",
""
] |
I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use ([details](http://issues.apache.org/bugzilla/show_bug.cgi?id=42411)).
I am therefore looking to include a small servlet in the web... | I ended up rolling my own `StaticServlet`. It supports `If-Modified-Since`, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either.
The code is available: [StaticServlet.java](http://bruno.defraine.net/StaticServlet.java). ... | I came up with a slightly different solution. It's a bit hack-ish, but here is the mapping:
```
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servle... | Servlet for serving static content | [
"",
"java",
"jsp",
"servlets",
"jakarta-ee",
""
] |
Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:
```
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
```
For those who have used PHP, here's what I'm trying to do in C#:
```
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr... | You can do this way -
```
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
```
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
```
List<int> termsList = new List<int>();
for (int runs ... | Using [Linq](https://learn.microsoft.com/en-us/dotnet/api/system.linq)'s method [Concat](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.concat) makes this simple
```
int[] array = new int[] { 3, 4 };
array = array.Concat(new int[] { 2 }).ToArray();
```
result
3,4,2 | Adding values to a C# array | [
"",
"c#",
"arrays",
""
] |
What is an example of a fast SQL to get duplicates in datasets with hundreds of thousands of records. I typically use something like:
```
SELECT afield1, afield2 FROM afile a
WHERE 1 < (SELECT count(afield1) FROM afile b WHERE a.afield1 = b.afield1);
```
But this is quite slow. | This is the more direct way:
```
select afield1,count(afield1) from atable
group by afield1 having count(afield1) > 1
``` | You could try:
```
select afield1, afield2 from afile a
where afield1 in
( select afield1
from afile
group by afield1
having count(*) > 1
);
``` | Fastest "Get Duplicates" SQL script | [
"",
"sql",
"scripting",
"duplicates",
"performance",
""
] |
I'm trying to do the following without too much special case code to deal with invalidated POSITIONs etc:
What's the best way to fill in the blanks?
```
void DeleteUnreferencedRecords(CAtlMap<Record>& records)
{
for(____;____;____)
{
if( NotReferencedElsewhere(record) )
{
// Delete record
... | According to this:
<http://msdn.microsoft.com/en-us/library/0h4c3zkw(VS.80).aspx>
RemoveAtPos has these semantics
> Removes the key/value pair stored at the specified position. The memory used to store the element is freed. The POSITION referenced by pos becomes invalid, and while the POSITION of any other elements ... | I'm not too familiar with `CAtlMap`, but if it's similar to the STL's `map` type, then [Rob's "first thought"](https://stackoverflow.com/questions/197121/how-do-i-write-a-for-loop-that-iterates-over-a-catlmap-selectively-deleting-ele#197209) is safe -- deleting an item does not affect any iterators except the one(s) po... | How do I write a for loop that iterates over a CAtlMap selectively deleting elements as it goes? | [
"",
"c++",
"atl",
""
] |
How do I make my application always use English when displaying win32/.net exceptions messages?
I got this message, it looks like someone used babelfish to translate it (it's Swedish):
"System.ComponentModel.Win32Exception: Programmet kunde inte starta eftersom programmets sida-vid-sidakonfiguration är felaktig."
Ext... | You can try setting `Thread.CurrentThread.CurrentUICulture` and/or `.CurrentCulture` to `CultureInfo("en-US")`. | If it's an ASP.NET application, you can set the UI language in web.config (\*):
```
<system.web>
<globalization ... uiCulture="en-US" ... />
</system.web>
```
For other applications, the current user's regional settings are used by default, and you have to explicitly override it - e.g. Thread.CurrentUICulture = n... | Prevent exception messages from being translated into the user's language? | [
"",
"c#",
".net",
"exception",
"globalization",
""
] |
I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header.
```
<rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/>
<rich:dataTable id="instanceList" rows="10" value="... | I ended up doing it manually. I adding a support tag to the header text tag, like so.
```
<h:outputText value="#{column}">
<a4j:support event="onclick" action="#{pageDataModel.sort(idx)}"
eventsQueue="instancesQueue"
reRender="instanceList,instanceListScroller"/>
</h:outputText>
```
To... | There is a fairly elegant solution to this solution here:
<http://livedemo.exadel.com/richfaces-demo/richfaces/sortingFeature.jsf?tab=ex-usage>
This demo avoids using the tag. | Server-side DataTable Sorting in RichFaces | [
"",
"java",
"ajax",
"jsf",
"richfaces",
""
] |
I'm building small web site in Java (Spring MVC with JSP views) and am trying to find best solution for making and including few reusable modules (like "latest news" "upcoming events"...).
So the question is: Portlets, tiles or some other technology? | If you are using Spring MVC, then I would recommend using Portlets. In Spring, portlets are just lightweight controllers since they are only responsible for a fragment of the whole page, and are very easy to write. If you are using Spring 2.5, then you can enjoy all the benefits of the new annotation support, and they ... | Tiles can be a pain. Vast improvement over what came before (i.e. nothing), but rather limiting.
[Wicket](http://wicket.apache.org/) might be more what you're looking for, unless you've settled on JSP. | What's the best way to make a modular java web application | [
"",
"java",
"spring-mvc",
"module",
""
] |
I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints.
What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't h... | <http://wiki.wxpython.org/CreatingStandaloneExecutables>
It shouldn't be that large unless you have managed to include the debug build of wx.
I seem to rememebr about 4Mb for the python.dll and similair for wx. | This may help:
[How can I make an EXE file from a Python program?](https://stackoverflow.com/questions/49146/what-is-the-best-way-to-make-an-exe-file-from-a-python-program) | Python GUI Application redistribution | [
"",
"python",
"user-interface",
"wxpython",
"distribution",
"freeze",
""
] |
I have a website which uses the custom 404 error handling in PHP/Apache to display specific pages.
e.g. <http://metachat.org/recent>
I've a feeling this is a bad way of doing this, but it's code I inherited...
Although the page displays correctly on most browsers, I'm getting a situation where AVG Anti-Virus is hij... | There's no way other than using URL rewriting (mod\_rewrite) or creating the missing pages. What's happening is that the client requests a page which doesn't exist. Apache is configured to serve a special page upon 404 errors, but it still sends the 404 status code, then AVG traps that.
So, you could do something like... | If what you get is a *Page Not Found* error, **don't** make it send Status 200 OK. Please.
It's one of most annoying "tricks" people do for whatever reason. If the page user requests does not exist, tell this to him, as well as to his browser. And to search engines, that otherwise will crawl/cache your custom error-pa... | PHP - Custom error handling. Redirected 404 is being hijacked by AVG Anti-Virus. How to stop? | [
"",
"php",
"http-headers",
"http-status-code-404",
"antivirus",
""
] |
I'm learning DirectX as part of a hobby project. I've been looking for some good online resources for DirectX9 (using C++, if that distinction matters), but haven't found anything that's a) great for a beginner and b) up to date.
Any recommendations? | When I started using DirectX I found this to be the best resource around for basic stuff:
<http://www.directxtutorial.com/>
When you start reaching an intermediate level they want you to pay a subscription but all the good basic stuff is free. Tutorials are clear and literally step-by-step.
This is website is not bad... | * [Toymaker](http://www.toymaker.info/Games/index.html)
* [Triple Buffer](http://triplebuffer.devmaster.net/list.php?display=s&page=0)
* [DirectX4VB](http://directx4vb.vbgamer.com/DirectX4VB/TUT_DX9Start.asp)
* [32Bits](http://www.32bits.co.uk/)
[Introduction to 3D Game Programming with DirectX 9](https://rads.stackov... | What are some good DirectX resources for a beginner? | [
"",
"c++",
"resources",
"directx",
""
] |
What is the difference between `bool` and `Boolean` types in C#? | `bool` is an alias for `System.Boolean` just as `int` is an alias for `System.Int32`. See a full list of aliases here: [Built-In Types Table (C# Reference)](https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx). | I don't believe there is one.
`bool` is just an alias for `System.Boolean` | What is the difference between bool and Boolean types in C# | [
"",
"c#",
"types",
"boolean",
""
] |
I personally use [`var_dump`](http://php.net/var_dump), but lots of people like [`print_r`](http://php.net/print_r).
What does everyone use? Pros and Cons?
Does someone have a special home brew function of their own? | I always use the Xdebug extended var\_dump. It gives out a lot of verbose output.
See: <http://xdebug.org/docs/display> for more details. | I use `print_r()` because I like the pretty array structure... but `var_dump` does give you a bit more information (like types)
```
$obj = (object) array(1, 2, 3);
// output of var_dump:
object(stdClass)#1 (3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
// output of print_r
stdClass Object
(
[0] => 1
... | Which php variable debugging function do you use? var_dump, print_r, var_export, other? | [
"",
"php",
"debugging",
""
] |
I have this Python application that gets stuck from time to time and I can't find out where.
Is there any way to signal Python interpreter to show you the exact code that's running?
Some kind of on-the-fly stacktrace?
***Related questions:***
* [Print current call stack from a method in Python code](https://stackov... | I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals):
```
import code, traceback, signal
def debug(sig, frame):
"""Interrupt running process, and pr... | The suggestion to install a signal handler is a good one, and I use it a lot. For example, [bzr](http://bazaar-vcs.org/) by default installs a SIGQUIT handler that invokes `pdb.set_trace()` to immediately drop you into a [pdb](http://docs.python.org/lib/module-pdb.html) prompt. (See the [bzrlib.breakin](https://bazaar.... | Showing the stack trace from a running Python application | [
"",
"python",
"debugging",
"stack-trace",
"traceback",
""
] |
Basically, I have a class with 2 methods: one to serialize an object into an XML file and another to read an object from XML.
Here is an example of synchronized part from the method that restores an object:
```
public T restore(String from) throws Exception {
// variables declaration
synchronized (fro... | 1.
Yes, it's OK to synchronize on a String, however you'd need to synchronize on the string.[intern()](http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()) in order to always get the same Object
```
StringBuffer sb = new StringBuffer(); sb.append("a").append("b");
String a = new String(sb.toString());... | Given that the some parts of your code are missing, my bet is that the problem lies with synchronizing on a string. You cannot freely assume that strings are pooled (which would break your synchronization scheme).
The best approach would be to add a map that will associate a key (string) with its actual synchronizatio... | synchronizing io operation in java on a string method argument? | [
"",
"java",
"multithreading",
"synchronization",
"io",
""
] |
I'm currently using default implementation of STL for VS2005 and I'm [not really satisfied](https://stackoverflow.com/questions/186494/ifstr1str2-versus-ifstr1lengthstr2length-str1str2) with it. Perhaps there is something better? | The Dinkumware STL implementation (supplied with VS2005) is actually quite good. The STL is a general purpose library and so it is almost always possible to write something better for very specific use cases.
I'm aware of the following alternative implementations, but I've never used them with VS2005:
SGI Standard Te... | How about STLPort?
<http://www.stlport.org/> | What is the best implementation of STL for VS2005? | [
"",
"c++",
"visual-studio-2005",
"stl",
""
] |
In my webapplication (C#, .Net 3.5), made up of a *core* class library (containing the business logic, data layer and a couple of utility classes), a windows service project, a webservice project and the website project, I have a couple of static classes in the *core* library used by all other projects. These classes (... | I would try to avoid static classes for things which will require initialization. Make your Log class a normal class, and perhaps have a separate factory class to create instances or a single instance. You might want to use dependency injection to avoid having any statics, although this could get painful for something ... | I would suggest, if the initialisation is expensive, to use a Singleton (if you're not familiar with design patterns, google Singleton Design pattern). As part of the construction of the instance, you then read in a config file, which can be specific to the environment.
This way you would get the best of both worlds. | Initializing static objects - Code design question | [
"",
"c#",
"design-patterns",
"architecture",
"static",
""
] |
Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding. | That's very nice, however in order to simulate some time passing we need to run a command that takes some time and that's very clear in second example.
However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing l... | Use the System.Threading.Timer class.
System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.
There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer clas... | How do you add a timer to a C# console application | [
"",
"c#",
"console",
"timer",
""
] |
Consider the class below that represents a Broker:
```
public class Broker
{
public string Name = string.Empty;
public int Weight = 0;
public Broker(string n, int w)
{
this.Name = n;
this.Weight = w;
}
}
```
I'd like to randomly select a Broker from an array, taking into account t... | Your algorithm is nearly correct. However, the test should be `<` instead of `<=`:
```
if (randomNumber < broker.Weight)
```
This is because 0 is inclusive in the random number while `totalWeight` is exclusive. In other words, a broker with weight 0 would still have a small chance of being selected – not at all what ... | How about something a little more generic, that can be used for any data type?
```
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public static class IEnumerableExtensions {
public static T RandomElementByWeight<T>(this IEnumerable<T> sequence, Func<T, float> wei... | Random weighted choice | [
"",
"c#",
"algorithm",
"random",
""
] |
In PHP5, is the \_\_destruct() method guaranteed to be called for each object instance? Can exceptions in the program prevent this from happening? | The destructor will be called when the all references are freed, or when the script terminates. I assume this means when the script terminates properly. I would say that critical exceptions would not guarantee the destructor to be called.
The [PHP documentation](https://www.php.net/__construct) is a little bit thin, b... | It's also worth mentioning that, in the case of a subclass that has its own destructor, the parent destructor is **not** called automatically.
You have to explicitly call **parent::\_\_destruct()** from the subclass **\_\_destruct()** method if the parent class does any required cleanup. | Can I trust PHP __destruct() method to be called? | [
"",
"php",
"garbage-collection",
""
] |
I need a short code snippet to get a directory listing from an HTTP server.
Thanks | A few important considerations before the code:
1. The HTTP Server has to be configured to allow directories listing for the directories you want;
2. Because directory listings are normal HTML pages there is no standard that defines the format of a directory listing;
3. Due to consideration **2** you are in the land w... | **Basic understanding:**
Directory listings are just HTML pages generated by a web server.
Each web server generates these HTML pages in its own way because there is no standard way for a web server to list these directories.
The best way to get a directory listing, is to simply do an HTTP request to the URL you'd li... | C# HttpWebRequest command to get directory listing | [
"",
"c#",
"http",
""
] |
I have some hierarchical data - each entry has an id and a (nullable) parent entry id.
I want to retrieve all entries in the tree under a given entry. This is in a SQL Server 2005 database. I am querying it with LINQ to SQL in C# 3.5.
LINQ to SQL does not support [Common Table Expressions](http://msdn.microsoft.com/en... | I would set up a view and an associated table-based function based on the CTE. My reasoning for this is that, while you could implement the logic on the application side, this would involve sending the intermediate data over the wire for computation in the application. Using the DBML designer, the view translates into ... | This [option](http://www.scip.be/index.php?Page=ArticlesNET18) might also prove useful:
**LINQ AsHierarchy() extension method**
<http://www.scip.be/index.php?Page=ArticlesNET18> | Hierarchical data in Linq - options and performance | [
"",
"sql",
"linq",
"sql-server-2005",
"c#-3.0",
"common-table-expression",
""
] |
Well... simple question, right? But with no so simple answers.
In firefox i use firebug console (profile) but... what to do in other browsers? Like Internet Explorer / Opera / Safari (on windows) | You may use JavaScript optimizers
* <http://js-optimizer.sourceforge.net/>
* <http://www.xtreeme.com/javascript-optimizer/> | This particular problem solves itself over time. ;-)
Version 8 of the Internet Explorer (currently in beta 2) ships with a built-in JavaScript profiler. The next Safari version will probably also include one since its rendering engine, WebKit, now has one as part of its [Web Inspector](http://webkit.org/blog/148/web-i... | How do you optimise your Javascript? | [
"",
"javascript",
"performance",
""
] |
One of my co-workers claims that even though the execution path is cached, there is no way parameterized SQL generated from an ORM is as quick as a stored procedure. Any help with this stubborn developer? | I would start by reading this article:
<http://decipherinfosys.wordpress.com/2007/03/27/using-stored-procedures-vs-dynamic-sql-generated-by-orm/>
Here is a speed test between the two:
<http://www.blackwasp.co.uk/SpeedTestSqlSproc.aspx> | Round 1 - You can start a profiler trace and compare the execution times. | Why is parameterized SQL generated by NHibernate just as fast as a stored procedure? | [
"",
"sql",
"stored-procedures",
"orm",
""
] |
Is there an easy way of programmatically checking if a serial COM port is already open/being used?
Normally I would use:
```
try
{
// open port
}
catch (Exception ex)
{
// handle the exception
}
```
However, I would like to programatically check so I can attempt to use another COM port or some such. | I needed something similar some time ago, to search for a device.
I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working.
```
var portNames = SerialPort.GetPortNames();
foreach(var port in portNames)... | This is how I did it:
```
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
```
t... | C# check if a COM (Serial) port is already open | [
"",
"c#",
".net",
"serial-port",
""
] |
I've been working on porting some of my Processing code over to regular Java in NetBeans. So far so well, most everything works great, except for when I go to use non-grayscale colors.
I have a script that draws a spiral pattern, and should vary the colors in the spiral based on a modulus check. The script seems to ha... | Have you considered adding debugging statements (System.out.println) and looking at the Java Console?
There may be a massive amount of output and definitive slowdown, but you can at least see what happens when nothing seems to happen.
What I do think is a logic error is the filling if statement; every iteratation you... | Not sure if you have still an issue. You mention hanging. It is a shot in the dark, but I remember fry repeating that size() call must be the first instruction in setup(). So perhaps moving down the background() call might help. Couldn't hurt anyway. | Varying Colors in Processing | [
"",
"java",
"colors",
"processing",
"spiral",
""
] |
Is there any way to use C# to build a container application where each tab is actually its own process like with Google chrome? | You can use the [SetParent](http://pinvoke.net/default.aspx/user32/SetParent.html) Win32 call to do this, but it's really fraught with problems. I had enough troubles getting it all to work nicely using windows from different AppDomains - there'd be even more difficulties with whole extra processes.
Basically there's ... | For those of you interested in the actual implementation of multi-process apps, I wrote an article about it on my website: **[Multi-process C# app like Google Chrome](http://wyday.com/blog/2010/multi-process-c-sharp-application-like-google-chrome-using-named-pipes/)**.
I've included working C# code. It's been tested t... | Windows Forms application like Google Chrome with multiple processes | [
"",
"c#",
"winforms",
"process",
""
] |
I am building an application as a library, but to make sure I can get the output that I'd like, I switched it over to produce an exe. As soon as I did, I got several errors about unresolved external symbols.
At first I thought that I didn't have a path set to the 3rd party library that I was referencing, so I added th... | Building a library, the linker doesn't need to resolve imported symbols. That happens only when it starts linking object files and libraries together.
That's why you only started seeing the error when building an executable.
Indeed, in VC2008 (and 2005, if I remember well), use the project properties -> Linker -> Inp... | You also need to specify that you wish to link against that library in particular. The link paths merely tell the linker where the data you need to find is, not what to look for. You will also need to specify that you are linking against the library in question (xerces?).
Unfortunately, I don't know how to specify thi... | Unresolved External Symbol Errors switching from build library to exe or dll | [
"",
"c++",
"visual-studio-2005",
"linker",
""
] |
So, I understand *that* the following doesn't work, but *why* doesn't it work?
```
interface Adapter<E> {}
class Adaptulator<I> {
<E, A extends I & Adapter<E>> void add(Class<E> extl, Class<A> intl) {
addAdapterFactory(new AdapterFactory<E, A>(extl, intl));
}
}
```
The `add()` method gives me a compi... | I'm also not sure why the restriction is there. You could try sending a friendly e-mail to the designers of Java 5 Generics (chiefly Gilad Bracha and Neal Gafter).
My guess is that they wanted to support only an absolute minimum of [intersection types](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4... | Two possible reasons for outlawing this:
1. Complexity. [JDK-4899305](https://bugs.openjdk.java.net/browse/JDK-4899305) suggests that a bound containing a type parameter plus additional parameterized types would allow for even more complicated mutually recursive types than already exist. In short, [Bruno's answer](htt... | Why can't I use a type argument in a type parameter with multiple bounds? | [
"",
"java",
"generics",
"constraints",
""
] |
I have one text input and one button (see below). How can I use JavaScript to **trigger the button's click event** when the `Enter` key is pressed inside the text box?
There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I *only* want the `Enter` key to... | In jQuery, the following would work:
```
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode === 13) {
$("#id_of_button").click();
}
});
```
```
$("#pw").keyup(function(event) {
if (event.keyCode === 13) {
$("#myButton").click();
}
});
$("#myButton").click(function() {... | Then just code it in!
```
<input type = "text"
id = "txtSearch"
onkeydown = "if (event.keyCode == 13)
document.getElementById('btnSearch').click()"
/>
<input type = "button"
id = "btnSearch"
value = "Search"
onclick = "doSomething();"
/>
``` | Trigger a button click with JavaScript on the Enter key in a text box | [
"",
"javascript",
"button",
"onclick",
"onkeydown",
"onkeypress",
""
] |
I want to have a class which implements an interface, which specifies the specific subclass as a parameter.
```
public abstract Task implements TaskStatus<Task> {
TaskStatus<T> listener;
protected complete() {
// ugly, unsafe cast
callback.complete((T) this);
}
}
public interface TaskStatus<T> {
... | It is not clear what you are trying to do inside of `Task`. However, if you define the generic class `Task<T>` as follows:
```
class Task<T extends Task<T>> { ... }
```
The following two are possible:
```
class MyTask extends Task<MyTask> { ... }
class YourTask extends Task<MyTask> { ... }
```
But the following is ... | I suggest adding a getThis which should return this appropriately typed. Sure a subclas could misbehave, but that's always true. What you avoid is the cast and the possibility of a ClassCastException.
```
public abstract class Task<THIS extends Task<THIS>> {
private TaskStatus<THIS> callback;
public void setC... | Generic type args which specificy the extending class? | [
"",
"java",
"generics",
"design-patterns",
""
] |
If you want a cryptographically strong random numbers in Java, you use `SecureRandom`. Unfortunately, `SecureRandom` can be very slow. If it uses `/dev/random` on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty?
Has anyone used [Uncommon Maths](https://uncommons... | If you want true random data, then unfortunately you have to wait for it. This includes the seed for a `SecureRandom` PRNG. Uncommon Maths can't gather true random data any faster than `SecureRandom`, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlik... | You should be able to select the faster-but-slightly-less-secure /dev/urandom on Linux using:
```
-Djava.security.egd=file:/dev/urandom
```
However, this doesn't work with Java 5 and later ([Java Bug 6202721](https://bugs.openjdk.java.net/browse/JDK-6202721)). The suggested work-around is to use:
```
-Djava.security... | How to deal with a slow SecureRandom generator? | [
"",
"java",
"performance",
"security",
"random",
"entropy",
""
] |
Is it possible to connect PHP to a SQL Server Compact Edition database? What would be the best driver?
---
I need it for a desktop application where SQL Server Express is too heavy. | Short Answer : **No.**
Long Answer : To my knowledge, unlike PostgreSQL / MySQL / MS-SQL, there is no native driver to connect PHP to SQL Server Compact Edition.
If you want to connect to it, your best bet is to use PHP ODBC connections to talk to a ODBC Driver connected to the SQL Compact server. But its pretty much... | You could also consider SQLite:
<http://www.devshed.com/c/a/PHP/Introduction-to-Using-SQLite-with-PHP-5/> | Is it possible to connect PHP to SQL Server Compact Edition? | [
"",
"php",
"sql-server",
"sql-server-ce",
""
] |
Let's say I have a multithreaded C++ program that handles requests in the form of a function call to `handleRequest(string key)`. Each call to `handleRequest` occurs in a separate thread, and there are an arbitrarily large number of possible values for `key`.
I want the following behavior:
* Simultaneous calls to `ha... | You could do something similar to what you have in your question, but instead of a single global\_key\_map have several (probably in an array or vector) - which one is used is determined by some simple hash function on the string.
That way instead of a single global lock, you spread that out over several independent o... | **Raise granularity and lock entire key-ranges**
This is a variation on Mike B's answer, where instead of having several fluid lock maps you have a single fixed array of locks that apply to key-ranges instead of single keys.
Simplified example: create array of 256 locks at startup, then use first byte of key to deter... | How do I use an arbitrary string as a lock in C++? | [
"",
"c++",
"multithreading",
"concurrency",
"locking",
""
] |
what is the best way to put a container class or a some other class inside a class as private or a public member?
Requirements:
1.Vector< someclass> inside my class
2.Add and count of vector is needed interface | If the container's state is part of the class's invariant, then it should, if possible, be private.
For example, if the container represents a three dimensional vector then part of the invariant might be that it always contains exactly 3 numbers. Exposing it as a public member would allow code external to the class to... | Whether a member is declared Private or Public depends entirely on your application. Could you give some more detail?
One important point to remember when declaring your member is that if you provide a "getter" to retrieve it, then you are no longer encapsulating that object. Instead, it can be good to write wrapper m... | Class design with vector as a private/public member? | [
"",
"c++",
"class-design",
"encapsulation",
""
] |
I have a link that I dynamically create which looks something like the following:
```
<a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a>
```
with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there... | Convert quote charaters to their HTML equivalents, `"` etc. before you insert them into the HTML. There's a [long list](http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references) of HTML/XML character codes on wikipedia.
There may well be a function to do this for you, depending on how you're ... | You could just replace the ' with \' | Passing in a text to a javascript function that may have a single quote | [
"",
"javascript",
""
] |
I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.
Edit: My current solution, as suggested, is to use an anonymous Comparator... | I think your solution is the only sensible way. The only way to get the list of files is to use [File.listFiles()](http://java.sun.com/javase/6/docs/api/java/io/File.html#listFiles()) and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a [Compara... | **Elegant solution since Java 8:**
```
File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified));
```
---
**Or, if you want it in descending order, just reverse it:**
```
File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified... | Best way to list files in Java, sorted by Date Modified? | [
"",
"java",
"file",
"sorting",
""
] |
When using JDBC, I often come across constructs like
```
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
// Some other actions
}
```
I asked myself (and authors of code too) why not to use labels for retrieving column values:
```
int id = rs.getInt("CUSTOMER_ID");
```
The best e... | You should use **string labels by default.**
**Pros:**
* Independence of column order
* Better readability/maintainability
**Cons:**
* You have no control over the column names (access via stored procedures)
**Which would you prefer?**
ints?
```
int i = 1;
customerId = resultSet.getInt(i++);
customerName = r... | Warning: I'm going to get bombastic here, because this drives me crazy.
99%\* of the time, it's a ridiculous micro-optimization that people have some vague idea makes things 'better'. This completely ignores the fact that, unless you're in an extremely tight and busy loop over millions of SQL results *all the time*, w... | ResultSet: Retrieving column values by index versus retrieving by label | [
"",
"java",
"optimization",
"jdbc",
"resultset",
""
] |
I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration:
```
<defaultProxy useDefaultCredentials="false">
<proxy... | Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.
Create an assembly called *SomeAssembly.dll* with this class :
```
namespace SomeNameSpace
{
public class MyProxy : IWebProxy
{
public ICredentials Credentia... | While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:
```
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="proxyAddress" usesystemdefault="True"... | Is it possible to specify proxy credentials in your web.config? | [
"",
"c#",
"web-services",
"proxy",
""
] |
I'm using `Console.WriteLine()` from a very simple WPF test application, but when I execute the application from the command line, I'm seeing nothing being written to the console. Does anyone know what might be going on here?
I can reproduce it by creating a WPF application in VS 2008, and simply adding `Console.Write... | You'll have to create a Console window manually before you actually call any Console.Write methods. That will init the Console to work properly without changing the project type (which for WPF application won't work).
Here's a complete source code example, of how a ConsoleManager class might look like, and how it can ... | You can use
```
Trace.WriteLine("text");
```
This will output to the "Output" window in Visual Studio (when debugging).
make sure to have the Diagnostics assembly included:
```
using System.Diagnostics;
``` | No output to console from a WPF application? | [
"",
"c#",
".net",
"wpf",
"console",
""
] |
How can I make my compilation optimized for Windows 64 bit? | A managed project is automatically built according to the architecture selected => default C# project created on AMD64 will be AMD64, X86 on X86. The native one is always 32-bit by default.
To explicitly set a platform:
1 open the solution explorer, select solution, right click->Configuration Manager.
2 go to 'Activ... | You might also want to do a check at runtime, just to be sure:
```
using System;
using System.Runtime.InteropServices;
class SystemChecker
{
static bool Is64Bit
{
get { return Marshal.SizeOf(typeof(IntPtr)) == 8; }
}
}
``` | C# for 64bit OS? | [
"",
"c#",
".net",
"64-bit",
""
] |
Does BeautifulSoup work with Python 3?
If not, how soon will there be a port? Will there be a port at all?
Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?) | About two months after I asked this question, a port has been released:
<http://groups.google.com/group/beautifulsoup/browse_thread/thread/f24882cc17a0625e>
It'll bet BS working, but that's about it. Not yet tried it though. | Beautiful Soup **4.x** [officially supports Python 3.](https://groups.google.com/forum/#!msg/beautifulsoup/VpNNflJ1rPI/sum07jmEwvgJ)
```
pip install beautifulsoup4
``` | BeautifulSoup's Python 3 compatibility | [
"",
"python",
"python-3.x",
"beautifulsoup",
"porting",
""
] |
I have written something that uses the following includes:
```
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <commctrl.h>
```
This code works fine on 2 machines with the Platform SDK installed, but doesn't run (neither debug nor release versions) on clean ins... | Use Dependency Walker. Download and install from <http://www.dependencywalker.com/> (just unzip to install). Then load up your executable. The tool will highlight which DLL is missing. Then you can find the redistributable pack which you need to ship with your executable.
If you use VS2005, most cases will be covered ... | **Common controls is a red herring**. Your problem is that the Visual C++ 8.0 runtime - I assume you're using Visual Studio 2005 - isn't installed. Either statically link to the C/C++ runtime library, or distribute the runtime DLL.
You will have this problem with any C or C++ program that uses the DLL. You could get a... | Windows API commctrl.h using application doesn't work on machines without the Platform SDK | [
"",
"c++",
"windows",
"dll",
""
] |
Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:
```
>>> 6/3
2
>>> 6//3
2
``` | In Python 3.x, `5 / 2` will return `2.5` and `5 // 2` will return `2`. The former is floating point division, and the latter is ***floor division***, sometimes also called ***integer division***.
In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a `from __future__ import di... | ### Python 2.x Clarification:
To clarify for the Python 2.x line, `/` is neither floor division nor true division.
`/` is floor division when **both** args are `int`, but is true division when ***either*** of the args are `float`. | What is the difference between '/' and '//' when used for division? | [
"",
"python",
"math",
"syntax",
"operators",
"floor-division",
""
] |
How do I invoke a console application from my .NET application and capture all the output generated in the console?
(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.) | This can be quite easily achieved using the [ProcessStartInfo.RedirectStandardOutput](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx) property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the stand... | This is bit improvement over accepted answer from **@mdb**. Specifically, we also capture error output of the process. Additionally, we capture these outputs through events because `ReadToEnd()` doesn't work if you want to capture *both* error and regular output. It took me while to make this work because it actually a... | Capturing console output from a .NET application (C#) | [
"",
"c#",
".net",
"debugging",
"console",
""
] |
He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings `{'id': id, 'url': url}`. Some `id`s in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:
```
def unique_mapping(map):
d = {}
... | Your example can be rewritten slightly to construct the first dictionary using a generator expression and to remove necessity of construction of another mappings. Just reuse the old ones:
```
def unique_mapping(mappings):
return dict((m['id'], m) for m in mappings).values()
```
Although this came out as a one-lin... | There are a couple of things you could improve.
* You're performing two loops, one over the original dict, and then again over the result dict. You could build up your results in one step instead.
* You could change to use a generator, to avoid constructing the whole list up-front. (Use list(unique\_mapping(items)) to... | Extracting unique items from a list of mappings | [
"",
"python",
"unique",
"duplicate-data",
""
] |
How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | ```
import socket
socket.gethostbyname(socket.gethostname())
```
This won't work always (returns `127.0.0.1` on machines having the hostname in `/etc/hosts` as `127.0.0.1`), a paliative would be what gimel shows, use `socket.getfqdn()` instead. Of course your machine needs a resolvable hostname. | I just found this but it seems a bit hackish, however they say tried it on \*nix and I did on windows and it worked.
```
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()
```
This assumes you have an internet access, and that there is no ... | Finding local IP addresses using Python's stdlib | [
"",
"python",
"networking",
"ip-address",
""
] |
I am using sql server 2005. I just want to know is there something we can get the week number for the particular month. Example `Date = '2008-10-16'` Is there something we can have `SELECT WEEK(Date)`. Or any better suggestion. | ```
select (datepart(dd,'2008-10-08')-1) / 7 + 1
``` | ```
SELECT DATEPART( week, '2008-10-16')
``` | Week() function in sql script | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
1. What are the patterns you use to determine the frequent queries?
2. How do you select the optimization factors?
3. What are the types of changes one can make? | This is a nice question, if rather broad (and none the worse for that).
If I understand you, then you're asking how to attack the problem of optimisation starting from scratch.
The first question to ask is: "*is there a performance problem?*"
If there is no problem, then you're done. This is often the case. Nice.
... | Your question is a bit vague. Which DB platform?
If we are talking about SQL Server:
1. Use the Dynamic Management Views. Use SQL Profiler. Install the SP2 and the performance dashboard reports.
2. After determining the most costly queries (i.e. number of times run x cost one one query), examine their execution plans... | How do you optimize tables for specific queries? | [
"",
"sql",
"database-design",
""
] |
```
Pattern pattern = Pattern.compile("^[a-z]+$");
String string = "abc-def";
assertTrue( pattern.matcher(string).matches() ); // obviously fails
```
Is it possible to have the character class match a "-" ? | Don't put the minus sign between characters.
```
"[a-z-]"
``` | Escape the minus sign
```
[a-z\\-]
``` | In a java regex, how can I get a character class e.g. [a-z] to match a - minus sign? | [
"",
"java",
"regex",
""
] |
Here is an example of polymorphism from <http://www.cplusplus.com/doc/tutorial/polymorphism.html> (edited for readability):
```
// abstract base class
#include <iostream>
using namespace std;
class Polygon {
protected:
int width;
int height;
public:
void set_values(int a, int b) { widt... | Each object (that belongs to a class with at least one virtual function) has a pointer, called a `vptr`. It points to the `vtbl` of its actual class (which each class with virtual functions has at least one of; possibly more than one for some multiple-inheritance scenarios).
The `vtbl` contains a bunch of pointers, on... | [Chris Jester-Young](https://stackoverflow.com/questions/203126/how-does-the-c-compiler-know-which-implementation-of-a-virtual-function-to-call#203136) gives the basic answer to this question.
[Wikipedia](http://en.wikipedia.org/wiki/Virtual_table) has a more in depth treatment.
If you want to know the full details f... | How does the C++ compiler know which implementation of a virtual function to call? | [
"",
"c++",
"oop",
"polymorphism",
""
] |
I need to send email through an (external) SMTP server from Java however this server will only accept CRAM-MD5 authentication, which is not supported by JavaMail.
What would be a good way to get these emails to send? (It must be in Java.) | Here is [thread](http://lists.gnu.org/archive/html/classpathx-javamail/2010-10/msg00004.html) which says that you need to add the following property:
```
props.put("mail.smtp.auth.mechanisms", "CRAM-MD5")
```
Also in Geronimo implementation there is [CramMD5Authenticator](http://geronimo.apache.org/maven/javamail/1.7... | Since Java Mail 1.4.4, CRAM-MD5 is supported for use with smtp.
Just set this parameter to your properties and it will work:
`props.put("mail.smtp.sasl.enable", "true");` | SMTP with CRAM-MD5 in Java | [
"",
"java",
"smtp",
"sasl",
""
] |
I have a new app I'll be working on where I have to generate a Word document that contains tables, graphs, a table of contents and text. What's a good API to use for this? How sure are you that it supports graphs, ToCs, and tables? What are some hidden gotcha's in using them?
Some clarifications:
* I can't output a P... | In 2007 my project successfully used OpenOffice.org's [Universal Network Objects](https://www.openoffice.org/udk/common/man/uno.html) (UNO) interface to programmatically generate MS-Word compatible documents (\*.doc), as well as corresponding PDF documents, from a Java Web application (a Struts/JSP framework).
OpenOff... | I think [Apache POI](http://poi.apache.org/) can do the job. A possible problem depending on the usage your aiming to may be caused by the fact that HWPF is still in early development.
> [HWPF](http://poi.apache.org/hwpf/index.html)
> is the set of APIs for reading and
> writing Microsoft Word 97(-XP)
> documents usin... | Is there a Java API that can create rich Word documents? | [
"",
"java",
"ms-word",
"docx",
"doc",
""
] |
Is there a better way to debug JavaScript than MS Script Editor? I am searching for something like Firebug. Firebug Lite doesn't offer this functionality, though.
| Use Visual Studio 2008.
The Web Development Helper from Nikhilk is useful as is the Internet Explorer Developer Toolbar (<http://www.microsoft.com/en-us/download/details.aspx?id=18359>). They are not as good as FireBug though :-( | Though not strictly debuggers, these are useful tools for your arsenal
* <http://www.debugbar.com/>
* <http://projects.nikhilk.net/WebDevHelper/> | How to debug JavaScript in IE? | [
"",
"javascript",
"internet-explorer",
""
] |
I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the [docs](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx), 'd' sh... | See [here](http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx)
> d, %d
>
> The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns.
Otherwise d is interpreted as:
> d - 'Short... | From the MSDN documentation for "Custom Date and Time Format Strings":
> Any string that is not a standard date
> and time format string is interpreted
> as a custom date and time format
> string.
{0:d} is interpreted as a standard data and time format string. From "Standard Date and Time Format Strings", the "d" for... | Why do these two date formats differ? | [
"",
"c#",
".net",
"datetime",
"formatting",
""
] |
Say I have my sources in my src/ tree (and possibly in my test/ tree). Say I would like to compile only *part* of that tree. The reasons why I might want to do that are various. Just as an example, I might want to create the smallest possible jar (without including certain classes), or I might want the fastest compile ... | Why are you excluding as well as including? If you have at least one include, then files are only compiled if they're explicitly included. So this should work:
```
<javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"
includes="src/path/to/MyClass.java" />
```
Or more flexibly:
```
<java... | Old question, but I was struggling with the same problem and found a a more elegant solution. So here it is, for future reference:
According to the ant docs the `<javac>` element is an implicit `<fileset>` and as such can take [Selectors](https://ant.apache.org/manual/Types/selectors.html "Selectors") like `<filename ... | compiling only part of the source tree with ant | [
"",
"java",
"ant",
"jar",
"javac",
""
] |
I'm trying to access the Facebook API Admin.getMetrics method via jQuery. I'm correctly composing the request url on the server side (in order to keep my app secret secret). I'm then sending the url over to the browser to be request using `jQuery.getJSON()`.
Facebook requires that I send a copy of all of my request pa... | The use of `jQuery.getScript` turned out to be close to -- but not quite -- the answer. Using getScript eliminates jQuery's need to add the dynamically named anonymous function to the request params (though it will still do that if you go ahead and pass it an anonymous function as in the above code). However, the defau... | The only thing that did the work for me were the following settings
`jQuery.ajax({
url: fbookUrl,
dataType: "jsonp",
type: "GET",
cache: true,
jsonp: false,
jsonpCallback: "MyFunctionName" //insert here your function name
});` | using a named function as the callback for $.getJSON in jQuery to satisfy Facebook request signing demands | [
"",
"javascript",
"jquery",
"json",
"facebook",
"jsonp",
""
] |
I have a bit of code where I am looping through all the select boxes on a page and binding a `.hover` event to them to do a bit of twiddling with their width on `mouse on/off`.
This happens on page ready and works just fine.
The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won'... | **As of jQuery 1.7** you should use [`jQuery.fn.on`](https://api.jquery.com/on/#on-events-selector-data-handler) with the selector parameter filled:
```
$(staticAncestors).on(eventName, dynamicChild, function() {});
```
*Explanation:*
This is called event delegation and works as followed. The event is attached to a ... | There is a good explanation in the documentation of [`jQuery.fn.on`](http://api.jquery.com/on/).
In short:
> Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to `.on()`.
Thus in the following example `#dataTable tbody tr` must exist be... | Event binding on dynamically created elements? | [
"",
"javascript",
"jquery",
"events",
"unobtrusive-javascript",
""
] |
I tried but I guess Message Box only works with win forms. What is the best alternative to use in web forms? | You can use `confirm` for yes/no questions and `alert` for "OK" messages in JavaScript.
The other alternative is to use JavaScript to pop up a new window that looks and acts like a message box. Modality in this case varied by browser. In Internet Explorer, the method
```
window.showModalDialog(url,name,params)
```
w... | ```
result = confirm('Yes or no question here.')
``` | Is it possible to get Message Box in web forms? | [
"",
"javascript",
"user-interface",
"dialog",
""
] |
I've ran some "ALTER" scripts on the database [SQL Server Server 2005], and overwrote some sprocs. Is there any way to undo changes and get my old sprocs back?
Is there a way to get the scripts that were executed out of the .LDf file? That way i can re-run my initial "create" script for my sprocs.
I don't have a back... | FIRST: DO NOT TAKE ANY BACKUPS JUST YET.
There are several tools on the market to do this sort of thing.
You might try this one:
[ApexSQL Log](http://www.apexsql.com/sql_tools_log.asp) | In case anybody else has the same problem - Were you doing transaction log backups every X minutes? If so, you can use Quest LiteSpeed's log reader or Quest Toad for SQL Server's log reader to read the log file backups. It gives undo/redo scripts too for any transaction in the log backups or the ldf. | Undo changes to SQL Server 2005 database | [
"",
"sql",
"sql-server",
"sql-server-2005",
"recovery",
""
] |
How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net? | There are two possible solutions.
1. Call the Win32 function GetDiskFreeSpaceEx. Here is a sample program:
```
internal static class Win32
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesFo... | Use WMI
```
using System.Management;
// Get all the network drives (drivetype=4)
SelectQuery query = new SelectQuery("select Name, VolumeName, FreeSpace from win32_logicaldisk where drivetype=4");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject drive in searcher.Get(... | How can I determine if a remote drive has enough space to write a file using C#? | [
"",
"c#",
".net",
"networking",
"filesystems",
""
] |
Here's a common code pattern I have to work with:
```
class foo {
public:
void InitMap();
void InvokeMethodsInMap();
static void abcMethod();
static void defMethod();
private:
typedef std::map<const char*, pMethod> TMyMap;
TMyMap m_MyMap;
}
void
foo::InitMap()
{
m_MyMap["abc"] = &foo::abcM... | Don't use `const char*` as the key for maps. That means the map is ordered by the addresses of the strings, not the contents of the strings. Use a `std::string` as the key type, instead.
`std::map` is not a hash table, it's usually implemented as a red-black tree, and elements are guaranteed to be ordered by some crit... | The definition of map is:
**map<Key, Data, Compare, Alloc>**
Where the last two template parameters default too:
Compare: less<Key>
Alloc: allocator<value\_type>
When inserting new values into a map. The new value (valueToInsert) is compared against the old values in order (**N.B.** This is not sequentia... | std::map iteration - order differences between Debug and Release builds | [
"",
"c++",
"stl",
""
] |
I noticed a good while back that Wikipedia links to a [Javascript implementation](http://pajhome.org.uk/crypt/md5/) of different hash functions. Also found [Clipperz Crypto](http://www.clipperz.com/open_source/javascript_crypto_library). Even Mozilla implements a [crypto object](http://developer.mozilla.org/en/JavaScri... | There are uses for hashing functions in Javascript, for example validating captchas client side (by comparing hash in session to computed hash from input). Obviously, the uses are limited since it runs almost exclusively client side (and you can't trust client input), but the potential is there. | You can encrypt data using JavaScript; however I'm not sure about the benefits. Because if you are using, let's say bas64, you need to send the encryption key to the client, and if someone can intercept the encrypted information he/ she would probably be able to intercept the encryption key too.
You should never use t... | Is Javascript a proper platform for cryptography? Or, can it be? | [
"",
"javascript",
"security",
"language-agnostic",
"cryptography",
""
] |
Is there any way to clean up this type of loop using LINQ?
```
List<Car> result;
List<string> makes;
List<string> models;
for (int i = 0; i < makes.Count() && i < models.Count(); i++)
{
result.Add(new Car() { Make = makes[i], Model = models[i] });
}
```
Basically I'm looking for some way to collate m... | You could use `Enumerable.Range`, like so:
```
List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count))
.Select(i => new Car { Make = makes[i], Model = models[i] }).ToList();
```
If `makes` and `models` always contain the same number of items, you can use more compact syntax:
```
List<Car> res... | It sounds like you really need a new LINQ operator - one which wasn't included in LINQ, somewhat accidentally: Zip. It would basically take two enumerables and return a single enumerable which paired entries, until one or other of the original sequences finished.
I don't have anything like that up my sleeve, but it sh... | How do I LINQify this? | [
"",
"c#",
".net",
"linq",
""
] |
Our base Masterpage has something like the following
```
<head runat="server">
<title></title>
<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/actions.js")%>"></script>
<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/jquery/jquery-1.2.6.min.js")%>"></... | Use the ScriptManager server control:
```
<asp:ScriptManager ID="myScriptManager" runat="server">
<Scripts>
<asp:ScriptReference Path = "~/javascript/actions.js" />
<asp:ScriptReference Path = "~/javascript/jquery/jquery-1.2.6.min.js" />
</Scripts>
</asp:ScriptManager>
``` | Have you tried:
```
<script type="text/javascript" src='<%= Page.ResolveClientUrl("~/javascript/actions.js") %>'></script>
``` | Preferred way to include relative reference to JavaScript in VS 2008 nested Masterpage | [
"",
"asp.net",
"javascript",
"master-pages",
"relative-path",
"nested",
""
] |
Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too. | [PHP Code Beautifier](http://www.waterproof.fr/products/phpCodeBeautifier/) is a useful free tool that should do what you're after, although their [download page](http://www.waterproof.fr/products/phpCodeBeautifier/download.php) does require an account to be created.
> The tool has been declined into 3 versions:
>
> *... | Well here is my very basic and rough script:
```
#!/usr/bin/php
<?php
class Token {
public $type;
public $contents;
public function __construct($rawToken) {
if (is_array($rawToken)) {
$this->type = $rawToken[0];
$this->contents = $rawToken[1];
} else {
$... | Php code formatter / beautifier and php beautification in general | [
"",
"php",
"editor",
""
] |
Does the using catch the exception or throw it? i.e.
```
using (StreamReader rdr = File.OpenText("file.txt"))
{
//do stuff
}
```
If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it? | using statements do not eat exceptions.
All "Using" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block.
There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called. | When you see a using statement, think of this code:
```
StreadReader rdr = null;
try
{
rdr = File.OpenText("file.txt");
//do stuff
}
finally
{
if (rdr != null)
rdr.Dispose();
}
```
So the real answer is that it doesn't do anything with the exception thrown in the body of the using block. It doesn'... | C# "Using" Syntax | [
"",
"c#",
"exception",
"using",
"using-statement",
""
] |
What is the best way to keep a console application open as long as the CancelKeyPress event has not been fired?
I would prefer to not use Console.Read or Console.ReadLine as I do not want to accept input. I just want to enable the underlying application to print to the console event details as they are fired. Then onc... | I'm assuming that "gracefully shut down the application" is the part you are struggling with here. Otherwise your application will automatically exit on ctrl-c. You should change the title.
Here's a quick demo of what I think you need. It could be refined a bit more with use of locking and Monitors for notification. I... | The `_s_stop` boolean should be declared volatile in the example code, or an overly-ambitious optimizer might cause the program to loop infinitely. | How can I keep a console open until CancelKeyPress event is fired? | [
"",
"c#",
".net",
"console",
""
] |
I'm writing code that looks similar to this:
```
public IEnumerable<T> Unfold<T>(this T seed)
{
while (true)
{
yield return [next (T)object in custom sequence];
}
}
```
Obviously, this method is never going to return. (The C# compiler silently allows this, while R# gives me the warning *"Function ... | So long as you document very clearly that the method will never finish iterating (the method itself returns very quickly, of course) then I think it's fine. Indeed, it can make some algorithms much neater. I don't believe there are any significant memory/perf implications - although if you refer to an "expensive" objec... | > "Generally speaking, is it bad desing
> to provide an enumerator that returns
> an infinite amount of items, without
> supplying a way to stop enumerating?"
The consumer of the code, can **always** stop enumerating (using break for example or other means). If your enumerator returns and infinite sequence, that doesn... | How do you design an enumerator that returns (theoretically) an infinite amount of items? | [
"",
"c#",
"enumerator",
""
] |
I'm looking for a good audio compression library for .NET. Anything using MP3 is out (because of the licensing issue). Basically I just need to be able to compress regular WAV audio data into some format, and decompress back to WAV. Preferably the code would be all .NET (C# or VB.NET), but I don't think this is likely.... | Have you thought about using WMA? If you use managed C++ or C++/CLI it's very easy to write a managed wrapper around the Windows Media Format SDK. This assembly can then be easily used by a higher level VB.Net or C# assembly. As long as you have WMP installed it even has the advantage of not requiring any additional de... | You've thought about the **.OGG** format yet? I don't know if a .net library is available, but the libogg and libvorbis C libs aren't rocket-science and well tested. For a simple compress/decompress job you may get away with a two function wrapper that handles all the details.
It should be easy to write a .net wrapper... | What's the best audio compression library for .NET? | [
"",
"c#",
".net",
"vb.net",
"audio",
"compression",
""
] |
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi?
Which combination will need more memory and CPU time?
Which one is faster?
Which is known for being more stable than the other?
I am also thinking to use CherryPy's WSGI server but I hear it's not very suit... | For nginx/mod\_wsgi, ensure you read:
<http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html>
Because of how nginx is an event driven system underneath, it has behavioural characteristics which are detrimental to blocking applications such as is the case with WSGI based applications. Worse case... | The author of nginx mod\_wsgi explains some differences to Apache mod\_wsgi [in this mailing list message](http://osdir.com/ml/web.nginx.english/2008-05/msg00451.html). | In production, Apache + mod_wsgi or Nginx + mod_wsgi? | [
"",
"python",
"apache",
"nginx",
"mod-wsgi",
""
] |
The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?
The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd b... | I don't endorse this solution in any way, shape or form. But if you add a variable to the `__builtin__` module, it will be accessible as if a global from any other module that includes `__builtin__` -- which is all of them, by default.
a.py contains
```
print foo
```
b.py contains
```
import __builtin__
__builtin__... | If you need a global cross-module variable maybe just simple global module-level variable will suffice.
a.py:
```
var = 1
```
b.py:
```
import a
print a.var
import c
print a.var
```
c.py:
```
import a
a.var = 2
```
Test:
```
$ python b.py
# -> 1 2
```
Real-world example: [Django's global\_settings.py](https://... | How to make a cross-module variable? | [
"",
"python",
"module",
"global",
""
] |
Is there a way to deploy a given war file on Tomcat server? I want to do this without using the web interface. | Just copy the war file into the $TOMCAT\_HOME/webapps/ directory. Tomcat will deploy the war file by automatically exploding it. FYI - If you want you can make updates directly to the exploded directory, which is useful for development. | There are several ways to deploy a Tomcat webapp:
* Dropping into $CATALINA\_HOME/webapps, as was already mentioned.
* Using your build scripts to deploy automatically via the manager interface (that comes with Tomcat). Here are the two ways
+ for *Maven*: use the tomcat plugin. You don't need to include it in `pom.... | Deployment of war file on Tomcat | [
"",
"java",
"linux",
"tomcat",
"deployment",
"release-management",
""
] |
Our company runs a web site (oursite.com) with affiliate partners who send us traffic. In some cases, we set up our affiliates with their own subdomain (affiliate.oursite.com), and they display selected content from our site on their site (affiliate.com) using an iframe.
Example of a page on their site:
```
<html>
<h... | 1. You have to append the Google Analytics tracking code to the end of `example_page.html`. The content between the `<iframe>` - `</iframe>` tag only displays for browsers, which do not support that specific tag.
2. Should you need to merge the results from the subdomains, there's an excellent article on Google's help ... | In the specific case of iframes, Google doesn't say much. I've been in the same situation but I'm glad I figured it out. I posted a [walkthrough here](http://www.emarketeur.fr/gestion-de-projet/developper/mesurer-son-trafic-sur-plusieurs-domaines-au-travers-dun-iframe-avec-google-analytics). It's in French but you won'... | Running Google Analytics in iframe? | [
"",
"javascript",
"iframe",
"google-analytics",
"cross-domain",
"tracking",
""
] |
How can I unset variable? For example, PHP has an `unset($var)` function. | There is not really an equivalent to "unset".
The closest match I know is the use of the [default](http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx) keyword.
For example:
```
MyType myvar = default(MyType);
string a = default(string);
```
The variable will still be "set", but it will have its default va... | You can't. There's no notion of "unsetting" a variable. You can set it to a different value - 0, null, whatever's appropriate. Instance/static variables don't even have a concept of whether the variable is set/unset, and local variables only have "definitely assigned" or "not definitely assigned".
What is it you're tr... | How to unset variable in C#? | [
"",
"c#",
""
] |
I've been unable to build [P4Python](http://www.perforce.com/perforce/loadsupp.html#api) for an Intel Mac OS X 10.5.5.
These are my steps:
1. I downloaded p4python.tgz (from
<http://filehost.perforce.com/perforce/r07.3/tools/>) and expanded
it into "P4Python-2007.3".
2. I downloaded p4api.tar (from
<http://f... | The newer version 2008.1 will build with Python 2.4.
I had posted the minor changes required to do that on my P4Python page, but they were rolled in to the official version.
Robert | From <http://bugs.mymediasystem.org/?do=details&task_id=676> suggests that Py\_ssize\_t was added in python 2.5, so it won't work (without some modifications) with python 2.4.
Either install/compile your own copy of python 2.5/2.6, or work out how to change P4Python, or look for an alternative python-perforce library. | How do I build and install P4Python for Mac OS X? | [
"",
"python",
"macos",
"perforce",
"p4python",
""
] |
I have a table of items, each of which has a date associated with it. If I have the date associated with one item, how do I query the database with SQL to get the 'previous' and 'subsequent' items in the table?
It is not possible to simply add (or subtract) a value, as the dates do not have a regular gap between them.... | My own attempt at the set solution, based on TheSoftwareJedi.
First question:
```
select date from test where date = 8
union all
select max(date) from test where date < 8
union all
select min(date) from test where date > 8
order by date;
```
Second question:
While debugging this, I used the data set:
```
(key:date... | Select max(element) From Data Where Element < 8
Union
Select min(element) From Data Where Element > 8
But generally it is more usefull to think of sql for set oriented operations rather than iterative operation. | What is the SQL for 'next' and 'previous' in a table? | [
"",
"sql",
""
] |
I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.
I did some search to try to find a pythonic way to do this task. Generally I got quite much nothin... | There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example:
```
class Whois(object):
_whois_by_query_cache = {}
def __init__(self, query):
"""Initializes the instance variables... | Found this question in the process of my own search for a python whois library.
Don't know that I agree with cdleary's answer that using a library that wraps
a command is always the best way to go - but I can see his reasons why he said this.
Pro: cmd-line whois handles all the hard work (socket calls, parsing, etc)
... | What Python way would you suggest to check whois database records? | [
"",
"python",
"system-administration",
"whois",
""
] |
Let's say I have a class that has a member called data which is a list.
I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.
What's your technique for doing this?
Do you just check the type by looking at `__class__`?
Is there so... | A much neater way to get 'alternate constructors' is to use classmethods. For instance:
```
>>> class MyData:
... def __init__(self, data):
... "Initialize MyData from a sequence"
... self.data = data
...
... @classmethod
... def fromfilename(cls, filename):
... "Initialize MyD... | with python3, you can use [Implementing Multiple Dispatch with Function Annotations](https://github.com/dabeaz/python-cookbook/blob/master/src/9/multiple_dispatch_with_function_annotations/example1.py) as Python Cookbook wrote:
```
import time
class Date(metaclass=MultipleMeta):
def __init__(self, year:int, mont... | How to overload __init__ method based on argument type? | [
"",
"python",
"constructor",
"operator-overloading",
""
] |
I have a table in my database which stores a tree structure. Here are the relevant fields:
```
mytree (id, parentid, otherfields...)
```
I want to find all the leaf nodes (that is, any record whose `id` is not another record's `parentid`)
I've tried this:
```
SELECT * FROM mytree WHERE `id` NOT IN (SELECT DISTINCT ... | Your query didn't work because the sub-query includes `NULL`. The following slight modification works for me:
```
SELECT * FROM `mytree` WHERE `id` NOT IN (
SELECT DISTINCT `parentid` FROM `mytree` WHERE `parentid` IS NOT NULL)
``` | No clue why your query didn't work. Here's the identical thing in left outer join syntax - try it this way?
```
select a.*
from mytree a left outer join
mytree b on a.id = b.parentid
where b.parentid is null
``` | Find leaf nodes in hierarchical tree | [
"",
"sql",
"database",
"tree",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.