Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I know what PermGen is, what it's used for, why it fails, how to increase it etc.
What I don't know is what PermGen actually stands for. Permanent... Gen... something?
Does anyone know what PermGen actually stands for? | Permanent Generation. Details are of course implementation specific.
Briefly, it contains the Java objects associated with classes and interned strings. In Sun's client implementation with sharing on, `classes.jsa` is memory mapped to form the initial data, with about half read-only and half copy-on-write.
Java objec... | PermGen is used by the JVM to hold loaded classes. You can increase it using:
`-XX:MaxPermSize=384m`
if you're using the Sun JVM or OpenJDK.
So if you get an OutOfMemoryException: PermGen you need to either make PermGen bigger or you might be having class loader problems. | What does PermGen actually stand for? | [
"",
"java",
"permgen",
""
] |
For my Java game server I send the Action ID of the packet which basically tells the server what the packet is for. I want to map each Action ID (an integer) to a function. Is there a way of doing this without using a switch? | What about this one?
```
HashMap<Integer, Runnable> map = new HashMap<Integer, Runnable>();
map.put(Register.ID, new Runnable() {
public void run() { functionA(); }
});
map.put(NotifyMessage.ID, new Runnable() {
public void run() { functionB(); }
});
// ...
map.get(id).run();
```
(If you need to pass some a... | Another similar approach could be using Java 8's Suppliers:
```
Map<Integer, Supplier<T>> suppliers = new HashMap();
suppliers.put(1, () -> methodOne());
suppliers.put(2, () -> methodTwo());
// ...
public T methodOne() { ... }
public T methodTwo() { ... }
// ...
T obj = suppliers.get(id).run();
``` | Function pointers/delegates in Java? | [
"",
"java",
"delegates",
"function-pointers",
""
] |
I haven't used a statically typed language in many years and have set myself the task of getting up to speed with C#. I'm using my usual trick of following the fifteen exercises here <http://www.jobsnake.com/seek/articles/index.cgi?openarticle&8533> as my first task.
I've just finished the second Fibonacci task which ... | As an iterator block:
```
using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static IEnumerable<long> Fibonacci() {
long n = 0, m = 1;
yield return 0;
yield return 1;
while (true) {
long tmp = n + m;
n = m;
... | If you prefer recursion instead of the loop:
```
public static void Main(string[] args)
{
Func<int, int> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
int start = 1;
int end = 10;
var numbers = Enumerable.Range(start, end).Select(fib);
foreach (var number in numbers)
{
... | Refactoring Fibonacci Algorithm | [
"",
"c#",
"refactoring",
""
] |
Supposing to have something like this:
```
#include <map>
int main(){
std::map<int,int> m;
m[1] = 2;
m[2] = 4;
return 0;
}
```
I would like to be able to inspect the contents of the map running the program from gdb.
If I try using the subscript operator I get:
```
(gdb) p m[1]
Attempt to take addre... | I think there isn't, at least not if your source is optimized etc. However, there are some macros for gdb that can inspect STL containers for you:
<http://sourceware.org/ml/gdb/2008-02/msg00064.html>
However, I don't use this, so YMMV | The existing answers to this question are **very** out of date. With a recent GCC and GDB it Just WorksTM thanks to the built-in Python support in GDB 7.x and the libstdc++ pretty printers that come with GCC.
For the OP's example I get:
```
(gdb) print m
$1 = std::map with 2 elements = {[1] = 2, [2] = 4}
```
If it d... | Inspecting standard container (std::map) contents with gdb | [
"",
"c++",
"stl",
"dictionary",
"gdb",
""
] |
I'm trying to work out a way of passing the web current http context to a service class (or initialising the class with a reference to it). I am doing this to abstract the rest of the app away from needing to know anything about the http context.
I also want the service to be testable using TDD, probably using one of ... | This is why HttpContextBase and HttpContextWrapper were introduced. You probably want to use HttpContextBase and when passing the real context in, use `new HttpContextWrapper( httpContext )`, although, I think that what is available to you in the controller is already of type HttpContextBase. I would create one of thes... | What we do is spin one of these up <http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx>
Easy as pie, just instanciate an HttpSimulator and fill in the values, and HttpContext.Current gets filled up with whatever you specify.
IHttpContext is something that is in MVC... | Passing web context to a 'service' in ASP MVC app | [
"",
"c#",
".net",
"asp.net-mvc",
"tdd",
"mocking",
""
] |
In the [Boost Signals](http://www.boost.org/doc/html/signals.html "Boost Signals documentation") library, they are overloading the () operator.
Is this a convention in C++? For callbacks, etc.?
I have seen this in code of a co-worker (who happens to be a big Boost fan). Of all the Boost goodness out there, this has o... | One of the primary goal when overloading operator() is to create a functor. A functor acts just like a function, but it has the advantages that it is stateful, meaning it can keep data reflecting its state between calls.
Here is a simple functor example :
```
struct Accumulator
{
int counter = 0;
int operator... | It allows a class to act like a function. I have used it in a logging class where the call should be a function but i wanted the extra benefit of the class.
so something like this:
```
logger.log("Log this message");
```
turns into this:
```
logger("Log this message");
``` | Why override operator()? | [
"",
"c++",
"boost",
"operator-overloading",
"functor",
"function-call-operator",
""
] |
Is there C# look-alike for Linux? What about a compiler? | There is another language called [Vala](http://live.gnome.org/Vala). It's not well known, but as you can see from the page, an interesting amount of projects have been produced already. | You could actually use C# with [Mono](http://www.mono-project.com/). | Is there C# look-alike for Linux? | [
"",
"c#",
"linux",
"compiler-construction",
""
] |
I'm looking for a good, simple PHP function to get my latest Facebook status updates. Anyone know of one?
Thanks!
**EDIT:** I've added a half-solution below.
Or if anyone knows a good way to read in the RSS feed and spit out the recent status update? | Since I couldn't use the API route, I went with the RSS found at: <http://www.new.facebook.com/minifeed.php?filter=11>
And used the following PHP function, [called StatusPress](http://www.paradoxica.net/2007/08/30/statuspress/), with some of my own modifications, to parse the RSS feed for my Facebook status. Works gre... | A quick check on [PEAR](http://pear.php.net) found [Services\_Facebook](http://pear.php.net/package/Services_Facebook) | PHP function to get Facebook status? | [
"",
"php",
"facebook",
"status",
"updates",
""
] |
Most C++ naming conventions dictate the use of `camelCaseIdentifiers`: names that start with an uppercase letter for classes (`Person`, `Booking`) and names that start with a lowercase letter for fields and variables (`getPrice()`, `isValid()`, `largestValue`). These recommendations are completely at odds with the nami... | One way it to adopt the C++ `naming_convention`, this is what most code examples in the literature do nowadays.
I slowly see these conventions move into production code but it's a battle against MFC naming conventions that still prevail in many places.
Other style differences that fight against old standards are usin... | Diomidis, I share your pain and have spent a lot of time switching between different schemes over the years, trying to find something that works with the different libraries/frameworks that I use (MFC and/or STL/Boost). When working with a single framework, such as the STL, you can try and copy the naming convention it... | How do you reconcile common C++ naming conventions with those of the libraries | [
"",
"c++",
"coding-style",
"naming-conventions",
""
] |
I have a spec in my current project that requires us to advise the user which browsers are best to use the web application. If their current browser version they are using is not in our list of "ideal" browsers we want to display a message.
What is the best way to check a specific version of the users browser. I am aw... | [Here](http://davecardwell.co.uk/javascript/jquery/plugins/jquery-browserdetect/) is a JQuery plugin that'll help | Also check for $.browser.version in the docs.jquery.com
It can return 2.0 for Firefox 2.x.x, check the docs :) | Browser version Detection | [
"",
"javascript",
"jquery",
"browser",
""
] |
I want to display an image at 'true size' in my application. For that I need to know the pixel size of the display.
I know windows display resolution is nominally 96dpi, but for my purposes I want a better guess. I understand this information may not always be available or accurate (e.g. older CRT displays), but I ima... | For the display size you'll want [`Screen`](http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx)`.PrimaryScreen.Bounds.Size` (or `Screen.GetBounds(myform)`).
If you want the DPI, use the [DpiX](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.dpix.aspx) and [DpiY](http://msdn.micros... | sorry, you've got to P/Invoke for this information.
Here's the link that I utilized for it a while ago:
<http://www.davidthielen.info/programming/2007/05/get_screen_dpi_.html> | How do I determine the true pixel size of my Monitor in .NET? | [
"",
"c#",
".net",
"windows",
""
] |
I haven't looked at this in a while, but if I recall correctly both ant and maven still rely on JUnit 3 for unit tests (as of maven 2.09 the default POM file still has JUnit 3.81).
Does it still make sense to stick to JUnit 3 instead of using the latest and greatest? Any good reason I might be missing? | I don't see a reason to stick to the 3.x versions. Most tools have been compatible with 4.x for a while now. The only reason I would stick to 3.x is in a java 1.4 environment (because there is no other way).
By the way, maven is switching to Java 5 in 2.1, so there is a chance they will propose junit 4.x | JUnit 4 has lots of advantages over 3.x. The most important is that you no longer have to extend TestCase, nor do your test methods have to begin with "test." It's all annotation-based now. You can also add the Hamcrest matchers, which gives you a really nice and expressive way of writing test assertions.
If you're st... | Is running tests with JUnit 3.x vs JUnit 4.x still a best practice? | [
"",
"java",
"unit-testing",
"junit",
""
] |
I'm currently wrestling with an Oracle SQL DATE conversion problem using iBATIS from Java.
Am using the Oracle JDBC thin driver ojdbc14 version 10.2.0.4.0. iBATIS version 2.3.2. Java 1.6.0\_10-rc2-b32.
The problem revolves around a column of DATE type that is being returned by this snippet of SQL:
```
SELECT *
FROM ... | The full info (and it's more complex than described here and might depend upon which particular version of the Oracle drivers are in use) is in Richard Yee's answer here - [now expired link to Nabble]
---
Quick grab before it expires from nabble...
Roger,
See: <http://www.oracle.com/technetwork/database/enterprise-e... | I found out how to solve this problem. iBATIS permits custom type handlers to be registered. So in my sqlmap-config.xml file I added this:
```
<typeAlias alias="OracleDateHandler" type="com.tideworks.ms.CustomDateHandler"/>
<typeHandler callback="OracleDateHandler" jdbcType="DATETIME" javaType="date"/>
```
And then a... | Oracle SQL DATE conversion problem using iBATIS via Java JDBC | [
"",
"java",
"oracle",
"date",
"jdbc",
"ibatis",
""
] |
I'm building a new app that is using NHibernate to generate the database schema but i can see a possible problem in the future.
Obviously you use all the data from your database is cleared when you update the schema but what stratagies do people use to restore any data to the new database. I am aware that massive chan... | When testing, we use NHibernate to create the database, then a series of [builders](http://en.wikipedia.org/wiki/Builder_pattern) to create the data for each test fixture. We also use Sqlite for these tests, so they are lightening fast.
Our builders look a something like this:
```
public class CustomerBuilder : Build... | I think it is a good thing in many situations to let NHibernate generate the schema for you. To recreate the test data you either use code driven by a testing framework (such as NUnit) or you could export your test data as a SQL script which you can run after you have updated the schema. | Strategies for using NHibernate to generate a schema | [
"",
"sql",
"nhibernate",
""
] |
[Mono](http://www.mono-project.com/) claims to be compatible with .NET.
Have you tried it?
Can you share any tips or guidelines for making a running .NET application compatible with mono? | Might be [MoMA](http://www.mono-project.com/MoMA) helps you | See these documents for in-depth answers:
* General document about [Application Portability](http://www.mono-project.com/Guidelines:Application_Portability)
* [Porting Winforms Applications](http://www.mono-project.com/Guide:_Porting_Winforms_Applications)
* [Porting ASP.NET Applications](http://www.mono-project.com/G... | Guidelines to write C# applications for .NET and mono | [
"",
"c#",
".net",
"mono",
"cross-platform",
"porting",
""
] |
In my everlasting quest to suck less I'm trying to understand the "yield" statement, but I keep encountering the same error.
> The body of [someMethod] cannot be an iterator block because
> 'System.Collections.Generic.List< AClass>' is not an iterator interface type.
This is the code where I got stuck:
```
foreach (... | A method using *yield return* must be declared as returning one of the following two interfaces:
```
IEnumerable<SomethingAppropriate>
IEnumerator<SomethingApropriate>
```
(thanks [Jon](https://stackoverflow.com/users/22656/jon-skeet) and [Marc](https://stackoverflow.com/users/23354/marc-gravell) for pointing out IEn... | It's a tricky topic. In a nutshell, it's an easy way of implementing IEnumerable and its friends. The compiler builds you a state machine, transforming parameters and local variables into instance variables in a new class. Complicated stuff.
I have a few resources on this:
* [Chapter 6 of C# in Depth](https://www.man... | Some help understanding "yield" | [
"",
"c#",
"iterator",
"yield",
""
] |
I have a small application to convert several file formats, with a main windows form which contains several text boxes, buttons, etc. I have another "Document" class which handles all of the actual conversion work, and my form essentially iterates through all of the files, and calls the proper Document methods to conve... | The simplest solution is to have your processing done on a background thread using the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx "BackgroundWorker") component. You can drag it in from the VS toolbox. It allows you to update the UI thread with progress notific... | You should use two threads so that the form continues to respond while you do work.
This is so common that .NET has a BackgroundWorker control that wraps some of this up for you. | Windows Forms: Progress Bar Unresponsive | [
"",
"c#",
"winforms",
""
] |
I'm always surprised that even after using C# for all this time now, I still manage to find things I didn't know about...
I've tried searching the internet for this, but using the "~" in a search isn't working for me so well and I didn't find anything on MSDN either (not to say it isn't there)
I saw this snippet of c... | ~ is the unary one's complement operator -- it flips the bits of its operand.
```
~0 = 0xFFFFFFFF = -1
```
in two's complement arithmetic, `~x == -x-1`
the ~ operator can be found in pretty much any language that borrowed syntax from C, including Objective-C/C++/C#/Java/Javascript. | I'd think that:
```
[Flags]
public enum PurchaseMethod
{
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4,
All = Cash | Check | CreditCard
}
```
Would be a bit more clear. | What is the tilde (~) in the enum definition? | [
"",
"c#",
"enums",
"language-features",
"enumeration",
""
] |
I've added a label control to a webform. It appears when I run the page but when I try to reference it using the codebehind, I get no intellisense and the code I write somehow doesn't work. I've verified the project is running in debug, that debug compilation is set in the web.config. In fact, I can debug all pages. Ho... | In the past I've had problems with this because the auto-generated designer files were bad. Try deleting them and then allow VS to recreate them, this may fix the problem. | Something similar happens to me from time to time...I add a control and I get no intellisense...VS basically has no idea the control is on the page/designer. If I close the file (codebehind and HTML) and come back...everything is honky dory. Clunky, but it works. Worth a try. I'm using 2008 BTW. | Intellisense not showing up for new controls in code behind | [
"",
"c#",
".net",
"asp.net",
"debugging",
""
] |
Why does C++ have header files and .cpp files? | Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.
This reduces dependencies so that code that uses the header doesn't necessarily need to kn... | ## C++ compilation
A compilation in C++ is done in 2 major phases:
1. The first is the compilation of "source" text files into binary "object" files: The CPP file is the compiled file and is compiled without any knowledge about the other CPP files (or even libraries), unless fed to it through raw declaration or heade... | Why have header files and .cpp files? | [
"",
"c++",
"header-files",
""
] |
Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it?
Aside from grabbing a string, file or url I have no idea of where to start with this. | Because python supports some algebraic forms, you could do:
```
eval("1 + 1")
```
But this allows the input to execute about anything defined in your env:
```
eval("__import__('sys').exit(1)")
```
Also, if you want to support something python doesn't support, the approach fails:
```
x³ + y² + c
----------- = 0
... | If you are receiving an expression as a string you'll need to parse it into its operators and operands and then process the resulting tree. This isn't a python problem per se. but a general issue of how to deal with mathematical expressions delivered as strings.
A quick google reveals a bunch of lexical parsers for py... | Reading and running a mathematical expression in Python | [
"",
"python",
""
] |
I have a container element which I need to resize as its contents change. It contains 2 absolutely positioned divs which can both change height. If I don't specify the height of the container then anything after the container disappears under the contents.
At the moment I am doing the following but I'd be pleased to f... | This is a very odd question, as div's height is always the height of its children.
Are you floating content in your container div? When you float child content the containing div doesn't act the same anymore.
If you're floating content that extends past the bottom of the container div, add the following div to the ve... | if you're floating the container div "overflow: auto" can also work magically, esp with regard to the whole IE hasLayout debacle | How to resize a container div to the total height of its children? | [
"",
"javascript",
"jquery",
"dom",
""
] |
I have a string with markup in it which I need to find using Java.
eg.
```
string = abc<B>def</B>ghi<B>j</B>kl
desired output..
segment [n] = start, end
segment [1] = 4, 6
segment [2] = 10, 10
``` | Regular expressions should work wonderfully for this.
Refer to your JavaDoc for
* java.langString.split()
* java.util.regex package
* java.util.Scanner
Note: StringTokenizer is not what you want since it splits around *characters*, not strings - the string delim is a list of characters, any one of which will split. ... | Given your example I think I'd use regex and particularly I'd look at the grouping functionality offered by Matcher.
Tom
```
String inputString = "abc<B>def</B>ghi<B>j</B>kl";
String stringPattern = "(<B>)([a-zA-Z]+)(<\\/B>)";
Pattern pattern = Pattern.compile(stringPattern);
Matcher matcher = pattern.matcher(input... | What is the best way to find specific tokens in a string (in Java)? | [
"",
"java",
"string",
""
] |
In my current project, I'm producing weekly releases. I've been using the technique described in [this post](http://jebsoft.blogspot.com/2006/04/consistent-version-numbers-across-all.html) to keep the version numbers of all of the assemblies in my project in sync. (I don't presently have any good reason to track the as... | CodeProject has a script to set the version number of an MSI file, which you could run in the pre-built step of the setup project. You find it here:
> <http://www.codeproject.com/KB/install/NewSetupVersion.aspx>
**More Details**
Be aware that with Windows Installer things are a bit more complicated. MSI files (as th... | Its going to depend on the installer toolkit you are using.
We use TFS Team Build and [WiX v3](http://wix.sourceforge.net/). I have a custom build task that increments the build number in Team build (5.0.0.X for example), then this version number is pushed to the common AssemblyInfo.cs AssemblyFileVersion field. It is... | How to keep the installer's version number in sync with the installed assemblies' version numbers? | [
"",
"c#",
"visual-studio",
"deployment",
""
] |
I want to get the UCS-2 code points for a given UTF-8 string. For example the word "hello" should become something like "0068 0065 006C 006C 006F". Please note that the characters could be from any language including complex scripts like the east asian languages.
So, the problem comes down to "convert a given characte... | [Scott Reynen](https://stackoverflow.com/users/10837/scott-reynen) wrote a function to [convert UTF-8 into Unicode](http://randomchaos.com/documents/?source=php_and_unicode). I found it looking at the [PHP documentation](http://us.php.net/manual/en/function.unicode-encode.php#73422).
```
function utf8_to_unicode( $str... | Use an existing utility such as [iconv](http://www.gnu.org/software/libiconv/), or whatever libraries come with the language you're using.
If you insist on rolling your own solution, read up on the [UTF-8](http://en.wikipedia.org/wiki/Utf-8) format. Basically, each code point is stored as 1-4 bytes, depending on the v... | How to get code point number for a given character in a utf-8 string? | [
"",
"php",
"unicode",
""
] |
In SQL server you can use the DATENAME function to get the day of week as a string
```
declare @date datetime
set @date = '12/16/08'
select datename(dw, @date)
```
which returns "Tuesday"
and you can use the DATEPART function to get the day of week as an integer
```
declare @date datetime
set @date = '12/16/08'
sel... | Rather than write a function, you should create a days of the week table with the description and the numeric value. THen you can simply join to the table to get the numeric.
And if you have days stored multiple ways (likely in a characterbased system), you can put all the variants into the table, so TUE, Tues., Tuesd... | unfortunately there isn't a built in function, but you can create your own like this:
```
CREATE FUNCTION dbo.WeekDay(@DayOfWeek Varchar(9))
RETURNS INT
AS
BEGIN
DECLARE @iDayofWeek INT
SELECT @iDayofWeek = CASE @DayOfWeek
WHEN 'Sunday' THEN 1
WHEN 'Monda... | Converting the name of a day to its integer representation | [
"",
"sql",
"sql-server",
"type-conversion",
""
] |
In trying to make my Javascript unobtrusive, I'm using `onLoad`s to add functionality to `<input>`s and such. With Dojo, this looks something like:
```
var coolInput = dojo.byId('cool_input');
if(coolInput) {
dojo.addOnLoad(function() {
coolInput.onkeyup = function() { ... };
});
}
```
Or, approximately equiv... | The exact syntax you want is not possible in JavaScript. The way JavaScript executes would need to change in a pretty fundamental fashion. For example:
```
var name = getUserById(id).andand().name;
// ^
// |-------------------------------
// if getUserById returns null, ex... | I don't know Dojo, but shouldn't your first example read
```
dojo.addOnLoad(function() {
var coolInput = dojo.byId('cool_input');
if(coolInput)
coolInput.onkeyup = function() { ... };
});
```
Otherwise, you might end up trying to access the element before the DOM has been built.
Back to your question... | Is there a Javascript equivalent of Ruby's andand? | [
"",
"javascript",
"ruby",
"andand",
""
] |
I am having lot of CPU and IO intensive code in shutdown hook. Some times I see they are not getting executed properly.
So Is there any limitation like we should not have lot of code in shutdown hook.
Thanks
D. L. Kumar | Simply No. [Read carefully API](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)) and you will see. There is limited time to shutdown. If you extend over this time slot the JVM will simply end/terminate without notification. If you are writing data, you will write down co... | I have placed some fairly substantial code in a shutdown hook for one of my apps, and it executes very reliably on a variety of O/S's (Windows XP, Vista, AS400/iSeries/Systemi, Linux) under a variety of circumstances, including sigterms and Windows shutdown.
But beware of any system's shutdown timeout (ala Windows goo... | Can I place lot of CPU and IO intensive code in ShutDown Hook | [
"",
"java",
""
] |
I know java and would normally put in getter/setter methods. I am interested in doing it in C# with the following code, but it throws a StackOverflow exception. What am I doing wrong?
Calling Code
```
c.firstName = "a";
```
Property Code
```
public String firstName;
{
get
{
return firstName;
}
... | It's because you're recursively calling the property - in the `set` you are setting the property again, which continues *ad infinitum* until you blow the stack.
You need a private backing field to hold the value, e.g.
```
private string firstName;
public string FirstName
{
get
{
return this.firstName... | You are setting the property name inside your property--not the field name. This would work better:
```
private string m_firstName;
public String firstName;
{
get
{
return m_firstName;
}
set
{
m_firstName = value;
}
}
``` | Why does Property Set throw StackOverflow exception? | [
"",
"c#",
""
] |
I have an MS SQL server application where I have defined my relationships and primary keys.
However do I need to further define indexes on relationship fields which are sometimes not used in joins and just as part of a where clause?
I am working on the assumption that defining a relationship creates an index, which t... | No indexes will be automatically created on foreign keys constraint. But unique and primary key constraints will create theirs.
Creating indexes on the queries you use, be it on joins or on the WHERE clause is the way to go. | Some very thick books have been written on this subject!
Here are some ruiles of thumb:-
Dont bother indexing (apart from PK) any table with < 1000 rows.
Otherwise index all your FKs.
Examine your SQL and look for the where clauses that will most reduce your result sets and index that columun.
eg. given:
```
... | SQL Relationships and indexes | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm having problems allocating and deallocating my memory in a recursive C++ program. So without using an automatic memory management solution, I wonder if anyone can help me resolve the memory leak I am experiencing.
The following code essentially explains the problem (although it's a contrived example, please correc... | The problem is here:
```
Number& operator + (const Number& n1) const {
Number result = value + n1.value;
return result;
};
```
You're returning a local variable (`result`) by reference, and that's a big NO-NO. Local variables are allocated on the stack, and when the function exits, the variables are gone. Ret... | I don't see why you're allocating the memory on the heap to begin with:
```
Number& recurse(const Number& v1) {
Number result;
Number one;
// I assume there is a step here to determine if the recursion should stop
result += recurse(one);
return result;
}
```
By allocating only on the stack you'r... | Memory Allocation in Recursive C++ Calls | [
"",
"c++",
"memory",
"memory-leaks",
"recursion",
""
] |
My employers website has multiple hostnames that all hit the same server and we just show different skins for branding purposes.
Unfortunately WCF doesn't seem to work well in this situation.
I've tried [overriding the default host with a custom host factory](http://www.robzelt.com/blog/2007/01/24/WCF+This+Collection... | If you don't put an address in the endpoint then it should resolve to whatever server hits the service. I use this code and it resolves both to my .local address and to my .com address from IIS.
```
<system.serviceModel>
<services>
<service name="ServiceName" behaviorConfiguration="ServiceName.Service1Beha... | I don't think that the **host base addresses** solution posted above will work for IIS-hosted websites (the OP did mention that this was for his employer's *website*).
See [this blog post](http://www.pluralsight.com/community/blogs/aaron/archive/2006/07/13/31879.aspx "this blog post")
Also, the other answer further u... | WCF and Multiple Host Headers | [
"",
"c#",
"wcf",
"iis",
"iis-6",
""
] |
I have a MySQL Left Join problem.
I have three tables which I'm trying to join.
A person table:
```
CREATE TABLE person (
id INT NOT NULL AUTO_INCREMENT,
type ENUM('student', 'staff', 'guardian') NOT NULL,
first_name CHAR(30) NOT NULL,
last_name CHAR(30) NOT NULL,
gender ENUM('m', 'f') NOT NULL,
... | What you are doing is fine, you just missed off the group by clause
```
SELECT p.first_name, p.last_name, COUNT(i.student)
FROM person p, student s LEFT JOIN incident i ON s.id = i.student
WHERE p.id = s.person_id AND s.year_group LIKE "%Year 9%"
GROUP BY p.first_name, p.last_name;
```
Here's some test data
```
in... | Would that not be a left outer join you are looking for? I may have my terminology mixed up? Would not be the first time. But Aron's answer would work. | Why is this LEFT JOIN eliminating records with nothing in the other table? | [
"",
"mysql",
"sql",
"join",
"left-join",
""
] |
For example: I'm on MS DOS, I have a source code in the folder C:\Documents and Settings\Programs. Can i make my source code use a program (for example gnuplot) that is in a random folder? | Here are some options:
1. Search in the system PATH for the executable you want to run
2. Allow the user to specify the location on the command-line
3. Store the location in a configuration file, and allow the user to specify it during install (if you have an install process) or by editing the file by hand
Ideally yo... | <http://www.codeproject.com/KB/system/newbiespawn.aspx>
ShellExecute will look into the PATH environment variable, so you don't need to specify the full PATH. Now, if it's really a random location and it's not even in the PATH environment variable, then I guess you are out of luck.
If they aren't even in the PATH, th... | How to use a program which is not in the source code's folder? | [
"",
"c++",
"dos",
""
] |
currently writes an application to connect to the device "BTLink Bluetooth to Serial Adapter"
More information about device: [device specification](http://cgi.ebay.pl/Bluetooth-to-RS232-Serial-Adapter-Dongle-100m-UK_W0QQitemZ300266522534QQcmdZViewItem?hash=item300266522534&_trkparms=72%3A1399|39%3A1|66%3A2|65%3A12|240... | I would first try to connect to the target machine using the device's built-in Bluetooth capabilities. Only after this succeeds would I try to connect to it programatically.
To be able to connect to a Bluetooth device you need to know the following:
* The Bluetooth profile to use. You've tried both Serial and Dialup,... | Have you checked with 32Feet.net or on [their support Forums](http://inthehand.com/forums/default.aspx?GroupID=29) (the provider of the [classes you're using](http://inthehand.com/content/32feet.aspx))? | Bluetooth to Serial Adapter - Connection Exception | [
"",
"c#",
"windows-mobile",
"compact-framework",
"bluetooth",
""
] |
Is there a convention for naming the private method that I have called "`_Add`" here? I am not a fan of the leading underscore but it is what one of my teammates suggests.
```
public Vector Add(Vector vector) {
// check vector for null, and compare Length to vector.Length
return _Add(vector);
}
public static ... | I usually see and use either "AddCore" or "InnerAdd" | I've never seen any coding convention in C# that distinguished between public and private methods. I don't suggest doing it, since I don't see the benefit.
If the method name conflicts with public methods, it’s time to become more descriptive; if, as in your case, it contains the actual method *implementation* for the... | Private method naming convention | [
"",
"c#",
"coding-style",
"private-methods",
""
] |
> **Possible Duplicate:**
> [How to properly clean up Excel interop objects in C#](https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c-sharp)
I've read many of the other threads here about managing COM references while using the .Net-Excel interop to make sure the Excel pro... | I don't have the code to hand, but I did run into a similar problem.
If I recall correctly, I ended up retrieving the process id of the excel instance, and killing it (after a suitable wait period, and when the other method failed).
I think I used:
`GetWindowThreadProcessId` (via P/Invoke) on the excel object hwnd pr... | I have done a similar thing. I create an Excel file or open an existing. I delete all the sheets and add my own. here is the code I use to ensure all references are closed:
```
workbook.Close(true, null, null);
excelApp.Quit();
if (newSheet != null)
{
Sy... | C# interop: excel process not exiting after adding new worksheet to existing file | [
"",
"c#",
"excel",
"com",
"interop",
"pia",
""
] |
### Disclaimer
Yes, I am fully aware that what I am asking about is totally stupid and that anyone who would wish to try such a thing in production code should be fired and/or shot. I'm mainly looking to see if *can* be done.
Now that that's out of the way, is there any way to access private class members in C++ from... | If the class contains any template member functions you can specialize that member function to suit your needs. Even if the original developer didn't think of it.
safe.h
```
class safe
{
int money;
public:
safe()
: money(1000000)
{
}
template <typename T>
void backdoor()
{
/... | I've added an [entry to my blog](http://bloglitb.blogspot.de/2011/12/access-to-private-members-safer.html) (see below) that shows how it can be done. Here is an example on how you use it for the following class
```
struct A {
private:
int member;
};
```
Just declare a struct for it where you describe it and instant... | Can I access private members from outside the class without using friends? | [
"",
"c++",
"encapsulation",
"private-members",
""
] |
I need to build a C++ library to distribute among our customers. The library must be able to be accessed from a wide range of languages including VB6, C++, VB.net and C#.
I've being using ActiveX controls (ocx files) until now. But I wonder if there is a better kind of library (dll, etc.) that I can build. What do you... | Almost every language has a way of loading dynamic libraries and accessing exported C functions from them.
There is nothing preventing you from using C++ inside the dll but for maximum portability, export only C functions.
I have some more about this in this [post](https://stackoverflow.com/questions/62398/middleware-... | If you're looking at supporting both VB6 and .NET, you're pretty much stuck with exposing interfaces via COM, but at least that'll get you out of having to create more than one wrapper based on the language/runtime system you're trying to interact with. | What kind of code library should I build for distribution? | [
"",
"c++",
"com",
"dll",
"vb6",
"ocx",
""
] |
So I've just recently made the step from ad hoc debugging with `dump`, `print_r` and `echo` to some more sophisticated methods and I'm having a struggle.
I work with Zend Framework, Aptana and Zend Debugger.
At this moment I'm trying to debug a custom controller and whatever I try I don't get to my breakpoint which I... | You want to change the current user's authentication details mid-way through a request?
I don't think this is possible. Zend Debugger is pretty much a read-only tool. Even if it were, you're assuming that whatever framework you're using can handle this. That would mean it would have to constantly try to synchronize it... | Wouldn't it be easier to set up a constant such as:
```
define('MODE_DEBUG', 1);
```
Then check in the authentication process:
```
if($obj->myLoginMethod() || constant('MODE_DEBUG') == 1){
}
```
Noone will be able to inject into that constant and the worst thing that can happen is you end up leaving debug mode on ... | PHP debugging - where to set the breakpoints? How to authenticate? | [
"",
"php",
"debugging",
"zend-framework",
"breakpoints",
"zend-debugger",
""
] |
Could you explain the difference between setting methods in the constructor and through prototype object? The following code shows these two ways of setting the methods - `say_hello` and `say_bye` both work fine:
```
function MessageClass() {
this.say_bye = function() { alert('see ya'); };
}
MessageClass.prototype.... | foxxtrot and annakata are both correct, but I'll throw in my 2 cents.
If you use the prototype then each instance of the "MessageClass" is really referencing the same functions. The functions exist in memory only once and are used for all instances. If you declare the methods in the constructor (or otherwise add it to... | If you bind methods by prototype JS only has to do it once and binds to an object class (which makes it elligible for OO JS extensions).
If you do the binding within the "class" function, JS has to do the work of creating and assigning for each and every instance. | Setting methods through prototype object or in constructor, difference? | [
"",
"javascript",
"constructor",
"prototype",
""
] |
Here's the .jsp code:
```
<table>
<s:iterator value="allAgents">
<tr>
<td><s:property value="firstName" /></td>
<td><s:property value="middleName" /></td>
<td><s:property value="lastName" /></td>
<td><s:checkbox name="ss"/></td>
... | Add the property theme="simple"
like | Struts2 renders s:checkbox as a table cell itself.The reason is tht struts2 uses a template system for tag rendering. The default is (as defined in struts-default.properties)
### Standard UI theme
struts.ui.theme=xhtml
struts.ui.templateDir=template
struts.ui.templateSuffix=ftl
You need to make this change -- stru... | struts2: s:checkbox doesn't go on the same row with s:checkbox | [
"",
"java",
"struts2",
"rendering",
""
] |
I have 3 projects in my VS solution. One of them is a Web app, the second one is a Windows Service and the last one a Setup project for my Web app.
What I want is by the end of the installation of the web app in my setup project, within my custom action to try and install my windows service given that I have the locat... | Ok, here is what REALLY worked for me, it has been tested on multiple machines with different OS ( Vista, XP, Win2k, Win2003 server )
The code has been taken from [here](http://www.tech-archive.net/Archive/VB/microsoft.public.vb.winapi/2006-08/msg00238.html) so full credit goes to whoever wrote this piece of code.
On... | I found several errors in the code that you reused and have fixed these and also cleaned it up a little. Again, the original code is taken from [here](http://www.tech-archive.net/Archive/VB/microsoft.public.vb.winapi/2006-08/msg00238.html).
```
public static class ServiceInstaller
{
private const int STANDARD_RIGH... | How to install a windows service programmatically in C#? | [
"",
"c#",
".net",
"windows-services",
"setup-project",
"visual-studio-setup-proje",
""
] |
I work on a web-based tool where we offer customized prints.
Currently we build an XML structure with Java, feed it to the [XMLmind XSL-FO Converter](http://www.xmlmind.com/foconverter/) along with customized XSL-FO, which then produces an RTF document.
This works fine on simple layouts, but there's some problem area... | If you could afford spending some money, you could use [Aspose.Words](http://www.aspose.com/categories/file-format-components/aspose.words-for-.net-and-java/default.aspx), a professional library for creating Word and RTF documents for Java and .NET. | You can take a look at a new library called [jRTF](http://code.google.com/p/jrtf/). It allows you to create new RTF documents and to fill RTF templates. | How do I generate RTF from Java? | [
"",
"java",
"xml",
"xslt",
"rtf",
""
] |
I've got a function creating some XmlDocument:
```
public string CreateOutputXmlString(ICollection<Field> fields)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = Encoding.GetEncoding("windows-1250");
StringBuilder builder = new StringBuilder();
X... | You need to use a StringWriter with the appropriate encoding. Unfortunately StringWriter doesn't let you specify the encoding directly, so you need a class like this:
```
public sealed class StringWriterWithEncoding : StringWriter
{
private readonly Encoding encoding;
public StringWriterWithEncoding (Encoding... | Just some extra explanations to why this is so.
Strings are sequences of characters, not bytes. Strings, per se, are not "encoded", because they are using characters, which are stored as Unicode codepoints. Encoding DOES NOT MAKE SENSE at String level.
An encoding is a mapping from a sequence of codepoints (character... | How to put an encoding attribute to xml other that utf-16 with XmlWriter? | [
"",
"c#",
"encoding",
"xmlwriter",
""
] |
I know that in C#, if you write `~MyClass()`, this basically translates to `override System.Object.Finalize()`. So, whether you write the *destructor* or not, every type in CLR will have a `Finalize()` method in it (of `System.Object` at least).
1] So, does it mean that, every object, by default, **has** a finalizer ?... | **Questions 1 and 2**: The CLR basically checks whether or not the finalizer is overridden. If it's not, it treats it as not having a finalizer.
The benefit of having a finalizer in System.Object is that compilers know they can *always* put a call to `base.Finalize()` in. This avoids versioning issues. Consider a worl... | 1: It only really counts (in the useful sense) if it has been overridden
2: As defined by 1, and GC.SuppressFinalize has not been called (plus re-register etc)
3: certainly not; in fact, unless you are directly handling an unmanaged resource, you **shouldn't** have a finalizer. You shouldn't add a finalizer just beca... | When does CLR say that an object has a finalizer? | [
"",
"c#",
".net",
"memory-management",
"garbage-collection",
""
] |
I know a lot about C# but this one is stumping me and Google isn't helping.
I have an IEnumerable range of objects. I want to set a property on the first one. I do so, but when I enumerate over the range of objects after the modification, I don't see my change.
Here's a good example of the problem:
```
public st... | When you call First() it enumerates over the result of this bit of code:
```
Select(i => new SubItem() {Name = "foo", MagicNumber = i});
```
Note that the Select is a lazy enumerator, meaning that it only does the select when you ask for an item from it (and does it *every* time you ask it). The results are not store... | I suspect something going in the background. Most likely due to the fact the IEnumerables can only be iterated once.
Does it work if you add a 'ToList()' after the call to Select() when assigning to 'items'? | Why does setting a property on an enumerated object not work? | [
"",
"c#",
"ienumerable",
""
] |
given the following code:
```
import ctypes
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)
```
how can I correctly pack this for a DLL that expects it as a c\_ulong datatype?
I've tried using:
```
ip_netFrmt = socket.inet_aton(ip)
ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt)
```... | The inet\_aton returns a string of bytes. This used to be the *lingua franca* for C-language interfaces.
Here's how to unpack those bytes into a more useful value.
```
>>> import socket
>>> packed_n= socket.inet_aton("128.0.0.1")
>>> import struct
>>> struct.unpack( "!L", packed_n )
(2147483649L,)
>>> hex(_[0])
'0x80... | First a disclaimer: This is just an educated guess.
an ip-address is traditionally represented as four bytes - i.e. xxx.xxx.xxx.xxx, but is really a unsigned long. So you should convert the representation 192.168.1.1 to an unsiged int. you could convert it like this.
```
ip="192.168.1.1"
ip_long = reduce(lambda x,y:x... | Python: packing an ip address as a ctype.c_ulong() for use with DLL | [
"",
"python",
"dll",
"ip-address",
"ctypes",
""
] |
I have an HTML element with a large collection of unordered lists contained within it. I need to clone this element to place elsewhere on the page with different styles added (this is simple enough using jQuery).
```
$("#MainConfig").clone(false).appendTo($("#smallConfig"));
```
The problem, however, is that all the ... | If you need a way to reference the list items after you've cloned them, you must use classes, not IDs. Change all id="..." to class="..."
If you are dealing with legacy code or something and can't change the IDs to classes, you must remove the id attributes before appending.
```
$("#MainConfig").clone(false).find("*"... | Since the OP asked for a way to replace all the duplicate id's before appending them, maybe something like this would work. Assuming you wanted to clone MainConfig\_1 in an HTML block such as this:
```
<div id="smallConfig">
<div id="MainConfig_1">
<ul>
<li id="red_1">red</li>
<li i... | jQuery clone duplicate IDs | [
"",
"javascript",
"jquery",
"html",
""
] |
I have a fairly expensive array calculation (SpectralResponse) which I like to keep to a minimum. I figured the best way is to store them and bring it back up when same array is needed again in the future. The decision is made using BasicParameters.
So right now, I use a LinkedList of object for the arrays of Spectral... | You are accessing a LinkedList by index, this is the worst possible way to access it ;)
You should use ArrayList instead, or use iterators for all your lists.
Possibly you should merge the three objects into one, and keep them in a map with responseNum as key.
Hope this helps! | You probably should use an array type (an actual array, like Vector, ArrayList), not Linked lists. Linked lists is best for stack or queue operation, not indexing (since you have to traverse it from one end). Vector is a auto resizing array, wich has less overhead in accessing inexes. | Storing & lookup double array | [
"",
"java",
"lookup",
""
] |
I have a scenario when I start 3..10 threads with ThreadPool.
Each thread does its job and returns to the ThreadPool.
What are possible options to be notified in main thread when all background threads have finished?
Currently I'm using a homegrown method with incrementing a variable for each of created threads and de... | Decrementing a variable (between threads) is a little bit risky unless done with `Interlocked.Decrement`, but that approach should be fine if you have the last thread (i.e. when it gets to zero) raise an event. Note that it would have to be in a "finally" block to avoid losing it in the case of exceptions (plus you don... | Try this: <https://bitbucket.org/nevdelap/poolguard>
```
using (var poolGuard = new PoolGuard())
{
for (int i = 0; i < ...
{
ThreadPool.QueueUserWorkItem(ChildThread, poolGuard);
}
// Do stuff.
poolGuard.WaitOne();
// Do stuff that required the child threads to have ended.
void ChildTh... | be notified when all background threadpool threads are finished | [
"",
"c#",
"multithreading",
"threadpool",
""
] |
I'm building a questionnaire mvc webapp, and i cant figure out how to pass an unknown number of arguments to the controller from the form.
My form is something like:
```
<% using (Html.BeginForm())
{ %>
<div id="Content">
<% foreach (var group in ViewData.Model.QuestionGroups)
{ %>
<div class="Group... | Garry's answer will work (and hence, up voted). However, you can model bind directly to a list, and I think it's a bit more elegant. [There are instructions in this blog post.](http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx) | You can add an argument to your action like
```
public ActionResult MyAction(FormCollection form)
```
Then the `form` parameter will contain all the data from the posted form. From that you can do what you want.
You could probably implement a binder that could map to ResponseAnswers but I have no experience of doing... | Asp.Net MVC form, with unknown parameters for Controller | [
"",
"c#",
"asp.net-mvc",
""
] |
I've been a fan of EasyMock for many years now, and thanks to SO I came across references to PowerMock and it's ability to mock Constructors and static methods, both of which cause problems when retrofitting tests to a legacy codebase.
Obviously one of the huge benefits of unit testing (and TDD) is the way it leads to... | I think you're right to be concerned. Refactoring legacy code to be testable isn't **that hard** in *most* cases once you've learned how.
Better to go a bit slower and have a supportive environment for learning than take a short cut and learn bad habits.
(And I just [read this](http://www.infoq.com/articles/levison-T... | I have to strongly disagree with this question.
There is no justification for a mocking tool that limits design choices. It's not just static methods that are ruled out by EasyMock, EasyMock Class Extension, jMock, Mockito, and others. These tools also prevent you from declaring classes and methods `final`, and that a... | Using PowerMock or How much do you let your tests affect your design? | [
"",
"java",
"unit-testing",
"dependency-injection",
"junit",
""
] |
I am looking at moving my company's internal business app from VB.NET to PHP. Some of the people were worried about losing GUI features that can be found in .NET. I am under the impression that with the right javascript framework, anything in .NET GUI can be replicated.
While I am still researching this point, I would... | First off: to answer your question.
A Tree Control is hard to emulate in a web environment. Doable, but hard (look at Yahoos YUI for an example).
* **State**: you get it in WinForms, not in the web. This has more to do with how people use the application.
* **Interaction**: That is easier on WinForms than web. Again,... | I will say that yes anything "CAN" be replicated, but the amount of time to do it might be a big bottle neck right away.
I am going to assume that your current application is an ASP.NET application and that you are not moving from WinForms. (If you are the answers are still pretty much the same...but I might add a few... | Javascript RIA vs .NET GUI | [
"",
"javascript",
"vb.net",
""
] |
If an object has a property that is a collection, should the object create the collection object or make a consumer check for null? I know the consumer should not assume, just wondering if most people create the collection object if it is never added to. | You can also use the "Lazy initailizer" pattern where the collection is not initialized until (and unless) someone accesses the property getter for it... This avoids the overhead of creating it in those cases where the parent object is instantiated for some other purpose that does not require the collection...
```
... | This depends on the contract you have between your API and the user.
Personally, I like a contract that makes the Object manage its collections, i.e., instantiating them on creation, and ensuring that they can't be set to null via a setter - possibly by providing methods to manage the collection rather than setting th... | Initialize a collection within an object? | [
"",
"c#",
".net",
"oop",
""
] |
Why are we not able to override an instance variable of a super class in a subclass? | Because if you changed the implementation of a data member it would quite possibly break the superclass (imagine changing a superclass's data member from a float to a String). | He perhaps meant to try and override the value used to **initialize** the variable.
For example,
## Instead of this (which is illegal)
```
public abstract class A {
String help = "**no help defined -- somebody should change that***";
// ...
}
// ...
public class B extends A {
// ILLEGAL
@Override
... | Overriding a super class's instance variables | [
"",
"java",
"inheritance",
""
] |
I've seen a class which is a class which is defined like this..
```
class StringChild : public StringBase
{
public:
//some non-virtual functions
static StringChild* CreateMe(int size);
private:
unsigned char iBuf[1];
};
```
The static factory function has the following implementation..
```
return... | It's an old C trick that was used to work around the non-availablity of variable length arrays in plain C. Yes, it also works in C++ as long as you use suitable allocator constructs (like allocating a bunch of raw memory the desired size and then placement newing the object in there). It's safe as long as you don't wan... | This should be OK for PODs provided iBuf is the last member of the structure. The problems with non-PODs could be that eg. compiler is free to reorder public/private/protected members, virtual base classes end up at the end of the most derived object IIUC, etc.
Your structure is non-POD (it has a base class) so I woul... | Variable sized class - C++ | [
"",
"c++",
"placement-new",
"memory-layout",
""
] |
Here is the situation:
User looks something up.
* Alert sound is played because there is a notice on the item he looked up
* User closes the notice - the application continues to retrieve information
* User is sent a 'ding' telling them the information has finished retrieving
* Application begins sending certain att... | I don't know if there's already a .NET library that would let you do this, but I think you could pretty easily P/Invoke [PlaySound](http://msdn.microsoft.com/en-us/library/ms712879.aspx) from the Windows API and use it to play your sounds. As long as you don't specify the SND\_ASYNC flag, it should block until the soun... | Extending Jon's answer: in .NET 2.0 and above, you can use [My.Computer.Audio.Play](http://msdn.microsoft.com/en-us/library/cf1shcah.aspx) with the [AudioPlayMode.WaitToComplete](http://msdn.microsoft.com/en-us/library/17c3wc6k.aspx) option.
edit: To use this in a C# context, see [How to: Use the My Namespace (C# Prog... | Determining when a sound has finished playing in C# | [
"",
"c#",
".net",
"audio",
""
] |
Is there a C# equivalent method to Java's `Exception.printStackTrace()` or do I have to write something myself, working my way through the InnerExceptions? | Try this:
```
Console.WriteLine(ex.ToString());
```
From <http://msdn.microsoft.com/en-us/library/system.exception.tostring.aspx>:
> The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the resul... | I would like to add: If you want to print the stack outside of an exception, you can use:
```
Console.WriteLine(System.Environment.StackTrace);
``` | C# equivalent to Java's Exception.printStackTrace()? | [
"",
"c#",
".net",
"exception",
"stack-trace",
""
] |
I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.
n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. S... | You actually want a sorted sequence of mins.
```
mins = items[:n]
mins.sort()
for i in items[n:]:
if i < mins[-1]:
mins.append(i)
mins.sort()
mins= mins[:n]
```
This runs *much* faster because you aren't even looking at mins unless it's provably got a value larger than the given item. Abo... | ```
import heapq
nlesser_items = heapq.nsmallest(n, items)
```
Here's a correct version of [S.Lott's algorithm](https://stackoverflow.com/questions/350519/getting-the-lesser-n-elements-of-a-list-in-python#350568):
```
from bisect import insort
from itertools import islice
def nsmallest_slott_bisect(n, iterable, ... | Getting the lesser n elements of a list in Python | [
"",
"python",
"algorithm",
"sorting",
""
] |
We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to `http://mybugtracker/bug1234` | check out the interwiki page in moinmoin, (most wikis have them) we use trac for example and you can set up different link paths to point to your different web resources. So in our Trac you can go [[SSGWiki:Some Topic]] and it will point to another internal wiki. | add to the file `data/intermap.txt` (create if not existing, but that should not happen) a line like
```
wpen http://en.wikipedia.org/wiki/
```
so that you can write `[[wpen:MoinMoin]]` instead of `http://en.wikipedia.org/wiki/MoinMoin`
I also have
```
wpfr http://fr.wikipedia.org/wiki/
wpde http://de.wikipedia.org... | How to use InterWiki links in moinmoin? | [
"",
"python",
"wiki",
"moinmoin",
""
] |
I recently upgraded a Web Application Project (as well as some dependent projects) from .net 2.0 to .net 3.5 using the built in conversion tool. Everything works well such as using MS AJAX 3.5 vs. the external MS AJAX libraries in 2.0.
My problem occurs when I tried using the new Lambda Expression syntax. The compiler... | If any of the page is being compiled by ASP.NET (i.e. you aren't pre-compiling the WAP), then you'll need to ensure that ASP.NET knows about the C# 3.0 (.NET 3.5) compiler. Ensure the following is in the `web.config`:
```
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp"
extension=".c... | I don't have much experience with the VS 2008 conversion tool, but I know other project conversion tools have had "issues". I'd recommend you compare the .csproj file for your 'broken' project to one that is working. Maybe the conversion utility broke something in your project. You could also try creating a new project... | Visual Studio 2008 doesn't recognize Lambda Expression Syntax | [
"",
"c#",
"asp.net",
"visual-studio-2008",
".net-3.5",
"lambda",
""
] |
In a way following on from [reading a windows \*.dmp file](https://stackoverflow.com/questions/158534/reading-a-windows-dmp-file)
Having received a dump file from random customer, running the debug session to see the crash, you often find it is in a MS or other third party library. The next issue is that you may not h... | What are you using to debug the minidump? I.e., WinDBG or Visual Studio? And how was the minidump generated?
There should be enough information in the minidump to resolve system dll symbols correctly. Are you using a local download of symbols or <http://msdl.microsoft.com/>?
Update: You should be able to add the publ... | If you are using WinDbg (part of the [Debugging Tools for Windows](http://www.microsoft.com/whdc/devtools/debugging/default.mspx) package), then it's simple to have it pull the right symbols for you from Microsoft automatically. Configure the symbol path using the ".symfix" (or ".symfix+", to simply append to your exis... | How do you identify (and get access to) modules/debug symbols to use when provided a windows .dmp or .minidmp | [
"",
"c++",
"module",
"symbols",
"dump",
"minidump",
""
] |
How do you do it? Given a byte array:
```
byte[] foo = new byte[4096];
```
How would I get the first x bytes of the array as a separate array? (Specifically, I need it as an `IEnumerable<byte>`)
This is for working with `Socket`s. I figure the easiest way would be array slicing, similar to Perls syntax:
```
@bar = ... | Arrays are enumerable, so your `foo` already is an `IEnumerable<byte>` itself.
Simply use LINQ sequence methods like [`Take()`](https://msdn.microsoft.com/en-us/library/bb503062(v=vs.110).aspx) to get what you want out of it (don't forget to include the `Linq` namespace with `using System.Linq;`):
```
byte[] foo = new... | You could use [`ArraySegment<T>`](http://msdn.microsoft.com/en-us/library/1hsbd92d.aspx). It's very light-weight as it doesn't copy the array:
```
string[] a = { "one", "two", "three", "four", "five" };
var segment = new ArraySegment<string>( a, 1, 2 );
``` | Array slices in C# | [
"",
"c#",
"arrays",
""
] |
I have a DateTime class and wish to display it according to some format... in this case, I specifically want to format it as YYYYMMDD format.
What's the best C#/.NET API function for doing this? | I always use this site to get any dates formats etc.
<http://blog.stevex.net/index.php/string-formatting-in-csharp/> | ToString(format)? i.e.
```
string s = DateTime.Today.ToString("yyyyMMdd");
```
(note the case) | What's the simplest way to format a .NET DateTime according to YYYYMMDD or the like? | [
"",
"c#",
".net",
"datetime",
"formatting",
""
] |
double TotalMinute=300.0
double TotalMinutesAdded=1378.0
```
double TotalMinute=300.0
double TotalMinutesAdded=1378.0
foreach(DataRow dr in ds.Tables[0].Rows)
{
//Add The above Timings to each Row's 2nd Column
DateTime correctDate=Convert.ToDateTime(dr[2]);
... | As mentioned, due to `DateTime` objects being immutable you have to reassign the variable.
However, a point to note is that you can chain the manipulations as so:
```
correctDate = correctDate.AddMinutes(TotalMinute)
.AddMinutes(TotalMinutesAdded);
``` | DateTiem Add\* functions are not supposed to change current DateTime value. They RETURN the new Value.
If you want your value changed, type like this:
```
correctDate = correctDate.AddMinutes(TotalMinute);
``` | Adding Minutes to Date is not changing the Date C# .NET | [
"",
"c#",
"datetime",
""
] |
I have a table, users, in an Oracle 9.2.0.6 database. Two of the fields are varchar - last\_name and first\_name.
When rows are inserted into this table, the first name and last name fields are supposed to be in all upper case, but somehow some values in these two fields are mixed case.
I want to run a query that wil... | How about this:
```
select id, first, last from mytable
where first != upper(first) or last != upper(last);
``` | I think BQ's SQL and Justin's second SQL will work, because in this scenario:
```
first_name last_name
---------- ---------
bob johnson
Bob Johnson
BOB JOHNSON
```
I want my query to return the first 2 rows.
I just want to make sure that this will be an efficie... | Oracle - Select where field has lowercase characters | [
"",
"sql",
"oracle",
"select",
"indexing",
"case-sensitive",
""
] |
With Symfony's Action Security if a user has not been identified he will be forwarded to the default login action as defined in the applications settings.yml file. How would I forward the user to the originally requested action after the user is successfully authenticated? | On first hit to your login action, store referer to the user session:
```
if(!$this->getUser()->hasParameter('referer'))
{
$this->getUser()->setParameter('referer',$this->getRequest()->getReferer());
}
```
and then when login succeeds, redirect user to stored referer with:
```
$this->redirect($this->getUser()->get... | More simply...
```
$this->getUser()->setReferer($this->getRequest()->getReferer());
```
like
```
setReferer($referer)
{
if (!$this->hasAttribute('referer'))
$this->setAttribute('referer', $referer);
}
``` | Symfony Action Security - How to forward after successful authentication? | [
"",
"php",
"security",
"symfony1",
"action",
""
] |
I have two tables in a DataSet where the ID field on each is the same. I have a Relation between the two tables. How do I, in C# code, pull the info from Table2 that relates to the info on Table1?
I have tried using a new DataRow and assigning it by using GetChildRow, but for some reason I cannot seem to make it work.... | The answer is different (and significantly easier) if your DataSet is strongly-typed (i.e. generated from a .xsd file). I'll assume that's not the case below, but if it is speak up.
For generic DataSet objects, the answer largely depends on what you have hold of to start. If you have simply an ID, then it's probably s... | In a strongly-typed DataSet, each DataRow object will have specific methods or properties for each relationship. If you have a parent DataRow and want to navigate to children in Table2, it will be a pluralized method (i.e. "row.GetTable2Rows()"). If you have a child and want to navigate to the parent, it will be a sing... | Get Table2 data from a relation to Table1 in C# Code | [
"",
"c#",
"dataset",
"relation",
""
] |
I am really trying to show what htmlentities gives me, but it doesn't give & euro; for the € character.
I am trying
```
echo htmlentities(htmlentities("LISBOA-VIENA DESDE 99€ TAXAS INCLUÍDAS, RESERVE JÁ",ENT_COMPAT,ISO-8859-1),ENT_COMPAT,ISO-8859-1);
echo '<br>';
echo htmlentities(htmlentities("LISBOA-VIENA D... | This is discussed [here](http://www.cs.tut.fi/~jkorpela/html/euro.html); it seems € (`€`) works often. | What is the original file encoding of the file in which you use these statements?
If you're on Windows chances are high that the file is encoded with [Windows-1252](http://en.wikipedia.org/wiki/Windows-1252) (CP1252) and not in [ISO-8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1), [ISO-8859-2](http://en.wikipedia... | Getting the € with htmlentities | [
"",
"php",
"character-encoding",
"html-entities",
""
] |
```
ClassA* pa = NULL;
ClassA* pb = NULL;
void assignObject(ClassA* pa, ClassB* pb)
{
pa = new ClassA;
pb = new ClassB;
}
```
What will be the value of `pa` and `pb` after executing the function?
EDIT
how to pass as pointer is the return if pa,pb is NULL | As pointed out in other answers - both will still be NULL after the call. However, there are two possible solutions to this problem:
1) **references**
```
void assignObject(ClassA*& pa, ClassB*& pb)
{
pa = new ClassA;
pb = new ClassB;
}
ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(pa, pb); // both will... | They will be NULL, since you're passing them by value. If you want to pass it by reference, you'd do this:
```
ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(ClassA*& pa, ClassB*& pb)
{
pa = new ClassA;
pb = new ClassB;
}
```
Note, I'm not sure what you're trying to accomplish with the global variables. T... | Assignment inside function that is passed as pointer? | [
"",
"c++",
"function",
"pointers",
"parameters",
""
] |
Is there any difference in the performance of the following three SQL statements?
```
SELECT * FROM tableA WHERE EXISTS (SELECT * FROM tableB WHERE tableA.x = tableB.y)
SELECT * FROM tableA WHERE EXISTS (SELECT y FROM tableB WHERE tableA.x = tableB.y)
SELECT * FROM tableA WHERE EXISTS (SELECT 1 FROM tableB WHERE tab... | The truth about the EXISTS clause is that the SELECT clause is not evaluated in an EXISTS clause - you could try:
```
SELECT *
FROM tableA
WHERE EXISTS (SELECT 1/0
FROM tableB
WHERE tableA.x = tableB.y)
```
...and should expect a divide by zero error, but you won't because it's... | Definitely #1. It "looks" scary, but realize the optimizer will do the right thing and is expressive of intent. Also ther is a slight typo bonus should one accidently think EXISTS but type IN. #2 is acceptable but not expressive. The third option stinks in my not so humble opinion. It's too close to saying "if 'no valu... | Performance of SQL "EXISTS" usage variants | [
"",
"sql",
"sql-execution-plan",
""
] |
I am trying to play the Asterisk system sound from a C# program with
```
System.Media.SystemSounds.Asterisk.Play();
```
but no sound plays. My system does have a sound set up for Asterisk and other programs (not written by me) cause various system sounds to play.
Can anyone suggest any possible reasons for this? | I had ignored this problem until today. Some googling revealed that this is quite a common problem and totally unrelated to the .NET Play calls.
What happens is that while you can play/preview the sounds from the Control Panel Sounds and Audio Devices applet they do not play when programs trigger the sounds. It seems ... | Sorry if this is overstating the obvious...
1. Are you sure this line of code is being executed?
2. As RobS suggests do any of the other SystemSounds play?
I had a look in reflector. Whichever of the SystemSounds you call returns a SystemSound instance initialised with the type (e.g. 0x40 for Asterix) for the system ... | SystemSounds Play not working | [
"",
"c#",
"audio",
""
] |
Is there a canonical or recommended pattern for implementing arithmetic operator overloading in C++ number-like classes?
From the C++ FAQ, we have an exception-safe assignment operator that avoids most problems:
```
class NumberImpl;
class Number {
NumberImpl *Impl;
...
};
Number& Number::operator=(const Num... | In Bjarne Stroustrup's book "[The C++ Programming Language](https://rads.stackoverflow.com/amzn/click/com/0201700735)", in chapter 11 (the one devoted to Operator Overloading) he goes through witting a class for a complex number type (section 11.3).
One thing I do notice from that section is that he implements mixed t... | The big thing to consider when writing any operator is that member operators do not undergo conversions on the left parameter:
```
struct example {
example(int);
example operator + (example);
};
void foo() {
example e(3), f(6);
e + 4; // okay: right operand is implicitly converted to example
e + f; // okay:... | Canonical operator overloading? | [
"",
"c++",
"operator-overloading",
""
] |
I am working on an application where i need to transfer mails from a mailbox to anoter one.I can not send these mails using smtp because this willchange the header information .I am using C# and out look api to process mails . is thre any way i can transfer mails to other mail box without changing mail header.
---
By... | If you cannot load all relevant mailboxes into a single Outlook profile, then this cannot be solved using the Outlook API. It should however be possible to run a standalone application from an administrative account that accesses the Exchange information store directly via Extended MAPI. You can then open the source ma... | I was able to move the mails from one mail box to another using Redemption. This is like a copy mail from one mail box to another. First logon to the destination mail box using redemption.
Get the reference to the folder where you want to move the mail . In my case , it was inbox. now convert the outlook mail item to R... | Transfer mail to other mail box | [
"",
"c#",
"outlook",
"exchange-server",
"mapi",
""
] |
In our project I have several [JUnit](http://www.junit.org/) tests that e.g. take every file from a directory and run a test on it. If I implement a `testEveryFileInDirectory` method in the `TestCase` this shows up as only one test that may fail or succeed. But I am interested in the results on each individual file. Ho... | Take a look at **Parameterized Tests** in JUnit 4.
Actually I did this a few days ago. I'll try to explain ...
First build your test class normally, as you where just testing with one input file.
Decorate your class with:
```
@RunWith(Parameterized.class)
```
Build one constructor that takes the input that will cha... | **JUnit 3**
```
public class XTest extends TestCase {
public File file;
public XTest(File file) {
super(file.toString());
this.file = file;
}
public void testX() {
fail("Failed: " + file);
}
}
public class XTestSuite extends TestSuite {
public static Test suite() {... | JUnit test with dynamic number of tests | [
"",
"java",
"unit-testing",
"junit",
"parameterized-unit-test",
""
] |
I have a method that I'm writing that is calling another overloaded method inside it. I'd like to only write one outer method, since the parameter to the outer method is being passed to the inner one. Is there a way to do this?
I tried using generics, but I don't know enough about this so it isn't working:
```
public... | You can do this in C++ but not in C# (unless the inner method can also be generic instead of overloaded).
---
Alternatively (if you won't take 'no' for an answer), you can do a run-time switch on type, like for example ...
```
public void OuterMethod(object parameter)
{
if (parameter is int)
InnerMethod(... | Like the others said, you can't really do what you are trying to do and the option you stated in your question is the best bet.
You would actually have to convert the value if you use the generic. Otherwise you can downcast by accepting an Object as ChrisW suggests.
```
public void OuterMethod<T>(T parameter)
... | Overloaded method calling overloaded method | [
"",
"c#",
".net",
"overloading",
""
] |
In Java, the idiomatic way to declare critical sections in the code is the following:
```
private void doSomething() {
// thread-safe code
synchronized(this) {
// thread-unsafe code
}
// thread-safe code
}
```
Almost all blocks synchronize on `this`, but is there a particular reason for this? Are there ot... | First, note that the following code snippets are identical.
```
public void foo() {
synchronized (this) {
// do something thread-safe
}
}
```
and:
```
public synchronized void foo() {
// do something thread-safe
}
```
do **exactly the same thing**. No preference for either one of them except for... | As earlier answerers have noted, it is best practice to synchronize on an object of limited scope (in other words, pick the most restrictive scope you can get away with, and use that.) In particular, synchronizing on `this` is a bad idea, unless you intend to allow the users of your class to gain the lock.
A particula... | In Java critical sections, what should I synchronize on? | [
"",
"java",
"multithreading",
"synchronized",
""
] |
If I am to follow [What should a developer know *before* building a public web site?](https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site) on authentication, then what options do I have ?
I have never used PEAR, and I'm not about to start. I have read about [phpGALC... | > *I'm not a big fan of using a single tinyint value which desides what a
> user can and cannot do, besides its
> not very flexible.*
That depends... Are you referring to using the value as an integer or as a bitfield?
If you're using it simply as a number (level 5 user has all the abilities of level 1-4 users, plus ... | ACL and Auth are the things I'm working on at this very moment. I'm using [CakePHP](http://cakephp.org) at the moment, and it provides an extensive (albeit not simple) module for ACL, and a simple way to do authentication. I'm interested in answers too.
What I've gathered:
* Learn to validate input, especially the di... | User authentication | [
"",
"php",
"authentication",
"acl",
""
] |
I understand that the WITH RECOMPILE option forces the optimizer to rebuild the query plan for stored procs but when would you want that to happen?
What are some rules of thumb on when to use the WITH RECOMPILE option and when not to?
What's the effective overhead associated with just putting it on every sproc? | As others have said, you don't want to simply include `WITH RECOMPILE` in every stored proc as a matter of habit. By doing so, you'd be eliminating one of the primary benefits of stored procedures: the fact that it saves the query plan.
Why is that potentially a big deal? Computing a query plan is a lot more intensive... | Putting it on every stored procedure is NOT a good idea, because compiling a query plan is a relatively expensive operation and you will not see any benefit from the query plans being cached and re-used.
The case of a dynamic where clause built up inside a stored procedure can be handled using `sp_executesql` to execu... | Rule of thumb on when to use WITH RECOMPILE option | [
"",
"sql",
"sql-server",
""
] |
I have a problem with my web module classpath in Websphere v6.1.
In my WEB-INF/lib I have a largish number of jar files which include xercesImpl.jar and xmlparserv2.jar. I need both jars to be present, but they appear to confict with each other. Specifically, each jar contains a META-INF/services directory so, when we... | I assume by WebSphere, you mean the regular J2EE Application Server (and not something like Community Edition; WebSphere is a brand name applied to a number of IBM products).
I think your options are limited. Since the dependencies look quite explicit, I would prefer a programmatic approach rather than relying on the ... | In IBM Websphere Application Server 6.1, web modules have their own class loaders that are usually used in the PARENT\_FIRST mode. This means that the web module class loaders attempt to delegate class loading to the parent class loaders, before loading any new classes.
If you wish to have the Xerces classes loaded be... | How do I manage the ClassPath in WebSphere | [
"",
"java",
"websphere",
""
] |
This is the ability to run your application on a cluster of servers with the intent to distribute the load and also provide additional redundancy.
I've seen a presentation for [GridGain](http://www.gridgain.com/) and I was very impressed with it.
Know of any others? | There are several:
* [Terracotta](http://www.terracotta.org/) ([open source, based on Mozilla Public License](http://www.terracotta.org/confluence/display/wiki/FAQ#FAQ-Q%3AWhat%27syourlicense%3F));
* [Oracle Coherence](http://www.oracle.com/technology/products/coherence/index.html) (formerly Tangosol Coherence; commer... | You may want to check out Hazelcast also. [Hazelcast](http://www.hazelcast.com) is an open source transactional, distributed/partitioned implementation of queue, topic, map, set, list, lock and executor service. It is super easy to work with; just add hazelcast.jar into your classpath and start coding. Almost no config... | What is the best library for Java to grid/cluster-enable your application? | [
"",
"java",
"grid",
"load-balancing",
"gridgain",
""
] |
Is there a way in JPA to map a collection of Enums within the Entity class? Or the only solution is to wrap Enum with another domain class and use it to map the collection?
```
@Entity
public class Person {
public enum InterestsEnum {Books, Sport, etc... }
//@???
Collection<InterestsEnum> interests;
}
```... | using Hibernate you can do
```
@ElementCollection(targetElement = InterestsEnum.class)
@JoinTable(name = "tblInterests", joinColumns = @JoinColumn(name = "personID"))
@Column(name = "interest", nullable = false)
@Enumerated(EnumType.STRING)
Collection<InterestsEnum> interests;
``` | The link in Andy's answer is a great starting point for mapping collections of "non-Entity" objects in JPA 2, but isn't quite complete when it comes to mapping enums. Here is what I came up with instead.
```
@Entity
public class Person {
@ElementCollection(targetClass=InterestsEnum.class)
@Enumerated(EnumType.... | JPA map collection of Enums | [
"",
"java",
"jpa",
"jakarta-ee",
""
] |
I need to define new UI Elements as well as data binding in code because they will be implemented after run-time. Here is a simplified version of what I am trying to do.
Data Model:
```
public class AddressBook : INotifyPropertyChanged
{
private int _houseNumber;
public int HouseNumber
{
get { ret... | The root of it was that the string I passed to PropertyChangedEventArgs did not EXACTLY match the name of the property. I had something like this:
```
public int HouseNumber
{
get { return _houseNumber; }
set { _houseNumber = value; NotifyPropertyChanged("HouseNum"); }
}
```
Where it should be this:
```
publ... | Make sure you're updating the `AddressBook` reference that was used in the binding, and not some other `AddressBook` reference.
I got the following to work with the AddressBook code you gave.
```
<StackPanel>
<Button Click="Button_Click">Random</Button>
<Grid x:Name="myGrid">
</Grid>
</StackPanel>
```
Co... | Problem with WPF Data Binding Defined in Code Not Updating UI Elements | [
"",
"c#",
"wpf",
"data-binding",
"inotifypropertychanged",
""
] |
Is it possible to get access to the spell checker that is incorporated in browsers for text areas from Javascript? I would like to be able to control spell checking from withing my code. Most browsers (apart from IE) seem to have some kind of a spell checker built in to them nowadays. | The most access that I know of is disabling or enabling spellchecking on a field: [Inline Disabling of Firefox Spellcheck?](https://stackoverflow.com/questions/223940/inline-disabling-of-firefox-spellcheck)
I don't know of a way that you can directly access the spellchecker of a browser via javascript. If you aren't p... | Browser's don't provide access to their built-in, proprietary spell checker APIs. I'm quite certain there's no x-plat way to do this, let alone a way to do it individually for each browser.
Best bet is to check with each browser vendor and see if they provide any javascript hooking of their spell checker.
I think the... | Javascript access to spell checker on browsers | [
"",
"javascript",
""
] |
I am looking to extend jQuery so I can easily retrieve the tagName of the first element in a jQuery object. This is what I have come up with, but it doesn't seem to work:
```
$.fn.tagName = function() {
return this.each(function() {
return this.tagName;
});
}
alert($('#testElement').tagName());
```
An... | Try this instead:
```
$.fn.tagName = function() {
return this.get(0).tagName;
}
alert($('#testElement').tagName());
```
To explain a little bit more of why your original example didn't work, the `each()` method will always return the original jQuery object (unless the jQuery object itself was modified). To see wh... | Why create a plugin at all? Seems a bit unnecessary...
```
alert( $('div')[0].tagName );
``` | How to extend jQuery to make it easier to retrieve the tagName | [
"",
"javascript",
"jquery",
""
] |
I'm trying to write a query for an advanced search page on my document archiving system. I'm attempting to search by multiple optional parameters. I have about 5 parameters that could be empty strings or search strings. I know I shouldn't have to check for each as a string or empty and create a separate stored procedur... | You could use COALESCE (or ISNULL) like so:
```
WHERE COALESCE(@var1, col1) = col1
AND COALESCE(@var2, col2) = col2
AND COALESCE(@var3, col3) = col3
``` | I usually do this :P
```
WHERE (@var1 IS NULL OR col1 = @var1)
AND (@var2 IS NULL OR col2 = @var2)
```
... | sql search query for multiple optional parameters | [
"",
"jquery",
"sql",
"sql-server",
"search",
"stored-procedures",
""
] |
How do you add a new variable to be inserted into a Java code template. How do I add a variable to the list in Window->Preferences->Java->Code Style->Code Templates->Code->New Java Files->Edit->Insert Variable... ?
Currently my new files get created with:
```
${filecomment}
${package_declaration}
${typecomment}
${typ... | I'm pretty sure that the list of "variables" is generated by Eclipse and there is no way to add a new template variable.
What do you want `${begin_filecomment}` and `${end_filecomment}` to be? Just type the content into the Edit box - there is nothing that says you cannot put static content in there. | Yes, you can indeed add a variable to this list. See the extension point called
org.eclipse.ui.editors.templates
and you'll find out how. | Eclipse Custom Variable for Java Code Templates | [
"",
"java",
"eclipse",
"templates",
""
] |
I have a database with 2 tables.
One of the tables holds a row containing numbers, from 0 to 10.
In PHP, I do this:
```
$query = "SELECT ".$param." FROM issues WHERE ".$param." >=0";
$result = @mysql_query($query) or showError("query failed");
if (!($record = mysql_fetch_array($result))) return null;
return $record;... | I'm not exactly sure what you are trying to achieve here, but I think what you want is:
```
// query...
$records = array();
while($r = mysql_fetch_array($result)) {
$records[] = $r;
}
return $records;
``` | You want to get all the results in one call. With your method you have to loop the results like Paolo showed you. But it might be better to use PDO with [fetchAll](http://no.php.net/manual/en/pdostatement.fetchall.php). If you are learning PHP database connections, learn [PDO](http://no.php.net/manual/en/intro.pdo.php)... | Trouble with PHP MySQL fetch array function | [
"",
"php",
"mysql",
""
] |
I'm writing a semi-generic form plugin using jQuery in order to speed up the development of the project I'm working on.
The plan is that a [jTemplates](http://jtemplates.tpython.com/) template contains the fields, my plugin looks through the template to find any required multi-lingual resources, requests them from the... | Set the `autocomplete` attribute in your text fields to `off`:
```
opts.coreElement.find('input[type=text]').each(function() {
$(this).attr('autocomplete', 'off');
});
```
This works for all the major browsers (Safari, Firefox, IE). | I have found that in order to prevent the default action for an [enter] or [tab] key event you have to listen for the keydown event and handle/cancel it.
By the time keyup or keypress is triggered the default for keydown has already happened. | JavaScript detection of keypress context (form history selection vs. form submit) | [
"",
"javascript",
"keypress",
"input-history",
""
] |
I'm trying to use the CRT memory leak detection but I keep getting the following message in Microsoft Visual Studio: "Detected memory leaks - skipping object dump." I can never get the it to actually do and object dump.
I followed the directions in the Microsoft article on Memory Leak Detection (<http://msdn.microsoft... | I don't have it here on my machine, but when you instal MSVC you have the option of installing (most of the) source code for the C run-time library (i.e. for MSVCRTxx.xxx). If you look in that source code for "skipping object dump" then you might be able to work out why the object dump is being skipped. | I just used [Visual Leak Detector](http://vld.codeplex.com/) after getting a large dump of leaked objects with no filenames/line numbers using the \_CrtDumpMemoryLeaks approach. VLD worked as advertised (it's free) and I'm pretty happy with that. | Visual Studio _CrtDumpMemoryLeaks always skipping object dump | [
"",
"c++",
"visual-studio",
"memory-leaks",
"msvcrt",
"crtdbg.h",
""
] |
I'm trying to format numbers. Examples:
```
1 => 1
12 => 12
123 => 123
1234 => 1,234
12345 => 12,345
```
It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.
Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model. | Django's contributed [humanize](http://docs.djangoproject.com/en/dev/ref/contrib/humanize/#ref-contrib-humanize) application does this:
```
{% load humanize %}
{{ my_num|intcomma }}
```
Be sure to add `'django.contrib.humanize'` to your `INSTALLED_APPS` list in the `settings.py` file. | Building on other answers, to extend this to floats, you can do:
```
{% load humanize %}
{{ floatvalue|floatformat:2|intcomma }}
```
Documentation: [`floatformat`](https://docs.djangoproject.com/en/stable/ref/templates/builtins/#floatformat), [`intcomma`](https://docs.djangoproject.com/en/stable/ref/contrib/humanize/... | Format numbers in django templates | [
"",
"python",
"django",
""
] |
Building on what has been written in SO question [Best Singleton Implementation In Java](https://stackoverflow.com/questions/70689/best-singleton-implementation-in-java) - namely about using an enum to create a singleton - what are the differences/pros/cons between (constructor omitted)
```
public enum Elvis {
INS... | Suppose you're binding to something which will use the properties of any object it's given - you can pass Elvis.INSTANCE very easily, but you can't pass Elvis.class and expect it to find the property (unless it's deliberately coded to find static properties of classes).
Basically you only use the singleton pattern whe... | A great advantage is when your singleton must implements an interface. Following your example:
```
public enum Elvis implements HasAge {
INSTANCE;
private int age;
@Override
public int getAge() {
return age;
}
}
```
With:
```
public interface HasAge {
public int getAge();
}
```
It c... | What is the best approach for using an Enum as a singleton in Java? | [
"",
"java",
"singleton",
""
] |
More specifically, I'm trying to check if given string (a sentence) is in Turkish.
I can check if the string has Turkish characters such as Ç, Ş, Ü, Ö, Ğ etc. However that's not very reliable as those might be converted to C, S, U, O, G before I receive the string.
Another method is to have the 100 most used words in... | One option would be to use a Bayesian Classifier such as [Reverend](http://www.divmod.org/trac/wiki/DivmodReverend). The Reverend homepage gives this suggestion for a naive language detector:
```
from reverend.thomas import Bayes
guesser = Bayes()
guesser.train('french', 'le la les du un une je il elle de en')
guesser... | A simple statistical method that I've used before:
Get a decent amount of sample training text in the language you want to detect. Split it up into trigrams, e.g.
"Hello foobar" in trigrams is:
'Hel', 'ell', 'llo', 'lo ', 'o f', ' fo', 'foo', 'oob', 'oba', 'bar'
For all of the source data, count up the frequency of ... | Best way to return the language of a given string | [
"",
"python",
"algorithm",
"string",
""
] |
Let me describe the problem in details:
I want to show an absolute positioned div when hovering over an element. That's really simple with jQuery and works just fine. But when the mouse goes over one of the child elements, it triggers the mouseout event of the containing div. How do I keep javascript from triggering t... | The question is a bit old, but I ran into this the other day.
The simplest way to do this with recent versions of jQuery is to use the `mouseenter` and `mouseleave` events rather than `mouseover` and `mouseout`.
You can test the behavior quickly with:
```
$(".myClass").on( {
'mouseenter':function() { console.log(... | For simplicity sake, I would just reorganize the html a bit to put the newly displayed content inside the element that the mouseover event is bound to:
```
<div id="hoverable">
<a>Hover Me</a>
<div style="display:none;">
<input>Test</input>
<select>
<option>Option 1</option>
<option>Option 2</o... | How to disable mouseout events triggered by child elements? | [
"",
"javascript",
"jquery",
"events",
""
] |
This is a fundamental question, but an important one none the less...
**When starting a C++ program whose main method has the following common signature:**
```
int main(int argc, char* args[]) {
//Magic!
return 0;
}
```
**is args[0] always guaranteed to be the path to the currently running program? What abou... | It is not always. It's the value that you gave the program by the Operation System. For example when starting a program using `exec` you can set that to an arbitrary value:
```
int execve(const char *filename, char *const argv[],
char *const envp[]);
```
The first parameter is the file to start, and argv w... | No. On Windows GetModuleFileName gurantees the exact full path to the current executing program. On linux there is a symlink /proc/self/exe. Do a readlink on this symlink to get the full path of the currently executing program. Even if youprogram was called thorugh a symlink /proc/self/exe will always point to the actu... | Is args[0] guaranteed to be the path of execution? | [
"",
"c++",
"argv",
""
] |
When writing plugins for media center your plugin is hosted in `ehexthost.exe` this exe gets launched from `ehshell.exe` and you have no way of launching it directly, instead you pass a special param to `ehshell.exe` which will launch the plugin in a separate process.
When we are debugging [media browser](http://code.... | I would use a macro. I've redefined my F5 function to attach to the asp.net process instead of the long build/validate it usually performs. This works pretty well for me and it's really easy.
```
For Each process In DTE.Debugger.LocalProcesses
If (process.Name.IndexOf("aspnet_wp.exe") <> -1) Then
... | For VS2012, macros have been dropped, but you can still do it quite quickly with standard keyboard shortcuts. For instance, to attach to iisexpress.exe:
`Ctrl` + `Alt` + `p` - brings up the Attach To Process dialog
`i` - jumps to the the first process beginning with i in the list (for me this is iisexpress.exe)
`Ent... | Attaching to a child process automatically in Visual Studio during Debugging | [
"",
"c#",
".net",
"visual-studio",
"debugging",
"visual-studio-debugging",
""
] |
I am trying to write a static function to Or two expressions, but recieve the following error:
> The parameter 'item' is not in scope.
>
> Description: An unhandled exception
> occurred during the execution of the
> current web request. Please review the
> stack trace for more information about
> the error and where i... | The issue is that the Expression you're creating in the method OrExpressions reuses the body of the two expressions. Those bodies will contain references to their own ParameterExpression that has been defined in FilterExpression.
A fix would be to rewrite the left and right parts to use the new ParameterExpression. Or... | As already suggested, [here](http://www.albahari.com/nutshell/predicatebuilder.aspx) you can find this very nice (working) code
```
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast... | Expression.Or, The parameter 'item' is not in scope | [
"",
"c#",
"linq",
"expression-trees",
"expression",
""
] |
I'm writing a web app (Java) which allows users to select contacts. The contacts details can be downloaded (currently in CSV format) and used to perform a mail merge in Word 2007.
I would like to use a format which is a bit more 'robust' than CSV. Those of you in non-English areas will know the comma/semicolon problem... | I prefer TSV (Tab Separated Values) for this sort of task. I have never encountered a dataset containing literal tabs that were desired in the output. | Not having much experience in "non-English" mail merges, what's wrong with exporting the contacts in xlsx format and using that as your datasource? | What is the best format to use when creating a mail list for use in a Word 2007? | [
"",
"java",
"ms-word",
"office-2007",
"mailmerge",
""
] |
I am looking for a C/C++ library to convert HTML (Actually XHTML + CSS) documents to PDF.
It is for commercial use and source would be nice but not essential.
Anybody have any recommendations or experience doing this?
UPDATE: To clarify, I am targeting the Windows platform only. I am developing with Borland C++ Buil... | Just to bump this, I have evaluated both [VisPDF](http://www.vispdf.com/) and [PDFDoc Scout](http://bytescout.com/pdfdocscout.html) and will probably go with PDFDoc Scout as it can format HTML input.
Thanks for everybody else's input. | To do that I have successfully used wkhtmltopdf.
Uses webkit and can be called from command line or as a static library. It's great and simply to use.
[wkhtmltopdf website](http://wkhtmltopdf.org/)
OpensSource (LGPL) and free!
Hope it can help | C++ Library to Convert HTML to PDF? | [
"",
"c++",
"html",
"pdf",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.