Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
When I use quick documentaion lookup (Ctrl+Q) on j2ee classes or annotations in IDEA I only get an empty javadoc. It only contains the basics like class name.
How do I add the javadoc to the libs IDEA provides itself? | You can attach javadoc to any library you have configure in your module or project. Just access the project structure windows `(File -> Project Structure)`, then select "modules" and select the module that has the dependency you want to configure.
Then select the "Dependencies" tab, select the dependency that's missin... | If using maven:
"right click on your pom.xml" -> "Maven" -> then choose "Download Sources and Documentation"
To avoid this in the future: "Preferences" -> "Build, Execution, Deployment" -> "Build Tools" -> "Maven" -> "Importing" -> Check the Automatically download Sources and Documentation boxes.
Credit to Yacov Sch... | Attaching additional javadoc in Intellij IDEA | [
"",
"java",
"intellij-idea",
"javadoc",
""
] |
There are so many Linux distributions to choose from! What is the "best" linux flavor for a web hosting environment running primarily:
Apache HTTP, Tomcat or JBoss, MySQL and Alfresco (not necessarily all in the same instance).
Are there any significant differences in terms of ease of administration and configuration,... | They all use similar tools to administer things like webmin, and sshd.
What are you more familiar with. Red Hat based systems(fedora, mandriva) or Debian based systems(Ubuntu). This family divide will determine a few things. First rpm packaging vs deb packaging.
You also want to look at the level of activity of the p... | You also might want to consider [OpenSolaris](http://opensolaris.org/), as it is from the same company which developed Java in the first place and I've heard rumours, that it supports threading better than Linux does and in Java threads are quite important.
Update: Since Oracle changed the distribution model of OpenSo... | Which distro of Linux is best suited for Java web apps? | [
"",
"java",
"mysql",
"linux",
"hosting",
"alfresco",
""
] |
Since the release of Adobe AIR I am wondering why Java Web Start has not gained more attention in the past as to me it seems to be very similar, but web start is available for a much longer time.
Is it mainly because of bad marketing from Sun, or are there more technical concerns other than the need of having the righ... | In my company we used Java Web Start to deploy Eclipse RCP applications. It was a pain to setup, but it works very well once in place. So the only recommendation I could make is to start small, to get the hang of it. Deploying one simple application first. Trying to deploy a complete product that is already made withou... | I work in the intranet of a Bank since 5 years, and my departament has developed and distributed a LOT of Java Web Start Applications which are used all arround the world, i think Java Web Start has the best of the Desktop applications (easy development, rich user interface, processing power in the client machine) and ... | Objections against Java Webstart? | [
"",
"java",
"java-web-start",
""
] |
Does someone have experience with storing key-value pairs in a database?
I've been using this type of table:
```
CREATE TABLE key_value_pairs (
itemid varchar(32) NOT NULL,
itemkey varchar(32) NOT NULL,
itemvalue varchar(32) NOT NULL,
CONSTRAINT ct_primarykey PRIMARY KEY(itemi... | Before you continue on your approach, I would humbly suggest you step back and consider if you really want to store this data in a "Key-Value Pair"table. I don't know your application but my experience has shown that every time I have done what you are doing, later on I wish I had created a color table, a fabric table ... | In most cases that you would use the first method, it's because you haven't really sat down and thought out your model. "Well, we don't know what the keys will be yet". Generally, this is pretty poor design. It's going to be slower than actually having your keys as columns, which they should be.
I'd also question why ... | Key value pairs in relational database | [
"",
"sql",
"database",
""
] |
For the following HTML:
```
<form name="myForm">
<label>One<input name="area" type="radio" value="S" /></label>
<label>Two<input name="area" type="radio" value="R" /></label>
<label>Three<input name="area" type="radio" value="O" /></label>
<label>Four<input name="area" type="radio" value="U" /><... | ```
$( function() {
$("input:radio")
.click(radioClicks)
.filter("[value='S']")
.attr("checked", "checked");
});
``` | ```
$(document).ready(function(){
$("input[name='area']").bind("click", radioClicks);
});
functionradioClicks() {
alert($(this).val());
}
```
I like to use `bind()` instead of directly wiring the event handler because you can pass additional data to the event hander (not shown here but the data is a third bin... | Using jQuery, what is the best way to set onClick event listeners for radio buttons? | [
"",
"javascript",
"jquery",
""
] |
I'm having a little problem and I don't see why, it's easy to go around it, but still I want to understand.
I have the following class :
```
public class AccountStatement : IAccountStatement
{
public IList<IAccountStatementCharge> StatementCharges { get; set; }
public AccountStatement()
{
new Ac... | This code:
```
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
```
is undoubtedly not what you wanted. That makes a second instance of AccountStatement and does nothing with it.
I think what you meant was this instead:
```
public AccountStatemen... | Use
```
public AccountStatement() : this(new Period(new NullDate().DateTime,newNullDate().DateTime), 0) { }
```
insetad of
```
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
``` | C# 3.0 - Object initializer | [
"",
"c#",
".net-3.5",
""
] |
In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar) | ```
Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)
```
To run this on a column, replace GetDate() with your column name.
The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates th... | ```
SELECT DATEADD(mm, DATEDIFF(mm, 0, @date), 0)
``` | Simplest way to create a date that is the first day of the month, given another date | [
"",
"sql",
"sql-server",
"datetime",
"date",
""
] |
I am using jProfiler to find memory leaks in a Java swing application. I have identified instances of a JFrame which keeps growing in count.
This frame is opened, and then closed.
Using jProfiler, and viewing the Paths to GC Root there is only one reference, 'JNI Global reference'.
What does this mean? Why is it han... | Wikipedia has a good overview of [Java Native Interface](http://en.wikipedia.org/wiki/Java_Native_Interface), essentially it allows communication between Java and native operating system libraries writen in other languages.
JNI global references are prone to memory leaks, as they are not automatically garbage collecte... | A JNI global reference is a reference from "native" code to a Java object managed by the Java garbage collector. Its purpose is to prevent collection of an object that is still in use by native code, but doesn't appear to have any live references in the Java code.
A JFrame is a `java.awt.Window`, and is associated wit... | What is 'JNI Global reference' | [
"",
"java",
"swing",
"jprofiler",
""
] |
To my amazement I just discovered that the C99 stdint.h is missing from MS Visual Studio 2003 upwards. I'm sure they have their reasons, but does anyone know where I can download a copy? Without this header I have no definitions for useful types such as uint32\_t, etc. | Turns out you can download a MS version of this header from:
<https://github.com/mattn/gntp-send/blob/master/include/msinttypes/stdint.h>
A portable one can be found here:
<http://www.azillionmonkeys.com/qed/pstdint.h>
Thanks to the [Software Rambling](http://stephendoyle.blogspot.com/2008/03/c-tr1-stdinth-still-mi... | Just define them yourself.
```
#ifdef _MSC_VER
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
``` | C99 stdint.h header and MS Visual Studio | [
"",
"c++",
"c",
"visual-studio",
"c99",
""
] |
After I [messed up the description of my previous post](https://stackoverflow.com/questions/121922/automatic-casts) on this I have sat down and tried to convey my exact intent.
I have a class called P which performs some distinct purpose. I also have PW which perform some distinct purpose on P. PW has no member variab... | You could try overriding operator\* and operator-> to return access to the embedded p.
Something like this might do the trick :
```
class P
{
public:
void a( ) { std::cout << "a" << std::endl; }
};
class PW
{
public:
PW(P& p) : p(p) { }
void b( ) { std::cout << "b" << std::endl; }
P & operator*(... | If you make P a superclass to PW, like you did in your previous question, you could call p->a() and it would direct to class P. It seems like you've already considered and rejected this though, judging from this question. If so, would you care to elaborate why this wont work for you? | Automatic Casts redux | [
"",
"c++",
"casting",
""
] |
I couldn't find any useful information on Microsoft's site, so here is the question: has the compiler in Visual C++ 2008 been improved significantly since the 2005 version? I'm especially looking for better optimization. | Straight from the horses mouth....
> <http://msdn.microsoft.com/en-us/library/bb384632.aspx> | [Somasegar](http://blogs.msdn.com/somasegar) has some notes in this [blog post](http://blogs.msdn.com/somasegar/archive/2007/09/27/vs-2008-performance-improvements.aspx).
Mainly about [incremental build improvements](http://blogs.msdn.com/vcblog/archive/2007/03/02/managed-incremental-build.aspx) and [multi core improve... | Difference between Visual C++ 2008 and 2005 | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"visual-studio-2005",
"compiler-construction",
""
] |
I am hosting [SpiderMonkey](http://developer.mozilla.org/En/SpiderMonkey/JSAPI_Reference) in a current project and would like to have template functions generate some of the simple property get/set methods, eg:
```
template <typename TClassImpl, int32 TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, J... | Pretty sure VC++ has "issues" here. Comeau and g++ 4.2 are both happy with the following program:
```
struct X
{
int i;
void* p;
};
template<int X::*P>
void foo(X* t)
{
t->*P = 0;
}
template<void* X::*P>
void foo(X* t)
{
t->*P = 0;
}
int main()
{
X x;
foo<&X::i>(&x);
foo<&X::p>(&x);
}
``... | Try changing the JSObject \* to another pointer type to see if that reproduces the error. Is JSObject defined at the point of use? Also, maybe JSObject\* needs to be in parens. | Are C++ non-type parameters to (function) templates ordered? | [
"",
"c++",
"templates",
"overloading",
""
] |
I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?
If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting [Unicode](http://en.wikipedia.org/wiki/Unicode) and dif... | Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.
``... | In **HTML 5**, you can just use the [Canvas.measureText method](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText) (further explanation [here](http://www.html5canvastutorials.com/tutorials/html5-canvas-text-metrics/)).
[Try this fiddle](http://jsfiddle.net/eNzjZ/34/):
```
/**
* U... | Calculate text width with JavaScript | [
"",
"javascript",
"textbox",
""
] |
How do I lock compiled Java classes to prevent decompilation?
I know this must be very well discussed topic on the Internet, but I could not come to any conclusion after referring them.
Many people do suggest obfuscator, but they just do renaming of classes, methods, and fields with tough-to-remember character sequen... | Some of the more advanced Java bytecode obfuscators do much more than just class name mangling. [Zelix KlassMaster](http://www.zelix.com/), for example, can also scramble your code flow in a way that makes it really hard to follow and works as an excellent code optimizer...
Also many of the obfuscators are also able t... | As long as they have access to both the encrypted data and the software that decrypts it, there is basically no way you can make this completely secure. Ways this has been solved before is to use some form of external black box to handle encryption/decryption, like dongles, remote authentication servers, etc. But even ... | How to lock compiled Java classes to prevent decompilation? | [
"",
"java",
"jvm",
"decompiling",
""
] |
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.
**EDIT**: [The Java Tutorials - Drag and Drop and Data Transfer](http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html). | I liked [Terai Atsuhiro san's DnDTabbedPane](http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html), but I wanted more from it. The original Terai implementation transfered tabs within the TabbedPane, but it would be nicer if I could drag from one TabbedPane to another.
Inspired by @[Tom](... | Curses! Beaten to the punch by a Google search. Unfortunately it's true there is no easy way to create draggable tab panes (or any other components) in Swing. So whilst the example above is complete this one I've just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit... | How to implement draggable tab using Java Swing? | [
"",
"java",
"user-interface",
"swing",
"tabs",
""
] |
This is kind of hard to explain, I hope my English is sufficient:
I have a class "A" which should maintain a list of objects of class "B" (like a private List). A consumer of class "A" should be able to add items to the list. After the items are added to the list, the consumer should not be able to modify them again, ... | To prevent editing the list or its items you have to make them [immutable](http://en.wikipedia.org/wiki/Immutable_object), which means you have to return a new instance of an element on every request.
See Eric Lippert's excellent series of "Immutability in C#": <http://blogs.msdn.com/ericlippert/archive/tags/Immutabil... | As many of these answers show, there are many ways to make the collection itself immutable.
It takes more effort to keep the members of the collection immutable. One possibility is to use a facade/proxy (sorry for the lack of brevity):
```
class B
{
public B(int data)
{
this.data = data;
}
... | Controlling access to an internal collection in c# - Pattern required | [
"",
"c#",
"design-patterns",
"collections",
"data-access",
""
] |
What's the best way to shut down the computer from a C# program?
I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net. | Taken from: [a Geekpedia post](http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html)
This method uses [WMI](http://en.wikipedia.org/wiki/Windows_Management_Instrumentation) to shutdown windows.
You'll need to add a reference to System.Management to your project to use this.
```
using System.Management;... | Works starting with windows XP, not available in win 2000 or lower:
This is the quickest way to do it:
```
Process.Start("shutdown","/s /t 0");
```
Otherwise use P/Invoke or WMI like others have said.
Edit: how to avoid creating a window
```
var psi = new ProcessStartInfo("shutdown","/s /t 0");
psi.CreateNoWindow ... | How to shut down the computer from C# | [
"",
"c#",
".net",
"windows",
"shutdown",
""
] |
Java is one of my programming languages of choice. I always run into the problem though of distributing my application to end-users.
Giving a user a JAR is not always as user friendly as I would like and using Java WebStart requires that I maintain a web server.
What's the best way to distribute a Java application? W... | There are a variety of solutions, depending on your distribution requirements.
1. Just use a jar. This assumes that the user has the the correct java version installed, otherwise the user will get "class-file format version" exceptions. This is fine for internal distribution inside a company.
2. Use launch4j and an in... | [advanced installer](http://www.advancedinstaller.com/) makes it easy to package java apps as windows executables, and it's quite flexible in the way you can set it up. I've found that for distributing java applications to windows clients, this is the easiest way to go. | What's the best way to distribute Java applications? | [
"",
"java",
"installation",
"jar",
"software-distribution",
""
] |
PHP stores its session information on the file system of the host of the server establishing that session. In a multiple-host PHP environment, where load is unintelligently distributed amongst each host, PHP session variables are not available to each request (unless by chance the request is assigned to the same host -... | Database, or Database+Memcache. Generally speaking sessions should not be written to very often. Start with a database solution that only writes to the db when the session data has *changed*. Memcache should be added later as a performance enhancement. A db solution will be very fast because you are only ever looking u... | Whatever you do, do not store it on the server itself (even if you're only using one server, or in a 1+1 failover scenario). It'll put you on a dead end.
I would say, use Database+Memcache for storage/retrieval, it'll keep you out of Zend's grasp (and believe me things do break down at some point with Zend). Since you... | What is the best way to handle sessions for a PHP site on multiple hosts? | [
"",
"php",
"mysql",
"session",
"load-balancing",
"memcached",
""
] |
Was this an oversight? Or is it to do with the JVM? | Java does indeed have pointers--pointers on which you cannot perform pointer arithmetic.
From the venerable [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.1):
> There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, corresp... | In Java they use the nomenclature REFERENCE for referring to dynamically created objects. In previous languages, it is named POINTER. Just as the naming of METHODS in object oriented languages has taken over from former FUNCTION's and PROCEDURE's in earlier (object oriented as well as not object oriented) languages. Th... | Java: Why aren't NullPointerExceptions called NullReferenceExceptions? | [
"",
"java",
""
] |
I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE_(Python)) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo cau... | There's a file called `idle.py` in your Python installation directory in `Lib\idlelib\idle.py`.
If you run that file with Python, then IDLE should start.
> c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py | In Python 3.2.2, I found `\Python32\Lib\idlelib\idle.bat` which was useful because it would let me open python files supplied as args in IDLE. | How to start IDLE (Python editor) without using the shortcut on Windows Vista? | [
"",
"python",
"python-idle",
"komodo",
"pywin",
""
] |
I've wanted this for fluent interfaces. See, for example [this](http://channel9.msdn.com/forums/Coffeehouse/257556-C-Extension-Properties/) Channel9 discussion. Would probably [require](http://ayende.com/Blog/archive/2007/12/02/Why-C-doesnt-have-extension-properties.aspx) also adding indexed properties.
What are your ... | In my book the #1 most substantial reason for extension properties is implementing fluent interface patterns around unowned code. I built a wrapper around the NHibernate session to make it more intitutive to work with so I can do logic similar to
```
public bool IsInTransaction
{
get { return _session.Is().Not.Nul... | Since properties are just syntactic sugar for methods, I don't see why C# should have extension methods without extension properties. | Should extension properties be added to C# 4.0? | [
"",
"c#",
""
] |
Say I have the following methods:
```
def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
```
In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define `methodA` as follows, the second argument will be passed on as positional rather than named variable ... | Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.
```
methodB("argvalue", **kwargs)
``` | As an aside: When using functions instead of methods, you could also use functools.partial:
```
import functools
def foo(arg, **kwargs):
...
bar = functools.partial(foo, "argvalue")
```
The last line will define a function "bar" that, when called, will call foo with the first argument set to "argvalue" and all ... | Passing on named variable arguments in python | [
"",
"python",
"variadic-functions",
""
] |
This has been a problem that I haven't been able to figure out for sometime. Preventing the second instance is trivial and has many methods, however, bringing back the already running process isn't. I would like to:
* Minimized: Undo the minimize and bring the running instance to the front.
* Behind other windows: Bri... | I found this code to be useful. It does the detection and optional activation of an existing application:
<http://www.codeproject.com/KB/cs/cssingprocess.aspx> | If you're using .NET, this seems easier and more straightforward using build-in .NET functionality:
[The Weekly Source Code 31- Single Instance WinForms and Microsoft.VisualBasic.dll](http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx) | Return to an already open application when a user tries to open a new instance | [
"",
"c#",
".net",
"windows",
"vb.net",
""
] |
Writing some test scripts in IronPython, I want to verify whether a window is displayed or not. I have the pid of the main app's process, and want to get a list of window titles that are related to the pid.
I was trying to avoid using win32api calls, such as FindWindowEx, since (to my knowledge) you cannot access win3... | The article below shows how to access the win32api indirectly from IronPython. It uses CSharpCodeProvider CompileAssemblyFromSource method to compile an assembly in memory from the supplied C# source code string. IronPython can then import the assembly.
[Dynamically compiling C# from IronPython](http://www.voidspace.o... | As of IronPython 2.6 the [ctypes](http://docs.python.org/library/ctypes) module is supported. This module provides C compatible data types, and allows calling functions in DLLs. Quick example:
```
import ctypes
buffer = ctypes.create_string_buffer(100)
ctypes.windll.kernel32.GetWindowsDirectoryA(buffer, len(buffer))
p... | How to use win32api from IronPython | [
"",
"c#",
"winapi",
"ironpython",
""
] |
(Java question)
If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class?
How can I avoid this?
Here is an example:
```
public class Outer {
private Other o;
private Inner i;
public Outer() {
o = new Other();
i = new Inner()... | **Static vs instance class:** If you declare the inner class as static then the instances of the inner class doesn't have any reference to the outer class. If it's not satic then your inner object efectivelly points to the outer object that created it (it has an implicit reference, in fact, if you use reflection over i... | The syntax you're using in the example is a little off there is no declaration of the class or interface Inner. But there isn't anything wrong with the concept of the example. In Java it will work fine.
I'm not sure what you're doing here, but you may want to consider a more simple design for maintainability etc.
It'... | How do you resolve a circular dependency with an inner class? | [
"",
"java",
"circular-dependency",
"anonymous-inner-class",
""
] |
In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int:
`activation successful of id 1010101`
The line above is the exact structure of the data in the db field.
And no I don't want to do this in th... | This should do the trick:
```
SELECT SUBSTRING(column, PATINDEX('%[0-9]%', column), 999)
FROM table
```
Based on your sample data, this that there is only one occurence of an integer in the string and that it is at the end. | ```
-- Test table, you will probably use some query
DECLARE @testTable TABLE(comment VARCHAR(255))
INSERT INTO @testTable(comment)
VALUES ('activation successful of id 1010101')
-- Use Charindex to find "id " then isolate the numeric part
-- Finally check to make sure the number is numeric before convertin... | SQL strip text and convert to integer | [
"",
"sql",
"text",
"strip",
""
] |
As many of us know (and many, many more don't), C++ is currently undergoing final drafting for the next revision of the International Standard, expected to be published in about 2 years. Drafts and papers are currently available from the [committee website](http://open-std.org/JTC1/SC22/WG21/). All sorts of new feature... | **auto** keyword for variable type inferencing | Lambdas and initializer lists.
Also, the changes to make it easier to eventually bring C++ into a garbage collected model, those seem pretty interesting. Perhaps C++1x will actually bring in garbage collection, but 0x/10 just set things up for the eventuality. | What's your favorite C++0x feature? | [
"",
"c++",
"c++11",
""
] |
Greetings all,
I'm trying to localize a .NET/C# project. I'm using string resource files and setting the "Localizable" property on all my forms to 'True'. The assembly culture is empty. The resx/resource files are successfully passed through Lingobit, resgen, and al.
When running the localized executables, *some* of ... | When you open the form in Visual Studio, if you change the Language property of the Form to the language you are localizing to, does the same problem exist there? Could it be possible that the non-localized forms/buttons still have the English text set even in the localized resources? | Yeah, I'd go with Andy on this and be suspicious of the contents of the resource files. We dabbled with localisation for a time, and encountered a number of issues, but this certainly wasn't one of them.
If that isn't it, then how are you testing your app? If you haven't tried this already I'd suggest firing up a set ... | Why Aren't All My WinForm Controls and Forms Localizing? | [
"",
"c#",
".net",
"localization",
""
] |
I want to access the call stack at runtime in a Native C++ application. I am not using the IDE. How do I display the call stack?
Update: I have a function which is called from many points all over the application. It crashes on rare occasions. I was looking for a way to get name of the caller and log it. | I believe that [this](https://stackoverflow.com/questions/105659/how-can-one-grab-a-stack-trace-in-c#105741) page has the answer you are looking for. You said Visual C so I assume you mean windows. | Have a look at [StackWalk64](http://msdn.microsoft.com/en-us/library/ms680650(VS.85).aspx).
If you're used to doing this on .NET, then you're in for a nasty surprise. | Call Stack at Runtime | [
"",
"c++",
"debugging",
"visual-c++",
"stack-trace",
"callstack",
""
] |
My users would like to be able to hit `Ctrl`+`S` to save a form. Is there a good cross-browser way of capturing the `Ctrl`+`S` key combination and submit my form?
App is built on Drupal, so jQuery is available. | ```
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
```
Key codes can differ between browsers, so you may need to check for more than just 115. | This works for me (using jquery) to overload `Ctrl`+`S`, `Ctrl`+`F` and `Ctrl`+`G`:
```
$(window).bind('keydown', function(event) {
if (event.ctrlKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 's':
event.preventDefault();
alert('ctrl-s... | Best cross-browser method to capture CTRL+S with JQuery? | [
"",
"javascript",
"jquery",
""
] |
I have an application that has created a number of custom event log sources to help filter its output. How can I delete the custom sources from the machine WITHOUT writing any code as running a quick program using System.Diagnostics.EventLog.Delete is not possible.
I've tried using RegEdit to remove the custom sources... | I also think you're in the right place... it's stored in the registry, under the name of the event log. I have a custom event log, under which are multiple event sources.
> HKLM\System\CurrentControlSet\Services\Eventlog\LOGNAME\LOGSOURCE1
> HKLM\System\CurrentControlSet\Services\Eventlog\LOGNAME\LOGSOURCE2
Those sou... | What about using [Powershell](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/remove-eventlog)?
```
Remove-EventLog -LogName "Custom log name"
Remove-EventLog -Source "Custom source name"
``` | Deleting Custom Event Log Source Without Using Code | [
"",
"c#",
"windows",
"event-log",
""
] |
So I was writing some code today that basically looks like this:
```
string returnString = s.Replace("!", " ")
.Replace("@", " ")
.Replace("#", " ")
.Replace("$", " ")
.Replace("%", " ")
.Replace("^", " ")
.Replace("*", " ")
.Replace("... | You can use **Regex.Replace()**. All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first para... | FYI - if you need to modify this regex, you'll need to have an understanding of the regular expression language. It is quite simple, and as a developer you really owe it to yourself to add regular expressions to your toolbox - you don't need them every day, but being able to apply them appropriately where necessary whe... | Alternative to String.Replace | [
"",
"c#",
"regex",
"string",
"replace",
""
] |
Eg. can I write something like this code:
```
public void InactiveCustomers(IEnumerable<Guid> customerIDs)
{
//...
myAdoCommand.CommandText =
"UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)";
myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs;
//...
}
```
The only w... | Generally the way that you do this is to pass in a comma-separated list of values, and within your stored procedure, parse the list out and insert it into a temp table, which you can then use for joins. As of **Sql Server 2005**, this is standard practice for dealing with parameters that need to hold arrays.
Here's a ... | You can with [SQL 2008](http://blog.benhall.me.uk/2007/07/sql-server-2008-table-value-parameters.html). It hasn't been out very long, but it is available. | Is it possible to send a collection of ID's as a ADO.NET SQL parameter? | [
"",
".net",
"sql",
"ado.net",
""
] |
What is `std::pair` for, why would I use it, and what benefits does `boost::compressed_pair` bring? | [`std::pair`](http://en.cppreference.com/w/cpp/utility/pair) is a data type for grouping two values together as a single object. [`std::map`](http://en.cppreference.com/w/cpp/container/map) uses it for key, value pairs.
While you're learning [`pair`](http://en.cppreference.com/w/cpp/utility/pair), you might check out ... | `compressed_pair` uses some template trickery to save space. In C++, an object (small o) can not have the same address as a different object.
So even if you have
```
struct A { };
```
`A`'s size will not be 0, because then:
```
A a1;
A a2;
&a1 == &a2;
```
would hold, which is not allowed.
*But* many compilers wil... | What is std::pair? | [
"",
"c++",
"boost",
"stl",
"std-pair",
""
] |
A poorly-written back-end system we interface with is having trouble with handling the load we're producing. While they fix their load problems, we're trying to reduce any additional load we're generating, one of which is that the back-end system continues to try and service a form submission even if another submission... | If you've got jQuery handy, attach a click() event that disables the button after the initial submission -
```
$('input[type="submit"]').click(function(event){
event.preventDefault();
this.click(null);
});
```
that sort of thing. | Using Prototype, you can use this code to watch if any form has been submitted and disable all submit buttons when it does:
```
document.observe( 'dom:loaded', function() { // when document is loaded
$$( 'form' ).each( function( form ) { // find all FORM elements in the document
form.observe( 'submit', fun... | Debounce clicks when submitting a web form | [
"",
"javascript",
"html",
"prototypejs",
""
] |
SQL is not my forte, but I'm working on it - thank you for the replies.
I am working on a report that will return the completion percent of services for indiviudals in our contracts. There is a master table "Contracts," each individual Contract can have multiple services from the "services" table, each service has mul... | I'm not sure if I understand the problem, if the result is ok for a service\_contract you canContract Service
```
SELECT con.ContractId,
con.Contract,
conSer.Contract_ServiceID,
conSer.Service,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FR... | You should be able to add in your select the company name and group by that and the service id and ditch the where clause...
Perhaps like this:
```
SELECT
Contract,
Contract_ServiceId,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FROM dbo.Standard sta ... | Nested SELECT Statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
That's it. If you want to document a function or a class, you put a string just after the definition. For instance:
```
def foo():
"""This function does nothing."""
pass
```
But what about a module? How can I document what a *file.py* does? | For the packages, you can document it in `__init__.py`.
For the modules, you can add a docstring simply in the module file.
All the information is here: <http://www.python.org/dev/peps/pep-0257/> | Add your docstring as the [first statement in the module](http://www.python.org/dev/peps/pep-0257/).
```
"""
Your module's verbose yet thorough docstring.
"""
import foo
# ...
```
For packages, you can add your docstring to `__init__.py`. | How do I document a module in Python? | [
"",
"python",
"documentation",
"python-module",
""
] |
I would like to use client-side Javascript to perform a DNS lookup (hostname to IP address) as seen from the client's computer. Is that possible? | There's no notion of hosts or ip-addresses in the javascript standard library. So you'll have to access some external service to look up hostnames for you.
I recommend hosting a cgi-bin which looks up the ip-address of a hostname and access that via javascript. | **Edit**: This question gave me an itch, so I put up a JSONP webservice on Google App Engine that returns the clients ip address. Usage:
```
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://jsonip.apps... | Can I perform a DNS lookup (hostname to IP address) using client-side Javascript? | [
"",
"javascript",
"dns",
""
] |
I have an asp.net application that runs exclusively on IE7 (internal web site).
When a user needs to enter data, I pop up a child window with a form. When the form closes, it calls javascript:window.opener.location.reload(true) so that the new data will display on the main page.
The problem is that the browser compla... | It's because the page in window.opener comes from a POST Request
Maybe you can use
javascript:window.opener.location = window.opener.location; to do just a GET request if the data can be fetched without a POST. | No, but there is a solution. Its generally considered good design to use a 302 redirect immediately after someone posts data to a page. This prevents that popup from ever occuring. Allow me to elaborate.
1) The user fills in a form and submits data via POST.
2) The backend receives the data and acts upon it.
3) Inst... | How to disable browser postback warning dialog | [
"",
"asp.net",
"javascript",
"internet-explorer-7",
""
] |
Basically, something similar to System.Xml.XmlWriter - A streaming XML Writer that doesn't incur much of a memory overhead. So that rules out xml.dom and xml.dom.minidom. Suggestions? | **xml.etree.cElementTree**, included in the default distribution of CPython since 2.5. Lightning fast for both reading and writing XML. | I think you'll find XMLGenerator from xml.sax.saxutils is the closest thing to what you want.
```
import time
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesNSImpl
LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR']
class xml_logger:
def __init__(self, output, encoding):
"""
... | What's the easiest non-memory intensive way to output XML from Python? | [
"",
"python",
"xml",
"streaming",
""
] |
I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?
```
String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);
```
Note: My input is a **S... | Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6.
```
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializ... | ```
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(ne... | How to pretty print XML from Java? | [
"",
"java",
"xml",
"pretty-print",
""
] |
Can anyone recommend a simple API that will allow me to use read a CSV input file, do some simple transformations, and then write it.
A quick google has found <http://flatpack.sourceforge.net/> which looks promising.
I just wanted to check what others are using before I couple myself to this API. | # Apache Commons CSV
Check out [*Apache Common CSV*](http://commons.apache.org/proper/commons-csv/).
This library reads and writes [several variations of CSV](http://commons.apache.org/proper/commons-csv/archives/1.6/apidocs/index.html), including the standard one [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180). A... | I've used [OpenCSV](http://opencsv.sourceforge.net/) in the past.
```
import au.com.bytecode.opencsv.CSVReader;
```
```
String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));
```
// if the first line is the header
String[] header = reader.readNext();
// iterate over reader.readN... | CSV API for Java | [
"",
"java",
"csv",
""
] |
In my job we have to deploy an application on various environments. It's a standard WAR file which needs a bit of configuration, deployed on Tomcat 6.
Is there any way of creating a 'deployment package' with Tomcat so that you just extract it and it sets up Tomcat as well as your application? I'm not sure that creatin... | We use [Ant Installer](http://antinstaller.sourceforge.net/) to deploy our application, app server and install it as a service. We embed [Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/integrate.html) in the installer to install the Windows service. | It's commercial, but [install4j](http://www.ej-technologies.com/products/install4j/overview.html) will do this for you, including installing the service. | Packaging up Tomcat | [
"",
"java",
"web-applications",
"tomcat",
""
] |
varchar(255), varchar(256), nvarchar(255), nvarchar(256), nvarchar(max), etc?
256 seems like a nice, round, space-efficient number. But I've seen 255 used a lot. Why?
What's the difference between varchar and nvarchar? | VARCHAR(255). It won't use all 255 characters of storage, just the storage you need. It's 255 and not 256 because then you have space for 255 plus the null-terminator (or size byte).
The "N" is for Unicode. Use if you expect non-ASCII characters. | In MS SQL Server (7.0 and up), varchar data is represented internally with up to three values:
* The actual string of characters, which will be from 0 to something over 8000 bytes (it’s based on page size, the other columns stored for the row, and a few other factors)
* Two bytes used to indicate how long the data str... | How should I store short text strings into a SQL Server database? | [
"",
"sql",
"sql-server",
"database",
"database-design",
""
] |
I am running following `PHP` code to interact with a MS Access database.
```
$odbc_con = new COM("ADODB.Connection");
$constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";";
$odbc_con -> open($constr);
$rs_select = $odbc_con -> execute ("SELECT * FROM Main");
```
Using `($rs_select -> RecordCoun... | ADODB has its own rules for what recordcount is returned depending on the type of recordset you've defined. See:
[MS Knowledge Base article 194973](http://support.microsoft.com/kb/194973)
[W3C Schools article](http://www.w3schools.com/ADO/prop_rs_recordcount.asp)
In the example above, the PHP COM() object is used to... | It is possible that ODBC doesn't know the recordcount yet. In that case it is possible to go to the last record and only then will recordcount reflect the true number of records. This will probably also not be very efficient since it will load all records from the query.
As Oli said, using `SELECT COUNT(*)` will give ... | PHP and MS Access: Number of Records returned by SELECT query | [
"",
"php",
"database",
"ms-access",
""
] |
I was asked to make some drools traning for my teammates. Just to show them how it can be used and how usefull it may be. To do this training I first have to learn Drools, and I figured that the best way to learn it will be small project centered around drools.
Any interesting ideas?
My idea for this project was to d... | Actually, we have a drools based project, you could try to mimic that. :-)
Suppose you have incoming SMS messages arriving on an HTTP based protocol. An HTTP request contains the Anumber (telephone number of the sender) the Bnumber (telephone number of the recipient) and the text of the message.
Your goal is to use d... | I'm gonna give you two real examples that my company is using right now. The company is one of the biggest e-commerce from Brazil.
1. Drools is used to apply price promotions and discount over products while users just navigates inside the product's catalog.
So, before rendering the response for the user browser, w... | Drools project idea needed | [
"",
"java",
"drools",
"webmethods",
""
] |
I have a little problem with a Listview.
I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error]. There is a a narrow str... | Ah! I see now :}
You want hacky? I present unto you the following:
```
...
lv.OwnerDraw = true;
lv.DrawItem += new DrawListViewItemEventHandler( lv_DrawItem );
...
void lv_DrawItem( object sender, DrawListViewItemEventArgs e )
{
Rectangle foo = e.Bounds;
foo.Offset( -10, 0 );
e.Graphics.F... | (Prior to the Edit...)
I've just tried setting the BackColor on a System.Windows.Forms.ListView, and the color is applied across the control just fine (with and without images).
Are you doing any Custom Painting at all? | Listview background drawing problem C# Winform | [
"",
"c#",
"winforms",
"listview",
""
] |
I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum wi... | You can embed newlines in the text to force it to wrap at a certain point. e.g.
```
"message text...\nmore text..."
```
update: I posted that thinking it was a win32 API question, but I think the principle should still apply. I assume WinForms eventually calls MessageBox(). | There's really just two ways (sane ways)
1) Add line breaks to your string yourself to limit the lenghth of each line.
2) Make your own form and use it rather than messagebox. | Shape of a Winforms MessageBox | [
"",
"c#",
"winforms",
""
] |
When a PHP application makes a database connection it of course generally needs to pass a login and password. If I'm using a single, minimum-permission login for my application, then the PHP needs to know that login and password somewhere. What is the best way to secure that password? It seems like just writing it in t... | Several people misread this as a question about how to **store** passwords in a database. That is wrong. It is about how to store the password that lets you get **to** the database.
The usual solution is to move the password out of source-code into a configuration file. Then leave administration and securing that conf... | If you're hosting on someone else's server and don't have access outside your webroot, you can always put your password and/or database connection in a file and then lock the file using a .htaccess:
```
<files mypasswdfile>
order allow,deny
deny from all
</files>
``` | How to secure database passwords in PHP? | [
"",
"php",
"database",
"security",
""
] |
What's the best practice for using a `switch` statement vs using an `if` statement for 30 `unsigned` enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conv... | Use switch.
In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.
In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary de... | For the special case that you've provided in your example, the clearest code is probably:
```
if (RequiresSpecialEvent(numError))
fire_special_event();
```
Obviously this just moves the problem to a different area of the code, but now you have the opportunity to reuse this test. You also have more options for how... | Advantage of switch over if-else statement | [
"",
"c++",
"if-statement",
"optimization",
"switch-statement",
""
] |
How can brackets be escaped in using `string.Format`?
For example:
```
String val = "1,2,3"
String.Format(" foo {{0}}", val);
```
This example doesn't throw an exception, but it outputs the string `foo {0}`.
Is there a way to escape the brackets? | For you to output `foo {1, 2, 3}` you have to do something like:
```
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
```
To output a `{` you use `{{` and to output a `}` you use `}}`.
**Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)**
**Escaping bracke... | Yes, to output `{` in `string.Format` you have to escape it like this: `{{`
So the following will output `"foo {1,2,3}"`.
```
String val = "1,2,3";
String.Format(" foo {{{0}}}", val);
```
*But* you have to know about a design bug in C# which is that by going on the above logic you would assume this below code will p... | How to escape braces (curly brackets) in a format string in .NET | [
"",
"c#",
".net",
"string",
"parsing",
"formatting",
""
] |
Is there a way to debug or trace every JavaScript event in Internet Explorer 7?
I have a bug that prevents scrolling after text-selecting, and I have no idea which event or action creates the bug. I really want to see which events are being triggered when I move the mouse for example.
It's too much work to rewire the... | Borkdude said:
> You might want to try Visual Studio 2008 and its feature to debug JavaScript code.
I've been hacking around event handling multiple times, and in my opinion, although classical stepping debuggers are useful to track long code runs, they're not good in tracking events. Imagine listening to mouse move ... | Loop through all elements on the page which have an onXYZ function defined and then add the trace to them:
```
var allElements = document.all; // Is this right? Anyway, you get the idea.
for (var i in allElements) {
if (typeof allElements[i].onblur == "function") {
var oldFunc = allElements[i].onblur;
... | How to trace JavaScript events like onclick onblur? | [
"",
"javascript",
"debugging",
"events",
""
] |
> **Possible Duplicate:**
> [JavaScript: var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname)
What's the difference between:
```
function sum(x, y) {
return x+y;
}
// and
var sum = function (x, ... | The first is known as a named function where the second is known as an anonymous function.
The key practical difference is in when you can use the sum function. For example:-
```
var z = sum(2, 3);
function sum(x, y) {
return x+y;
}
```
`z` is assigned 5 whereas this:-
```
var z = sum(2, 3);
var sum = function(... | The first tends to be used for a few reasons:
1. The name "sum" shows up in the
stacktrace which makes debugging
easier in many browsers.
2. The name
"sum" can be used inside the
function body which makes it easier
to use for recursive functions.
3. function declarations are "hoisted"
in javascript, ... | The difference between the two functions? ("function x" vs "var x = function") | [
"",
"javascript",
""
] |
What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes).
I've already seen a [few](http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) [wa... | The least painful and indeed Django-recommended way of doing this is through a `OneToOneField(User)` property.
> ## [Extending the existing User model](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model)
>
> …
>
> If you wish to store information related to `User`, you can... | **Note: this answer is deprecated. see other answers if you are using Django 1.7 or later.**
This is how I do it.
```
#in models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
#other fields h... | What's the best way to extend the User model in Django? | [
"",
"python",
"django",
"django-models",
"django-authentication",
"django-users",
""
] |
I could swear I've seen the function (or method) that takes a list, like this `[3, 7, 19]` and makes it into iterable list of tuples, like so: `[(0,3), (1,7), (2,19)]` to use it instead of:
```
for i in range(len(name_of_list)):
name_of_list[i] = something
```
but I can't remember the name and googling "iterate l... | ```
>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
... print i, val
...
0 3
1 4
2 5
3 6
>>>
``` | Yep, that would be the [`enumerate`](http://docs.python.org/library/functions.html#enumerate) function! Or more to the point, you need to do:
```
list(enumerate([3,7,19]))
[(0, 3), (1, 7), (2, 19)]
``` | Iterate a list with indexes | [
"",
"python",
"list",
""
] |
I am working on an application that is about 250,000 lines of code. I'm currently the only developer working on this application that was originally built in .NET 1.1. Pervasive throughout is a class that inherits from CollectionBase. All database collections inherit from this class. I am considering refactoring to inh... | 250,000 Lines is alot to refactor, plus you should take into account several of the follow:
1. Do you have a QA department that will be able to QA the refactored code?
2. Do you have unit tests for the old code?
3. Is there a timeframe that is around the project, i.e. are you maintaining the code as users are finding ... | Don't. Unless you have a really good business justification for putting your code base through this exercise. What is the cost savings or revenue generated by your refactor? If I were your manager I would probably advise against it. Sorry. | How to Refactor to Generics from Class that Inherits from CollectionBase? | [
"",
"c#",
"generics",
".net-3.5",
".net-2.0",
"refactoring",
""
] |
Lasty, I tried to implements an hybrid structure in Java, something that looks like:
```
public class MapOfSet<K, V extends HasKey<K>> implements Set<V>, Map<K, Set<V>>
```
Where HasKey is the following interface:
```
public interface HasKey<K> {
public K getKey();
}
```
Unfortunately, there are some conflicts ... | Perhaps you could add more information which operations do you really want. I guess you want to create a set which automatically groups their elements by a key, right? The question is which operations do you want to be able to have? How are elements added to the Set? Can elements be deleted by removing them from a grou... | What are you trying to accomplish? `Map` already exposes its keys as a `Set` via its [keySet()](<http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet())> method. If you want a reliable iteratior order, there's [LinkedHashMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html) and [TreeMa... | Implements several interfaces with conflict in signatures | [
"",
"java",
"collections",
""
] |
What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?
No legacy browser compatibility required, Safari, Opera and Firefox will do. | If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but **without jQuery**.
```
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
... | **Update** (5/5/16): [patriques' answer](https://stackoverflow.com/a/18053642/1026023) should be used instead, as it's both simpler and more reliable.
---
Since the canvas isn't always styled relative to the entire page, the `canvas.offsetLeft/Top` doesn't always return what you need. It will return the number of pix... | How do I get the coordinates of a mouse click on a canvas element? | [
"",
"javascript",
"canvas",
""
] |
I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle. | From my "Geometry" class:
```
public struct Line
{
public static Line Empty;
private PointF p1;
private PointF p2;
public Line(PointF p1, PointF p2)
{
this.p1 = p1;
this.p2 = p2;
}
public PointF P1
{
get { return p1; }
set { p1 = value; }
}
pu... | Do <http://mathworld.wolfram.com/Line-LineIntersection.html> for the line and each side of the rectangle.
Or: <http://mathworld.wolfram.com/Line-PlaneIntersection.html> | How to know if a line intersects a plane in C#? | [
"",
"c#",
"geometry",
"2d",
"computational-geometry",
""
] |
In my browsings amongst the Internet, I came across [this post](http://www.reddit.com/r/programming/comments/6y6lr/ask_proggit_which_is_more_useful_to_know_c_or_java/), which includes this
> "(Well written) C++ goes to great
> lengths to make stack automatic
> objects work "just like" primitives,
> as reflected in Str... | Stack objects are handled automatically by the compiler.
When the scope is left, it is deleted.
```
{
obj a;
} // a is destroyed here
```
When you do the same with a 'newed' object you get a memory leak :
```
{
obj* b = new obj;
}
```
b is not destroyed, so we lost the ability to reclaim the memory b owns. ... | In addition to the other answers:
The C++ language actually has the `auto` keyword to explicitly declare the storage class of an object. Of course, it's completely needless because this is the implied storage class for local variables and cannot be used anywhere. The opposite of `auto` is `static` (both locally and gl... | C++ - What does "Stack automatic" mean? | [
"",
"c++",
"oop",
""
] |
Do any C++ GNU standalone classes exist which handle paths cross platform? My applications build on Windows and LInux. Our configuration files refer to another file in a seperate directory. I'd like to be able to read the path for the other configuration file into a class which would work on both Linux or Windows.
Whi... | Unless you're using absolute paths, there's no need to translate at all - Windows automatically converts forward slashes into backslashes, so if you use relative paths with forward slash path separators, you'll be golden. You should really avoid absolute paths if at all possible. | try [boost::filesystem](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm) | Handling file paths cross platform | [
"",
"c++",
"windows",
"linux",
"cross-platform",
"gnu",
""
] |
Should simple JavaBeans that have only simple getters and setters be unit tested??
What about Beans with some logic in getters and setters? | You should not write tests which:
* Test the language or the IDE (i.e. automatically generated getters and setters)
* Add no value to your test harness and kill your enthusiasm for Unit Testing
The same applies for .NET objects which only have properties (sometimes called 'Info' objects).
In an ideal world you would... | If it's not worth testing, it's not worth writing.
That doesn't always mean you should write tests. Sometimes it means you should delete code. Do you need these beans? Do they actually do anything important? If you need them, you should write tests. If not, delete the code and live a happier life knowing you have less... | Should domain objects and simple JavaBeans be unit tested? | [
"",
"java",
"unit-testing",
""
] |
When I iterate over the values or keys are they going to correlate? Will the second key map to the second value? | No, not necessarily. You should really use the entrySet().iterator() for this purpose. With this iterator, you will be walking through all Map.Entry objects in the Map and can access each key and associated value. | to use the entrySet that @Cuchullain mentioned:
```
Map<String, String> map = new HashMap<String, String>();
// populate hashmap
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// your code here
}
``` | When using a HashMap are values and keys guaranteed to be in the same order when iterating? | [
"",
"java",
"collections",
"hashmap",
""
] |
In a `CakePHP 1.2` app, I'm using
```
<?php $session->flash();?>
```
to output messages like "Record edited". It's working great.
However, I want to add a link called "Dismiss" that will fade out the message. I know how to construct the link, but I don't know how to insert into the output of the flass message.
The ... | Figured this out:
Create a new layout in your layouts folder:
```
layouts/message.ctp
```
In that layout, include the call to output the content:
```
<?php echo $content_for_layout; ?>
```
Then when you set the flash message, specify the layout to use:
```
$this->Session->setFlash('Your record has been created! Wi... | You want to use the [setflash](http://api.cakephp.org/class_session_component.html) function. If you pass setflash an empty string for $default it will not wrap your message in a div and just store it as is. This way you can display any markup you want or as Justin posted you can use another view page for your message ... | Add dismiss control to session-flash() output in CakePHP | [
"",
"php",
"cakephp",
"cakephp-1.2",
""
] |
How do you get a Media Type (MIME type) from a file using Java? So far I've tried JMimeMagic & Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly.
How would you probe the file to determine its actual type (not merely based on the extension)? | In Java 7 you can now just use [`Files.probeContentType(path)`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType%28java.nio.file.Path%29). | Unfortunately,
```
mimeType = file.toURL().openConnection().getContentType();
```
does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.
However, you have this:
```
mimeType= URLConnection.guessContentTypeFromName(file.getName());
```
and also the following, which has t... | How to get a file's Media Type (MIME type)? | [
"",
"java",
"mime",
""
] |
what is the best method for inter process communication in a multithreaded java app.
It should be performant (so no JMS please) easy to implement and reliable,so that
objects & data can be bound to one thread only?
Any ideas welcome! | Assuming the scenario 1 JVM, multiple threads then indeed java.util.concurrent is the place to look, specifically the various Queue implementations. However an abstraction on top of that may be nice and there [Jetlang](http://code.google.com/p/jetlang/) looks very interesting, lightweight Java message passing. | Could you clarify a bit? Do you mean IPC in a single JVM? (Multiple threads, yes, but at an OS-level only one process.) Or do you mean multiple JVMs? (And truly OS-level inter process communications.)
If it is the first, then maybe something out of **java.util.concurrent**, like [ConcurrentLinkedQueue](http://java.sun... | Best practice for Java IPC | [
"",
"java",
"multithreading",
""
] |
In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.
Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.
What are your thoughts on this and what do you fo... | I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of `final` modifiers anywhere, but when you think about it...
Adding `final` to all things which *should not* change simply narrows down the possibilities that you (or the next programmer, working on your... | Obsess over:
* Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things... | Using the "final" modifier whenever applicable in Java | [
"",
"java",
"oop",
""
] |
I'm using Visual Studio 2008 and the built-in installation tools for a C# client application. How can I use this installer to install a font on the client machine (if it's not already there)? | In VS2005 (so I assume 2008 as well), right click on the File System on Target Machine, Add Special Folder -> Fonts Folder, then place your font file there. | For me, Timothy Carter had the answer mostly right:
"right click on the File System on Target Machine, Add Special Folder -> Fonts Folder, then place your font file there."
But that was not enough. The Fonts didn't actually get installed as system Fonts.
To install the fonts, I had to visit the Properties for each f... | Installing a font on a client machine | [
"",
"c#",
"visual-studio-2008",
"installation",
"fonts",
""
] |
I am building a site that uses a simple AJAX Servlet to talk JMS (ActiveMQ) and when a message arrives from the topic to update the site.
I have Javascript that creates an XMLHttpRequest for data. The Servlet processes the Get Request and sends back JSON. However I have no idea how to connect my Servlet into my Active... | The problem with having a servlet implement MessageListener is that servlets are synchronous and MessageListeners are asynchronous. Instead you should create some other object to act as the MessageListener and update some state somewhere (possibly a database or a JMX MBean or a Stateful Session EJB) when messages come ... | As James Strachan says - <http://activemq.apache.org/ajax.html> is an ideal out-of-the-box solution for your problem.
If you still want to create such solution manually you can just create JMS connection in your Ajax servlet (connection per request). Consider using Spring JMS template for that reason ( <http://static.... | Write a Servlet that Talks to JMS (ActiveMQ) and OnMessage Update the Site | [
"",
"javascript",
"servlets",
"jms",
"activemq-classic",
""
] |
I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a `JFileChooser`; when it is closed, the absolute path of the selected file is written to a `JTextField`.
The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too... | It may depend on the layout manager your text field is in. Some layout managers expand and some do not. Some expand only in some cases, others always.
I'm assuming you're doing
```
filedNameTextField = new JTextField(80); // 80 == columns
```
If so, for most reasonable layouts, the field should not change size (at l... | I solved this by setting the maximum width on the container of the text field, using `setMaximumSize`.
According to davetron's answer, this is a fragile solution, because the layout manager might disregard that property. In my case, the container is the top-most, and in a first test it worked. | Java, Swing: how do I set the maximum width of a JTextField? | [
"",
"java",
"swing",
"jtextfield",
""
] |
We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe.
For example, the page at the URL <http://oursite/Page.aspx?a=1&b=2> would have JavaScript in it to rea... | Upadte Sep 2022: Most JS runtimes now have a *URL* type which exposes query parameters via the [*searchParams*](https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams) property.
You need to supply a base URL even if you just want to get URL parameters from a relative URL, but it's better than rolling your ow... | Using a whitelist-approach would be better I guess.
Avoid only stripping out "bad" things. Strip out anything except for what you think is "safe".
Also I'd strongly encourage to do a HTMLEncode the Parameters. There should be plenty of Javascript functions that can this. | Best way to safely read query string parameters? | [
"",
"javascript",
"security",
"parameters",
""
] |
What is the best way to reduce the size of the viewstate hidden field in JSF?
I have noticed that my view state is approximately 40k this goes down to the client and back to the server on every request and response espically coming to the server this is a significant slowdown for the user.
My Environment JSF 1.2, MyFa... | Have you tried setting the state saving to server? This should only send an id to the client, and keep the full state on the server. Simply add the following to the file *web.xml* :
```
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
``` | If you are using MyFaces you can try this setting to compress the viewstate before sending to the client.
```
<context-param>
<param-name>org.apache.myfaces.COMPRESS_STATE_IN_CLIENT</param-name>
<param-value>true</param-value>
</context-param> `
``` | How to reduce javax.faces.ViewState in JSF | [
"",
"java",
"optimization",
"jsf",
"viewstate",
"bandwidth",
""
] |
Every time I try to run a small application that uses a Derby DB I get this error message:
> **Message: Database at /path/to/db/TheDB has an incompatible format with the current version of the software. The database was created by or upgraded by version 10.4.**
I've added the library from Netbeans, and still have the... | The version included with Netbeans might be old (Derby 10.2 as of NB 6.0). If you added Derby via the project properties and added the "Library", then you probably had the old version.
You can update the library by going to Tool -> Libraries. Select "Java DB Driver". Delete the jar references and update them to point ... | Hmmm, all I have to do was to add the proper derby.jar **manually** to the project.
A simple copy command operation:
> cp /opt/Apache/derbyinstall/lib/**derby.jar** /path/to/project/**dist/lib/**
...did the job.
The problem was that: I did this operation *from* Netbeans, and *I don't know why*, Netbeans didn't upda... | How do I configure a project to use latest Derby DB version (10.4)? | [
"",
"java",
"netbeans",
"derby",
""
] |
In a recent conversation, I mentioned that I was using JavaScript for a web application. That comment prompted a response: "You should use Flex instead. It will cut your development time down and JavaScript is too hard to debug and maintain. You need to use the right tool for the right job." Now, I don't know too much ... | I would push you towards standard web development technologies in most cases. Javascript is no longer a great challenge to debug or maintain with good libs like jQuery/Prototype to iron out some of the browser inconsistencies and tools like Firebug and the MS script debugger to help with debugging.
There are cases whe... | I have recently started to develop Flex applications, and I personally find it a refreshing framework for the web.
You get a state-ful application that runs completely client side. You get no worries about cross-browser portability that you do with JavaScript, and you get some really neat things such as effects, graph... | Why should I use Flex? | [
"",
"javascript",
"apache-flex",
""
] |
I'm working on a large c++ system that is has been in development for a few years now. As part of an effort to improve the quality of the existing code we engaged on a large long-term refactoring project.
Do you know a good tool that can help me write unit tests in C++? Maybe something similar to Junit or Nunit?
Can ... | Applying unit tests to legacy code was the **very reason** [Working Effectively with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052) was written. Michael Feathers is the author - as mentioned in other answers, he was involved in the creation of both [CppUnit](http://sourceforge.net/projects/cppun... | Google recently released their own library for unit testing C++ apps, called Google Test.
[Project on Google Code](http://code.google.com/p/googletest/) | Unit testing for C++ code - Tools and methodology | [
"",
"c++",
"unit-testing",
"refactoring",
""
] |
I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the file is already opened? Does this automatically make the second process get an exception if the file is open (which solves my problem) or do I have... | FileChannel.lock is probably what you want.
```
try (
FileInputStream in = new FileInputStream(file);
java.nio.channels.FileLock lock = in.getChannel().lock();
Reader reader = new InputStreamReader(in, charset)
) {
...
}
```
(Disclaimer: Code not compiled and certainly not tested.)
Note the section e... | Don't use the classes in the`java.io` package, instead use the `java.nio` package . The latter has a `FileLock` class. You can apply a lock to a `FileChannel`.
```
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").... | How can I lock a file using java (if possible) | [
"",
"java",
"file-io",
""
] |
In Java, I use a class in which some fields can be `null`. For example:
```
class Foo {
String bar;
//....
}
```
I want to write a BarComparator for this class,
```
private static class BarComparator
implements Comparator<Foo> {
public int compare( final Foo o1, final Foo o2 )
... | I guess you could wrap the call to the field compareTo method with a small static method to sort nulls high or low:
```
static <T extends Comparable<T>> int cp(T a, T b) {
return
a==null ?
(b==null ? 0 : Integer.MIN_VALUE) :
(b==null ? Integer.MAX_VALUE : a.compareTo(b));
}
```
Simple ... | Thanks for the replies! The generic method and the Google Comparators look interesting.
And I found that there's a [NullComparator](http://commons.apache.org/collections/api-release/org/apache/commons/collections/comparators/NullComparator.html) in the [Apache Commons Collections](http://commons.apache.org/collections... | What to do with null fields in compare()? | [
"",
"java",
"comparison",
"null",
""
] |
I have several log files of events (one event per line). The logs can possibly overlap. The logs are generated on separate client machines from possibly multiple time zones (but I assume I know the time zone). Each event has a timestamp that was normalized into a common time (by instantianting each log parsers calendar... | 1. Read the first line from each of the log files
2. LOOP
a. Find the "earliest" line.
b. Insert the "earliest" line into the master log file
c. Read the next line from the file that contained the earliest line
You could check for duplicates between b and c, advancing the pointer for each of those files. | Sure - open every log file. Read in the first line for each into an array of 'current' lines. Then repeatedly pick the line with the lowest timestamp from the current array. Write it to the output, and read a new line from the appropriate source file to replace it.
Here's an example in Python, but it makes good pseudo... | Algorithm for merging large files | [
"",
"java",
"sorting",
"file",
"merge",
""
] |
What are the potential pros and cons of each of these queries given different databases, configurations, etc? Is there ever a time when one would be more efficient than the other? Vice versa? Is there an even better way to do it? Can you explain why?
Query 1:
```
SELECT
*
FROM
table_a, table_b, table_c
WHERE
t... | Same query, different revision of SQL spec. The query optimizer should come up with the same query plan for those. | Nope. I'm just sharing a large, overwhelmed database with some coworkers and am trying to come up with some ways to get more processor bang for our buck. I've been looking around online but haven't found a good explanation for some questions like this.
Sorry for sounding homework-y. I guess I spent too many years as a... | Comparing MySQL Cross and Inner Joins | [
"",
"mysql",
"sql",
""
] |
I am doing a project at the moment, and in the interest of code reuse, I went looking for a library that can perform some probabilistic accept/reject of an item:
i.e., there are three people (a, b c), and each of them have a probability P{i} of getting an item, where p{a} denotes the probability of a. These probabilit... | Would something like this do? Put all p{i}'s in the array, function will return an index to the person who gets the item. Executes in O(n).
```
public int selectPerson(float[] probabilies, Random r) {
float t = r.nextFloat();
float p = 0.0f;
for (int i = 0; i < probabilies.length; i++) {
p += prob... | Here is a Ruby implementation: <https://github.com/cantino/walker_method> | Opensource Implementation of the Alias Method | [
"",
"java",
"statistics",
"random",
"probability",
""
] |
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type:
Which is quicker and why?
```
switch(childNode.Name)
{
case "Bob":
break;
case "Jill":
break;
case "Marko":
break;
}
if(childNode is Bob)
{
}
elseif(childNode is Ji... | Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data.
The sim... | Firstly, you're comparing apples and oranges. You'd first need to compare switch on type vs switch on string, and then if on type vs if on string, and then compare the winners.
Secondly, this is the kind of thing OO was designed for. In languages that support OO, switching on type (of any kind) is a code smell that po... | What is quicker, switch on string or elseif on type? | [
"",
"c#",
"performance",
""
] |
When I launch the "mvn install" command, maven sometimes tries to download dependencies that it has already downloaded. That's expected for SNAPSHOT but why does maven do that for other JARs?
I know I can avoid that behavior by "-o" flag but I just wonder what the cause is. | I'd look for dependencies that don't have a specified version number. Maven will periodically check to make sure that it has the most up-to-date version of these artifacts. | This is probably not what you're seeing, but in the past I've had to manually install artifacts into my local repository and if you forget to include the -Dgenerate.pom=true option there will be no pom in the repo for that artifact and Maven will go out to central (and any other remote repos you have configured) to try... | Why does maven 2 try to download dependencies that I already have? | [
"",
"java",
"maven-2",
""
] |
I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times.
```
ID uniqueidentifier not null,
ThingID int NOT NULL,
PriceDateTime datetime NOT NULL,
Price decimal(18,4) NOT NULL
... | I think the only solution with your table structure is to work with a subquery:
```
SELECT *
FROM Thing
WHERE ID IN (SELECT max(ID) FROM Thing
WHERE ThingID IN (1,2,3,4)
GROUP BY ThingID)
```
(Given the highest ID also means the newest price)
However I suggest you add a "... | I would try something like the following subquery and forget about changing your data structures.
```
SELECT
*
FROM
Thing
WHERE
(ThingID, PriceDateTime) IN
(SELECT
ThingID,
max(PriceDateTime )
FROM
Thing
WHERE
ThingID IN (1,2,3,4)
GROUP BY
ThingID
)
```
**Edit** the above is ANSI SQ... | SQL Query to get latest price | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned?
```
#define is_this_type_signed (my_type) ...
``` | If what you want is a simple macro, this should do the trick:
```
#define is_type_signed(my_type) (((my_type)-1) < 0)
``` | In C++, use `std::numeric_limits<type>::is_signed`.
```
#include <limits>
std::numeric_limits<int>::is_signed - returns true
std::numeric_limits<unsigned int>::is_signed - returns false
```
See <https://en.cppreference.com/w/cpp/types/numeric_limits/is_signed>. | Macro to test whether an integer type is signed or unsigned | [
"",
"c++",
"c",
""
] |
I are using EJB 3 on a fairly large J2EE project, by default with Netbeans sets the persistent provider for the entity beans to TopLink. There is the option to change the provider to one of the following or even add a new persistence library:
* Hibernate
* KODO
* OpenJPA
Which persistence provider do you prefer to us... | Theres only two JPA providers I'd consider using:
If you want to stick to standard JPA I'd use EclipseLink. Whereas Toplink Essentials is the reference implementation of JPA 1.0, EclipseLink basically inherited the TopLink Essentials code and will be the reference implementation of JPA 2.0 (and bundled with Glassfish ... | I would strongly recommend Hibernate for the following reasons:
* The most widely used and respected open source persistence layer in the Java world; huge active community and lots of use in high volume mission critical applications.
* You don't tie yourself to J2EE or a specific vendor at all should you wish to go a ... | Which EJB 3 persisent provider should I use? | [
"",
"java",
"orm",
"jpa",
"jakarta-ee",
""
] |
I'm experiencing an issue on a test machine running Red Hat Linux (kernel version is 2.4.21-37.ELsmp) using Java 1.6 (1.6.0\_02 or 1.6.0\_04). The problem is, once a certain number of threads are created in a single thread group, the operating system is unwilling or unable to create any more.
This seems to be specific... | Updating the kernel to a newer version (2.6.something) with NPTL threading fixed this. | Have you looked at [this resource](http://people.redhat.com/alikins/system_tuning.html#threads)?
It states that you should be able run thread-limit to find the maximum number of threads and can tweak it by compiling glibc. | Low Java single process thread limit in Red Hat Linux | [
"",
"java",
"linux",
"redhat",
""
] |
I would like to implement a data access object pattern in C++, but preferably without using multiple inheritance and/or boost (which my client does not like).
Do you have any suggestions? | OTL (otl.sourceforge.net) is an excellent C++ database library. It's a single include file so doesn't have all the complexity associated (rightly or wrongly!) with Boost.
In terms of the DAO itself, you have many options. The simplest that hides the database implementation is just to use C++ style interfaces and imple... | A quick google search on data access object design patterns will return at least 10 results on the first page that will be useful. The most common of these is the abstract interface design as already shown by Jeff Foster. The only thing you may wish to add to this is a data access object factory to create your objects.... | data access object pattern implementation | [
"",
"c++",
"design-patterns",
"oop",
""
] |
We want to maintain 3 webservices for the different steps of deployment, but how do we define in our application which service to use? Do we just maintain 3 web references and ifdef the uses of them somehow? | As others have mentioned you'll want to stash this information in a config file. In fact, I'd suggest using a different configuration file for each environment. This will address the inevitable problem of having multiple settings for each environment, e.g. you might have separate settings for the web service URL and we... | Don't maintain the differences in code, but rather through a configuration file. That way they're all running the same code, just with different configuration values (ie. port to bind to, hostname to answer to, etc.) | How do you maintain separate webservices for dev/stage/production | [
"",
"c#",
".net",
"asp.net",
"web-services",
""
] |
During a long compilation with Visual Studio 2005 (version 8.0.50727.762), I sometimes get the following error in several files in some project:
```
fatal error C1033: cannot open program database 'v:\temp\apprtctest\win32\release\vc80.pdb'
```
(The file mentioned is either `vc80.pdb` or `vc80.idb` in the project's t... | It is possible that an antivirus or a similar program is touching the pdb file on write - an antivirus is the most likely suspect in this scenario. I'm afraid that I can only give you some general pointers, based on my past experience in setting nightly builds in our shop. Some of these may sound trivial, but I'm inclu... | We've seen this a lot at my site too. [This explanation](http://graphics.ethz.ch/~peterkau/coding.php), from Peter Kaufmann, seems to be the most plausible based on our setup:
**When building a solution in Visual Studio 2005, you get errors like fatal error C1033: cannot open program database 'xxx\debug\vc80.pdb'. How... | Compilation fails randomly: "cannot open program database" | [
"",
"c++",
"visual-studio",
"visual-studio-2005",
"compiler-errors",
"nightly-build",
""
] |
If I start a process via Java's [ProcessBuilder](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html) class, I have full access to that process's standard in, standard out, and standard error streams as Java `InputStreams` and `OutputStreams`. However, I can't find a way to seamlessly connect those stre... | You will need to copy the [Process](http://java.sun.com/javase/6/docs/api/java/lang/Process.html) out, err, and input streams to the System versions. The easiest way to do that is using the [IOUtils](http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html) class from the Commons IO package. The [cop... | A variation on John's answer that compiles and doesn't require you to use Commons IO:
```
private static void pipeOutput(Process process) {
pipe(process.getErrorStream(), System.err);
pipe(process.getInputStream(), System.out);
}
private static void pipe(final InputStream src, final PrintStream dest) {
ne... | Starting a process with inherited stdin/stdout/stderr in Java 6 | [
"",
"java",
"io",
"process",
"pipe",
""
] |
I'm fairly new to the world of versioning but would like to introduce Subversion into our small development team as we're finding that more and more we are working on the same projects/files. We primarily code in `PHP` on a `LAMP` environment (Red Hat Enterprise).
What I'm looking for are some starting points to get m... | It depends on what version of RHEL you are running. Setting up Subversion in general is very easy you just have to install the binaries and run svnserve or adapt the Apache configuration.
1. Get it: <http://subversion.tigris.org/getting.html>
2. Install it
3. `svnadmin create --fs-type=fsfs`
After that you have a rep... | On a RHEL system, the easiest way to install subversion is by using yum:
yum install subversion | Setting up Subversion on a Red Hat system | [
"",
"php",
"svn",
"redhat",
""
] |
Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version? | I don´t know if it is correct usage, but I think you can force a reload of the css file using a query string:
```
<link href="mystyle.css?SOME_UNIQUE_TEXT" type="text/css" rel="stylesheet" />
```
I remember I used this method years ago to force a reload of a web-cam image, but time has probably moved on... | Without using js, you can just keep the css filename in a session variable. When a request is made to the Main Page, you simply compose the css link tag with the session variable name.
Being the ccs file name different, you force the broswer to download it without needing to check what was previusly loaded in the brow... | Force browser to use new CSS | [
"",
"c#",
"asp.net",
"css",
"master-pages",
""
] |
I administrate several Oracle Apps environment, and currently check profile options in lots of environments by loading up forms in each environment, and manually checking each variable, which requires a lot of time.
Is there a snippet of code which will list profile options and at what level and who they are applied t... | You'll want to query `APPLSYS.FND_PROFILE_OPTIONS` and `FND_PROFILE_OPTION_VALUES`.
For a comprehensive script that you can pick up the SQL from, look here:
<http://tipsnscripts.com/?p=16> | I hope this will help you get more granular information when you try to track down changes by users.
```
SELECT FP.LEVEL_ID "Level ID",
FPO.PROFILE_OPTION_NAME "PROFILE NAME",
FP.LEVEL_VALUE "LEVEL VALUE",
DECODE (FP.LEVEL_ID,
10001,
'SITE',
10002,
'A... | How do I list Oracle Apps profile options in PL/SQL? | [
"",
"c#",
"oracle",
"configuration",
""
] |
We are writing a complex rich desktop application and need to offer flexibility in reporting formats so we thought we would just expose our object model to a scripting langauge. Time was when that meant VBA (which is still an option), but the managed code derivative VSTA (I think) seems to have withered on the vine.
W... | I've used [CSScript](http://www.csscript.net/) with amazing results. It really cut down on having to do bindings and other low level stuff in my scriptable apps. | Personally, I'd use C# as the scripting language. The .NET framework (and Mono, thanks Matthew Scharley) actually includes the compilers for each of the .NET languages in the framework itself.
Basically, there's 2 parts to the implementation of this system.
1. Allow the user to compile the code
This is relatively ... | What is the best scripting language to embed in a C# desktop application? | [
"",
"c#",
"scripting",
""
] |
How do I read text from the (windows) clipboard with python? | You can use the module called [win32clipboard](http://timgolden.me.uk/pywin32-docs/win32clipboard.html), which is part of [pywin32](https://github.com/mhammond/pywin32).
Here is an example that first sets the clipboard data then gets it:
```
import win32clipboard
# set clipboard data
win32clipboard.OpenClipboard()
w... | you can easily get this done through the built-in module [Tkinter](https://docs.python.org/2/library/tkinter.html) which is basically a GUI library. This code creates a blank widget to get the clipboard content from OS.
```
from tkinter import Tk # Python 3
#from Tkinter import Tk # for Python 2.x
Tk().clipboard_get(... | How do I read text from the Windows clipboard in Python? | [
"",
"python",
"windows",
"interop",
"clipboard",
""
] |
What is the best python framework to create distributed applications? For example to build a P2P app. | You could checkout [pyprocessing](http://pyprocessing.berlios.de/) which will be included in the standard library as of 2.6. It allows you to run tasks on multiple processes using an API similar to threading. | I think you mean "Networked Apps"? Distributed means an app that can split its workload among multiple worker clients over the network.
You probably want.
[Twisted](http://twistedmatrix.com/trac/) | Distributed python | [
"",
"python",
"distributed",
""
] |
Is there a difference in performance (in oracle) between
```
Select * from Table1 T1
Inner Join Table2 T2 On T1.ID = T2.ID
```
And
```
Select * from Table1 T1, Table2 T2
Where T1.ID = T2.ID
```
? | No! The same execution plan, look at these two tables:
```
CREATE TABLE table1 (
id INT,
name VARCHAR(20)
);
CREATE TABLE table2 (
id INT,
name VARCHAR(20)
);
```
The execution plan for the query using the inner join:
```
-- with inner join
EXPLAIN PLAN FOR
SELECT * FROM table1 t1
INNER JOIN table2 t2 ON t... | If the query optimizer is doing its job right, there should be no difference between those queries. They are just two ways to specify the same desired result. | Inner join vs Where | [
"",
"sql",
"performance",
"oracle",
""
] |
I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p>
Now I want to insert an element in to the text so that it will become:
<p>Hello <span id=span1>new</span> world!</p>
I need the span tag because I want to handle it later.Show or hide.
B... | Simply override any span styles. Set layout properties back to browser defaults and set formating to inherit from the parent:
```
span#yourSpan {
/* defaults */
position: static;
display: inline;
margin: 0;
padding: 0;
background: transparent;
border: none;
/* inherit from parent node */
font: inher... | Well, I don't know how married you are to using a <span> tag, but why not do this?
```
<p style="display: inline">Hello <p id="myIdValue" style="display: inline">new</p> World</p>
```
That way the inserted html retains the same styling as the outer, and you can still have a handle to it, etc. Granted, you will have t... | How to insert a text-like element into document using javascript and CSS? | [
"",
"javascript",
"css",
""
] |
This may seem like a daft question, but i was wondering about how to use MVC frameworks on hosted servers.
I am playing about (albeit slowly) at home with the RoR on Ubuntu and understand that if i want to do a live site then i need hosting with Rails and Ruby.
However, what happens about the PHP frameworks. For exam... | Not every framework needs things installed or configured via the command line or even the php.ini file. I believe CodeIgnitor is like this - you can just put the path to the base CI directory in the path and off you go. I'm sure there's documentation about how to use symfony on a hosting solution. In fact, [this docume... | Most MVC frameworks\* (Kohana, Zend Framework, for example) can be installed anywhere on the server. The front controller in the document root then specifies where it is, and loads it from there. So basically, you put the framework directory somewhere, and then have your front controller load it. ZF and Kohana in parti... | MVC frameworks on hosted servers | [
"",
"php",
"model-view-controller",
"symfony1",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.