Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
First off, I'm working on an app that's written such that some of your typical debugging tools can't be used (or at least I can't figure out how :).
JavaScript, html, etc are all "cooked" and encoded (I think; I'm a little fuzzy on how the process works) before being deployed, so I can't attach VS 2005 to ie, and fire... | setAttribute is unreliable in IE. It treats attribute access and object property access as the same thing, so because the DOM property for the 'class' attribute is called 'className', you would have to use that instead on IE.
This bug is fixed in the new IE8 beta, but it is easier simply to use the DOM Level 1 HTML pr... | Have you tried changing this line
```
tblRows[i].style.display = (rowVisible) ? "none" : "";
```
to something like
```
tblRows[i].style.display = (rowVisible) ? "none" : "table-row";
```
or
```
tblRows[i].style.display = (rowVisible) ? "none" : "auto";
``` | IE Javascript Clicking Issue | [
"",
"javascript",
"internet-explorer",
"click",
""
] |
OK, so practically every database based application has to deal with "non-active" records. Either, soft-deletions or marking something as "to be ignored". I'm curious as to whether there are any radical alternatives thoughts on an `active' column (or a status column).
For example, if I had a list of people
```
CREATE... | You partition the table on the active flag, so that active records are in one partition, and inactive records are in the other partition. Then you create an active view for each table which automatically has the active filter on it. The database query engine automatically restricts the query to the partition that has t... | Well, to ensure that you only draw active records in most situations, you could create views that only contain the active records. That way it's much easier to not leave out the active part. | `active' flag or not? | [
"",
"sql",
"mysql",
"postgresql",
""
] |
Is there a way to determine how many capture groups there are in a given regular expression?
I would like to be able to do the follwing:
```
def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(... | ```
def num_groups(regex):
return re.compile(regex).groups
``` | ```
f_x = re.search(...)
len_groups = len(f_x.groups())
``` | Find out number of capture groups in Python regular expressions | [
"",
"python",
"regex",
""
] |
I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 ... | By using the [wordwrap](http://www.php.net/wordwrap) function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:
```
substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
```
One... | This will return the first 200 characters of words:
```
preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 201));
``` | How to Truncate a string in PHP to the word closest to a certain number of characters? | [
"",
"php",
"string",
"function",
""
] |
I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this', 'is', 'a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well,... | You want `split`, from the built-in [`shlex`](https://docs.python.org/library/shlex.html) module.
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
This should do exactly what you want.
If you want to preserve the quotation marks, then you can pass the `posix=False` kwarg.
```
>>... | Have a look at the `shlex` module, particularly `shlex.split`.
```
>>> import shlex
>>> shlex.split('This is "a test"')
['This', 'is', 'a test']
``` | Split a string by spaces -- preserving quoted substrings -- in Python | [
"",
"python",
"regex",
""
] |
I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:
```
<asp:Button ID="btnShowDetails" runat="server" CausesValidation="false"
CommandName="Details" Text="Order Details"
onClie... | I believe the way to do it is
> ```
> onClientClick=<%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %>
> ``` | I like @[AviewAnew](https://stackoverflow.com/questions/102343/including-eval-bind-values-in-onclientclick-code#102373)'s suggestion, though you can also just write that from the code-behind by wiring up and event to the grid views ItemDataBound event. You'd then use the FindControl method on the event args you get to ... | Including eval / bind values in OnClientClick code | [
"",
"asp.net",
"javascript",
"visual-studio",
""
] |
Given an array of **n** Objects, let's say it is an **array of strings**, and it has the following values:
```
foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";
```
What do I have to do to delete/remove all the strings/objects equal to **"a"** in the array? | [If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]
To flesh out [Dustman's idea](https://stackoverflow.com/a/112507/13):
```
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);... | An alternative in Java 8:
```
String[] filteredArray = Arrays.stream(array)
.filter(e -> !e.equals(foo)).toArray(String[]::new);
``` | How do I remove objects from an array in Java? | [
"",
"java",
"arrays",
"data-structures",
"data-manipulation",
""
] |
Do you still use session or entity EJBs in your project? Why? | EJB3 is a **vast** improvement over previous versions. It's still *technically* the standard server-side implementation toolset for JavaEE and since it now has none of the previous baggage (thanks to annotations and Java Persistence), is quite usable and being deployed as we speak. As one commenter noted, JBoss SEAM is... | We're working with EJB here and it works quite well with JBoss Seam and JSF, Faclets and MyFaces Trinidad. Good UI, Templating, AJAX and stable production 24/7 running on JBoss 4.2.
It's a good stack for business processes, workflows, messageing, webservices and ui control. Fast delivery of features, easy programming ... | Is EJB still alive? | [
"",
"java",
"jakarta-ee",
"ejb",
""
] |
I have successfully connected to an Oracle database (10g) from C# (Visual Studio 2008) by downloading and installing the client administration tools and Visual Studio 2008 on my laptop.
The installation footprint for Oracle Client tools was over 200Mb, and quite long winded.
Does anyone know what the minimum workable... | You need an Oracle Client to connect to an Oracle database. The easiest way is to install the [Oracle Data Access Components](http://www.oracle.com/technology/software/tech/windows/odpnet/index.html).
To minimize the footprint, I suggest the following :
* Use the Microsoft provider for Oracle (System.Data.OracleClien... | I use the method suggested by Pandicus above, on Windows XP, using ODAC 11.2.0.2.1. The steps are as follows:
1. Download the "ODAC 11.2 Release 3 (11.2.0.2.1) with Xcopy Deployment" package from oracle.com (53 MB), and extract the ZIP.
2. Collect the following DLLs: oci.dll (1 MB), oraociei11.dll (130 MB!), OraOps11w... | What is the minimum client footprint required to connect C# to an Oracle database? | [
"",
"c#",
"oracle",
"client",
""
] |
First of all, this question regards MySQL 3.23.58, so be advised.
I have 2 tables with the following definition:
```
Table A: id INT (primary), customer_id INT, offlineid INT
Table B: id INT (primary), name VARCHAR(255)
```
Now, table A contains in the range of 65k+ records, while table B contains ~40 records. In a... | You could try making sure there are covering indexes defined on each table. A covering index is just an index where each column requested in the select or used in a join is included in the index. This way, the engine only has to read the index entry and doesn't have to also do the corresponding row lookup to get any re... | I'm going to guess that your main problem is that you are using such an old version of MySQL. Maybe MySQL 3 doesn't like the COUNT(DISTINCT()).
Alternately, it might just be system performance. How much memory do you have?
Still, MySQL 3 is really old. I would at least put together a test system to see if a newer ver... | Optimize SQL query on large-ish table | [
"",
"mysql",
"sql",
"optimization",
""
] |
C++ seems to be rather grouchy when declaring templates across multiple files. More specifically, when working with templated classes, the linker expect all method definitions for the class in a single compiler object file. When you take into account headers, other declarations, inheritance, etc., things get really mes... | > Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files?
Yes; don't.
The C++ spec permits a compiler to be able to "see" the entire template (declaration *and* definition) at the point of instantiation, and (due to the complexities of any imple... | Across how many files? If you just want to separate class definitions from implementation then try [this article](https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl) in the C++ faqs. That's about the only way I know of that works at the moment, but some IDEs (Eclipse CDT for example) won't link this method pr... | Templates spread across multiple files | [
"",
"c++",
"templates",
""
] |
For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows.
I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will b... | <http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()>
```
File[] roots = File.listRoots();
for(int i = 0; i < roots.length ; i++)
System.out.println("Root["+i+"]:" + roots[i]);
```
google: list drives java, first hit:-) | Looking "everywhere" can be very messy.
Look at a CD-rom drive, and it spins up. That can be very noisy.
Look at a network drive, and it may be very slow. Maybe the server is down, and you may need to wait for minutes until it times out.
Maybe (for Windows-machines) you should just look in the start-menu. If nothing... | Find all drive letters in Java | [
"",
"java",
"windows",
""
] |
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class.
Two Questions:
1. I can't se... | Answers:
*>1. I can't seem to get the input loop to work out, what's the best practice for doing so.*
I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read:
*while the read number is not end signal and count is lower than limit: do.*
*>2. Wha... | What you need in your loop condition is:
```
while ( input.get( input.size()-1 ) != end_signal );
```
What you're doing is decrementing the counter variable.
Also you should declare the `ArrayList` like so:
```
ArrayList<Double> list = new ArrayList<Double>();
```
This makes the list type-specific and allows the c... | ArrayList in Java and inputting | [
"",
"java",
"arrays",
"arraylist",
""
] |
I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys? | How about something like this:
```
def itersorted(d):
for key in sorted(d):
yield d[key]
``` | By far the easiest approach, and almost certainly the fastest, is something along the lines of:
```
def sorted_dict(d):
keys = d.keys()
keys.sort()
for key in keys:
yield d[key]
```
You can't sort without fetching all keys. Fetching all keys into a list and then sorting that list is the most effic... | Sorting a dict on __iter__ | [
"",
"python",
"optimization",
"refactoring",
""
] |
The background should be transparent, but the text should not. | Enso is open source too.
You can directly peek at they source code.
<http://code.google.com/p/enso/>
Let us know how they do it when you find out!.
**UPDATE**
It looks like they use something called Cairo. If you can link it from C# you're done. | By making an "Enso style" application you mean the Enso launcher?
Here is a screenshot of it:
[alt text http://enscreenshots.softonic.com/s2en/68000/68880/3\_ensolauncher03.jpg](http://enscreenshots.softonic.com/s2en/68000/68880/3_ensolauncher03.jpg)
I would suggest at looking at the open-source C# [Cropper](http://w... | How can I make a Enso style application in C# | [
"",
"c#",
"winforms",
"windows-xp",
""
] |
I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL:
```
SELECT f.*
FROM Foo f
WHERE f.FooId IN (
SELECT fb.FooId
FROM FooBar fb
WHERE fb.BarId = 1000
)
```
Any help would be gratefully received. | Have a look at [this article](http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql). Basically, if you want to get the equivalent of IN, you need to construct an inner query first, and then use the Contains() method. Here's my attempt at translating:
```
var innerQuery = from fb in FoorBar where fb... | # General way to implement IN in LINQ to SQL
```
var q = from t1 in table1
let t2s = from t2 in table2
where <Conditions for table2>
select t2.KeyField
where t2s.Contains(t1.KeyField)
select t1;
```
# General way to implement EXISTS in LINQ to SQL
```
var q... | How can you handle an IN sub-query with LINQ to SQL? | [
"",
"sql",
"linq",
"linq-to-sql",
""
] |
i have a list of products that are being displayed in particular order. store admin can reassign the display order, by moving the "hot" items to the top of the list. what's the best way of implementing the admin functionality **UI** [asp.net C#]? Products table has a [displayOrder(int)] filed which determines the displ... | using AJAX you could implement a Reoder list control you can find more information here <http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ReorderList/ReorderList.aspx>
Mauro
[http://www.brantas.co.uk](http://www.brantas.co.uk/) | You need a Rank field for each product (which could also be the DisplayOrder field).
When the administrator ups or downs a product, update the rank value.
When you need to list the products, do a select query which sorts in DESC order of rank. | Implementing user defined display order UI | [
"",
"c#",
"asp.net",
"visual-studio-2005",
""
] |
I am looking for a .NET implementation of a priority queue or heap data structure
> Priority queues are data structures that provide more flexibility than simple sorting, because they allow new elements to enter a system at arbitrary intervals. It is much more cost-effective to insert a new job into a priority queue t... | I like using the `OrderedBag` and `OrderedSet` classes in [PowerCollections](http://www.codeplex.com/PowerCollections) as priority queues. | You might like IntervalHeap from the [C5 Generic Collection Library](http://www.itu.dk/research/c5/). To quote the [user guide](https://www.itu.dk/research/c5/latest/ITU-TR-2006-76.pdf)
> Class `IntervalHeap<T>` implements interface `IPriorityQueue<T>` using an interval heap stored as an array of pairs. The `FindMin` ... | Priority queue in .Net | [
"",
"c#",
".net",
"data-structures",
"heap",
"priority-queue",
""
] |
I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings?
For example:
1. I have a user setting na... | @ozgur,
```
Settings.Default.Properties["property"].DefaultValue // initial value from config file
```
Example:
```
string foo = Settings.Default.Foo; // Foo = "Foo" by default
Settings.Default.Foo = "Boo";
Settings.Default.Save();
string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo"
string original... | Reading "Windows 2.0 Forms Programming", I stumbled upon these 2 useful methods that may be of help in this context:
[ApplicationSettingsBase.Reload](http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.reload.aspx)
[ApplicationSettingsBase.Reset](http://msdn.microsoft.com/en-us/librar... | Reading default application settings in C# | [
"",
"c#",
".net",
"winforms",
"application-settings",
""
] |
I'm a PHP developer and now I use [Notepad++](http://en.wikipedia.org/wiki/Notepad_%28software%29) for code editing, but lately I've been searching for an IDE to ease my work.
I've looked into [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29), [Aptana Studio](http://en.wikipedia.org/wiki/Aptana#Aptana_Stu... | Are you sure you're looking for an IDE? The features you're describing, along with the impression of being too complicated that you got from e.g. Aptana, suggest that perhaps all you really want is a good editor with syntax highlighting and integration with some common workflow tools. For this, there are tons of option... | For PHP I would recommend [PhpStorm](http://www.jetbrains.com/phpstorm/).
It supports FTP/SFTP synchronization, integrates well with [Subversion](http://en.wikipedia.org/wiki/Apache_Subversion), [CVS](http://en.wikipedia.org/wiki/Concurrent_Versions_System), [Mercurial](http://en.wikipedia.org/wiki/Mercurial) and even... | What is the best IDE for PHP? | [
"",
"php",
"ide",
""
] |
I'm used to Atlas where the preferred (from what I know) method is to use XML comments such as:
```
/// <summary>
/// Method to calculate distance between two points
/// </summary>
///
/// <param name="pointA">First point</param>
/// <param name="pointB">Second point</param>
///
function calculatePointDistance(point... | There's [JSDoc](https://jsdoc.app/)
```
/**
* Shape is an abstract base class. It is defined simply
* to have something to inherit from for geometric
* subclasses
* @constructor
*/
function Shape(color){
this.color = color;
}
``` | The simpler the better, comments are good, use them :)
```
var something = 10; // My comment
/*
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
nisi ut aliquip ex ea commodo consequa... | What is the preferred method of commenting JavaScript objects and methods? | [
"",
"javascript",
"comments",
""
] |
What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new `Array` with the same strings but in a random order.
Please include a C# example in your answer. | First, you should use the most upvoted answer to this question so far, which is <https://stackoverflow.com/a/110570/1757994>.
You can shuffle using LINQ.
`var myShuffledArray = myArray.Shuffle()`.
Add the following code as a file called `EnumerableExtensions.cs` to your project:
```
public static class EnumerableEx... | The following implementation uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) AKA the Knuth Shuffle. It runs in O(n) time and shuffles in place, so is better performing than the 'sort by random' technique, although it is more lines of code. See [here](https://web.archive.org... | Best way to randomize an array with .NET | [
"",
"c#",
".net",
"algorithm",
"sorting",
"random",
""
] |
I would like to wipe out all data for a specific kind in Google App Engine. What is the
best way to do this?
I wrote a delete script (hack), but since there is so much data is
timeout's out after a few hundred records. | The [official answer](http://groups.google.com/group/google-appengine/browse_thread/thread/ec0800a3ca92fe69#) from Google is that you have to delete in chunks spread over multiple requests. You can use AJAX, [meta refresh](http://en.wikipedia.org/wiki/Meta_refresh), or request your URL from a script until there are no ... | I am currently deleting the entities by their key, and it seems to be faster.
```
from google.appengine.ext import db
class bulkdelete(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
try:
while True:
q = db.GqlQuery("SELECT __... | Delete all data for a kind in Google App Engine | [
"",
"python",
"google-app-engine",
""
] |
Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable. | First download the [JavaMail API](https://java.net/projects/javamail/pages/Home) and make sure the relevant jar files are in your classpath.
Here's a full working example using GMail.
```
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME =... | Something like this (sounds like you just need to change your SMTP server):
```
String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.por... | How can I send an email by Java application using GMail, Yahoo, or Hotmail? | [
"",
"java",
"email",
"gmail",
"jakarta-mail",
"mail-server",
""
] |
I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.
For example 5 would be converted to "101" and stored as a varchar. | Following could be coded into a function. You would need to trim off leading zeros to meet requirements of your question.
```
declare @intvalue int
set @intvalue=5
declare @vsresult varchar(64)
declare @inti int
select @inti = 64, @vsresult = ''
while @inti>0
begin
select @vsresult=convert(char(1), @intvalue % ... | Actually this is REALLY SIMPLE using plain old SQL. Just use bitwise ANDs. I was a bit amazed that there wasn't a simple solution posted online (that didn't invovled UDFs). In my case I really wanted to check if bits were on or off (the data is coming from dotnet eNums).
Accordingly here is an example that will give y... | SQL Server Convert integer to binary string | [
"",
"sql",
"sql-server",
""
] |
I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.
I.e., the same script is included on `/`, `/help`, `/whatever`, and so on, while it will always need to request from `/d... | For this I like to put `<link>` elements in the page's `<head>`, containing the URLs to use for requests. They can be generated by your server-side language so they always point to the right view:
```
<link id="link-action-1" href="${reverse_url ('action_1')}"/>
```
becomes
```
<link id="link-action-1" href="/my/web... | `document.location.href` will give you the current URL, which you can then manipulate using JavaScript's string functions. | Relative urls for Javascript files | [
"",
"javascript",
"html",
"url",
""
] |
Given a source color of any hue by the system or user, I'd like a simple algorithm I can use to work out a lighter or darker variants of the selected color. Similar to effects used on Windows Live Messenger for styling the user interface.
Language is C# with .net 3.5.
**Responding to comment:** Color format is (Alpha... | Simply multiply the RGB values by the amount you want to modify the level by. If one of the colors is already at the max value, then you can't make it any brighter (using HSV math anyway.)
This gives the exact same result with a lot less math as switching to HSV and then modifying V. This gives the same result as swit... | In [XNA there is the `Color.Lerp` static method](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.color.lerp.aspx) that does this as the difference between two colours.
`Lerp` is a mathematical operation between two floats that changes the value of the first by a ratio of the difference between... | How do I determine darker or lighter color variant of a given color? | [
"",
"c#",
"colors",
""
] |
Basically, growl notifications (or other callbacks) when tests break or pass. **Does anything like this exist?**
If not, it should be pretty easy to write.. Easiest way would be to..
1. run `python-autotest myfile1.py myfile2.py etc.py`
* Check if files-to-be-monitored have been modified (possibly just if they've ... | I found [autonose](https://github.com/gfxmonk/autonose) to be pretty unreliable but [sniffer](http://pypi.python.org/pypi/sniffer/0.2.3) seems to work very well.
```
$ pip install sniffer
$ cd myproject
```
Then instead of running "nosetests", you run:
```
$ sniffer
```
Or instead of `nosetests --verbose --with-doc... | [autonose](http://github.com/gfxmonk/autonose/tree/master) created by [gfxmonk](http://gfxmonk.net/):
> Autonose is an autotest-like tool for python, using the excellent nosetest library.
>
> autotest tracks filesystem changes and automatically re-run any changed tests or dependencies whenever a file is added, removed... | Is there something like 'autotest' for Python unittests? | [
"",
"python",
"testing",
""
] |
I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.
I can't forsee any problem with making these methods virtual but I was wondering wha... | Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider:
```
class Base {
public Base() {
InitializeComponent();
}
protected virtual void InitializeComponent() {
...
... | * If you have users that override your virtual methods you can't seal them again without breaking code.
* Any virtual methods you call from the constructor may fall down to derived implementations and if they don't call the base method and the constructor depends on it, the object may be in an invalid state | What are the dangers of making a method virtual? | [
"",
"c#",
"unit-testing",
"mocking",
"virtual-functions",
""
] |
I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a `SQL server 2000` query.
```
SELECT RECORD_CREATED_DA... | If it's not stored as a field, the info is *lost* after the transaction log recycles (typically daily), and maybe even sooner. | No, unfortunately date of insert or last update are not automatically stored with each record.
To do that, you need to create two **datetime** columns in your table (e.g. **CreatedOn**, **UpdatedOn**) and then in an **INSERT** trigger set the **CreatedOn = getdate()** and in the **UPDATE** trigger set the **UpdatedOn ... | SQL Server 2000 Function for record created datetime | [
"",
"sql",
"sql-server",
""
] |
I have the following enum:
```
public enum Status implements StringEnum{
ONLINE("on"),OFFLINE("off");
private String status = null;
private Status(String status) {
this.status = status;
}
public String toString() {
return this.status;
}
public static Status find(String... | It's not possible to specify either constructors or static methods in an interface. For a good, concise explanation, check out this article: [No static methods in interfaces](http://zoom.z3950.org/bind/java/comment/static.html) | Enums already have a [valueOf()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)) (your find method) method. And "toString()" is a java.lang.Object method, so, every class will have that, in other words, you can't force it! I can't see the value of enforcing a co... | How to build interface for such enum | [
"",
"java",
"interface",
"enums",
""
] |
Are there any libraries (3rd party or built-in) in `PHP` to calculate text diffs? | What sort of diffs? File diffs? There is [array\_diff()](http://php.net/array_diff) which acts on arrays. Then there is also [xdiff](http://php.net/manual/en/book.xdiff.php), which "enables you to create and apply patch files containing differences between different revisions of files.". The latter acts on files or str... | it depends exactly what you mean and what you want to do but there is
[PEAR Text\_Diff](http://pear.php.net/package/Text_Diff) - Engine for performing and rendering text diffs | Calculate text diffs in PHP | [
"",
"php",
"diff",
""
] |
Programming PHP in Eclipse PDT is predominately a joy: code completion, templates, method jumping, etc.
However, one thing that drives me crazy is that I can't get my lines in PHP files to word wrap so on long lines I'm typing out indefinitely to the right.
I click on Windows|Preferences and type in "wrap" and get:
... | This has really been one of the most desired features in Eclipse. It's not just missing in PHP files-- it's missing in the IDE. Fortunately, from Google Summer of Code, we get this plug-in [Eclipse Word-Wrap](http://ahtik.com/blog/projects/eclipse-word-wrap/)
To install it, add the following update site in Eclipse:
[... | [Eclipse Word-Wrap Plug-In](http://dev.cdhq.de/eclipse/word-wrap/) by Florian Weßling works well in Eclispe PDT (3.0.2).
**Installation and update sites**
*It is recommended to restart Eclipse with* `-clean` *option immediately after installation.*
Eclipse Indigo 3.7: <http://dev.cdhq.de/eclipse/updatesite/indigo/> ... | How can I get word wrap to work in Eclipse PDT for PHP files? | [
"",
"php",
"eclipse",
"eclipse-pdt",
"word-wrap",
""
] |
I'm working for a customer with a huge legacy codebase consisting of various Java en JSP based applications.
Most querying is done using the home-build 'orm' system. Some applications use Plain Old JDBC. Some applications are based on Hibernate (yes HQL build with plus signs is a potential problem as well). Some of th... | I would recommend [FindBugs](http://findbugs.sourceforge.net) (there is also an eclipse plugin) which can track down these issues and many more.
We are using it at work, it's fast and it's worth the money (as in free). We've solved some common problems with its help. | I'd write some searches or load up an IDE that looked for use of java.sql.Statement as opposed to PreparedStatement. | Find potential SQL inject problems in Java/JSP code | [
"",
"java",
"jsp",
"security",
"sql-injection",
""
] |
I've been reading a little about temporary tables in MySQL but I'm an admitted newbie when it comes to databases in general and MySQL in particular. I've looked at some examples and the MySQL documentation on how to create a temporary table, but I'm trying to determine just how temporary tables might benefit my applica... | Temporary tables are often valuable when you have a fairly complicated SELECT you want to perform and then perform a bunch of queries on that...
You can do something like:
```
CREATE TEMPORARY TABLE myTopCustomers
SELECT customers.*,count(*) num from customers join purchases using(customerID)
join items using(i... | First a disclaimer - my job is reporting so I wind up with far more complex queries than any normal developer would. If you're writing a simple CRUD (Create Read Update Delete) application (this would be most web applications) then you really don't want to write complex queries, and you are probably doing something wro... | How can my application benefit from temporary tables? | [
"",
"sql",
"mysql",
""
] |
I have a constructor like as follows:
```
public Agent(){
this.name = "John";
this.id = 9;
this.setTopWorldAgent(this, "Top_World_Agent", true);
}
```
I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By... | ~~You can pass this to methods, but setTopWorldAgent() cannot be abstract. You can't make a virtual call in the constructor.~~
~~In the constructor of an object, you can call methods defined in that object or base classes, but you cannot expect to call something that will be provided by a derived class, because parts ... | Out of curiousity, why are you passing 'this' to a member function of the same class? setTopWorldAgent() can use 'this' directly. It doesn't look like your constructor or setTopWorldAgent() are static, so I'm not sure why you would pass a member function something it already has access to.
Unless I'm missing something... | Using 'this' as a parameter to a method call in a constructor | [
"",
"java",
"constructor",
"methods",
"call",
"this",
""
] |
How do I get my C# program to sleep (pause execution) for 50 milliseconds? | ```
System.Threading.Thread.Sleep(50);
```
Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")
Just remove the `;` to make it work for VB.net as well. | There are basically 3 choices for waiting in (almost) any programming language:
1. **Loose waiting**
* Executing thread blocks for given time (= does not consume processing power)
* No processing is possible on blocked/waiting thread
* Not so precise
2. **Tight waiting** (also called tight loop)
* processo... | How do I get my C# program to sleep for 50 milliseconds? | [
"",
"c#",
"vb.net",
""
] |
This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed. | `foreach` does *not* require `IEnumerable`, contrary to popular belief. All it requires is a method `GetEnumerator` that returns any object that has the method `MoveNext` and the get-property `Current` with the appropriate signatures.
/EDIT: In your case, however, you're out of luck. You can trivially wrap your object... | Re: If foreach doesn't require an explicit interface contract, does it find GetEnumerator using reflection?
(I can't comment since I don't have a high enough reputation.)
If you're implying *runtime* reflection then no. It does it all compiletime, another lesser known fact is that it also check to see if the returned... | Does Class need to implement IEnumerable to use Foreach | [
"",
"c#",
"foreach",
"ienumerable",
""
] |
In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there:
(channels) \* (bits) \* (samples/s) \* (seconds) = (filesize)
Is there a simpler way - a free library, or something in the .net framework perhaps?
How would I do this ... | You may consider using the mciSendString(...) function (error checking is omitted for clarity):
```
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Sound
{
public static class SoundInfo
{
[DllImport("winmm.dll")]
private static extern uint mciSendString(
... | Download NAudio.dll
from the link
<https://www.dll-files.com/naudio.dll.html>
and then use this function
```
public static TimeSpan GetWavFileDuration(string fileName)
{
WaveFileReader wf = new WaveFileReader(fileName);
return wf.TotalTime;
}
```
you will get the Duration | How can I determine the length (i.e. duration) of a .wav file in C#? | [
"",
"c#",
"audio",
"compression",
""
] |
Now that it's clear [what a metaclass is](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception.... | A callable is anything that can be called.
The [built-in *callable* (PyCallable\_Check in objects.c)](http://svn.python.org/projects/python/trunk/Objects/object.c) checks if the argument is either:
* an instance of a class with a `__call__` method or
* is of a type that has a non null *tp\_call* (c struct) member whi... | From Python's sources [object.c](http://svn.python.org/view/python/trunk/Objects/object.c?rev=64962&view=markup):
```
/* Test whether an object can be called */
int
PyCallable_Check(PyObject *x)
{
if (x == NULL)
return 0;
if (PyInstance_Check(x)) {
PyObject *call = PyObject_GetAttrString(x, "_... | What is a "callable"? | [
"",
"python",
"callable",
""
] |
<http://en.wikipedia.org/wiki/Diamond_problem>
I know what it means, but what steps can I take to avoid it? | A practical example:
```
class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};
```
Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.
To solve this, we need virtual inheritance. It'... | I'd stick to using multiple inheritance of interfaces only. While multiple inheritance of classes is attractive sometimes, it can also be confusing and painful if you rely on it regularly. | How can I avoid the Diamond of Death when using multiple inheritance? | [
"",
"c++",
"multiple-inheritance",
""
] |
It looks quite easy to find such a tool for Java ([Checkstyle](http://checkstyle.sourceforge.net/), [JCSC](http://jcsc.sourceforge.net/)), but I can't seem to find one for C/C++. I am not looking for a lint-like static code analyzer, I only would like to check against coding standards like variable naming, capitalizati... | The only tool I know is [Vera](http://bitbucket.org/verateam/vera). Haven't used it, though, so can't comment how viable it is. [Demo](http://www.inspirel.com/vera/ce/demo.html) looks promising. | Google [c++lint](https://github.com/google/styleguide/tree/gh-pages/cpplint) from [Google code style guide](https://google.github.io/styleguide/cppguide.html). | A free tool to check C/C++ source code against a set of coding standards? | [
"",
"c++",
"c",
"coding-style",
""
] |
Greetings!
I'm working on wrapping my head around LINQ. If I had some XML such as this loaded into an XDocument object:
```
<Root>
<GroupA>
<Item attrib1="aaa" attrib2="000" attrib3="true" />
</GroupA>
<GroupB>
<Item attrib1="bbb" attrib2="111" attrib3="true" />
<Item attrib1="ccc"... | ```
XElement e = XElement.Parse(testStr);
string groupName = "GroupB";
var items = from g in e.Elements(groupName)
from i in g.Elements("Item")
select new {
attr1 = (string)i.Attribute("attrib1"),
attr2 = (string)i.Attribute("attrib2")
... | Yes, .Element() only returns the first matching element. You want .Elements() and you need to re-write your query somewhat:
```
var results = from group in l_theDoc.Root.Elements(groupName)
select new
{
items = from i in group.Elements("Item")
sel... | LINQ to XML Newbie Question: Returning More Than One Result | [
"",
"c#",
"linq-to-xml",
""
] |
For our online game, we have written tons of PHP classes and functions grouped by theme in files and then folders. In the end, we have now all our backend code (logic & DB access layers) in a set of files that we call **libs** and we include our libs in our GUI (web pages, presentation layer) using *include\_once('path... | * Manage all includes manually, only where needed
* Set your include\_path to only where it has to be, the default is something like .:/usr/lib/pear/:/usr/lib/php, point it only at where it has to be, php.net/set\_include\_path
* Don't use autoload, it's slow and makes APC and equivalent caches jobs a lot harder
* You ... | If you've done your programming in an object-oriented way, you can make use of the [autoload](https://www.php.net/autoload) function, which will load classes from their source files on-demand as you call them.
**Edit**: I noticed that someone downvoted both answers that referred to autoloading. Are we wrong? Is the ov... | How to create a fast PHP library? | [
"",
"php",
"include",
""
] |
I am attempting to update a project from ASP.NET MVC Preview 3 to Preview 5 and it seems that Controller.ReadFromRequest(string key) has been removed from the Controller class. Does anyone know of any alternatives to retrieving information based on an identifier from a form? | Looks like they've added controller.UpdateModel to address this issue, signature is:
```
UpdateModel(object model, string[] keys)
```
I haven't upgraded my app personally, so I'm not sure of the actual usage. I'll be interested to find out about this myself, as I'm using `controller.ReadFromRequest` as well. | Not sure where it went. You could roll your own extension though:
public static class MyBindingExtensions
{
```
public static T ReadFromRequest < T > (this Controller controller, string key)
{
// Setup
HttpContextBase context = controller.ControllerContext.HttpContext;
object val = null;
T result = d... | What is the replacement of Controller.ReadFromRequest in ASP.NET MVC? | [
"",
"c#",
"asp.net-mvc",
".net-3.5",
"entity-framework-ctp5",
""
] |
I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.
What I want to do is when a l... | I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.
```
function PreloadImage(imgSrc, callback){
var ... | You could show a static image that gives the [optical illusion of a spinny-wheel, like these](http://www.ritsumei.ac.jp/~akitaoka/saishin-e.html). | How to show a spinner while loading an image via JavaScript | [
"",
"javascript",
"jquery",
"dom",
""
] |
Is it possible to modify the title of the message box the confirm() function opens in JavaScript?
I could create a modal popup box, but I would like to do this as minimalistic as possible.
I would like to do something like this:
```
confirm("This is the content of the message box", "Modified title");
```
The default... | This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.
There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code. | YES YOU CAN do it!! It's a little tricky way ; ) (it almost works on ios)
```
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", 'data:text/plain,');
document.documentElement.appendChild(iframe);
if(window.frames[0].window.confirm("Are you sure?")){
// what to do if answer "YES"
}else{
/... | Changing the default title of confirm() in JavaScript? | [
"",
"javascript",
""
] |
I have a properties file in java, in which I store all information of my app, like logo image filename, database name, database user and database password.
I can store the password encrypted on the properties file. But, the key or passphrase can be read out of the jar using a decompiler.
Is there a way to store the d... | There are multiple ways to manage this. If you can figure out a way to have a user provide a password for a keystore when the application starts up the most appropriate way would be to encrypt all the values using a key, and store this key in the keystore. The command line interface to the keystore is by using keytool.... | You store a SHA1 hash of the password in your properties file. Then when you validate a users password, you hash their login attempt and make sure that the two hashes match.
This is the code that will hash some bytes for you. You can easily ger bytes from a String using the `getBytes()` method.
```
/**
* Returns... | Protect embedded password | [
"",
"java",
"security",
"passwords",
"embedded-resource",
"copy-protection",
""
] |
Ok so before I even ask my question I want to make one thing clear. I am currently a student at NIU for Computer Science and this does relate to one of my assignments for a class there. So if anyone has a problem read no further and just go on about your business.
Now for anyone who is willing to help heres the situat... | The problem with empty entries is in your while loop. If you get an empty string, you clean the next one, and add it without checking. Try changing:
```
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() == 0)
{
input >> s;
clean_entry(s, not_s);
}
mapz[not_s]++; //increment occurence
i... | Further improvements would be to
* declare variables only when you use them, and in the innermost scope
* use c++-style casts instead of the c-style (int) casts
* use empty() instead of length() == 0 comparisons
* use the prefix increment operator for the iterators (i.e. `++mapzIter`) | Cleaning a string of punctuation in C++ | [
"",
"c++",
""
] |
I have the following script, where the first and third `document.writeline` are static and **the second is generated**:
```
<script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'><\/sc" + "ript>");
document.write("<script language='jav... | I've found an answer more to my liking:
```
<script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'><\/sc" + "ript>");
document.write("<script defer language='javascript' type='text/javascript'>alert('during');<\/sc" + "ript>");
documen... | No, this is the behavior of Internet Explorer.
If you attach scripts dynamically, IE, Firefox, and Chrome will all download the scripts in an asynchronous manner.
Firefox and Chrome will wait till all of the async requests return and then will execute the scripts in the order that they are attached in the DOM but IE ... | JavaScript's document.write Inline Script Execution Order | [
"",
"javascript",
"cross-browser",
"browser",
""
] |
Is there a side effect in doing this:
C code:
```
struct foo {
int k;
};
int ret_foo(const struct foo* f){
return f.k;
}
```
C++ code:
```
class bar : public foo {
int my_bar() {
return ret_foo( (foo)this );
}
};
```
There's an `extern "C"` around the C++ code and each code is inside ... | This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.
There is one caveat here. There is *no guarantee* of... | I certainly not recommend using such weird subclassing. It would be better to change your design to use composition instead of inheritance.
Just make one member
> foo\* m\_pfoo;
in the bar class and it will do the same job.
Other thing you can do is to make one more class FooWrapper, containing the structure in itse... | Is it possible to subclass a C struct in C++ and use pointers to the struct in C code? | [
"",
"c++",
"c",
"gcc",
"extern-c",
""
] |
I have 2 arrays of 16 elements (chars) that I need to "compare" and see how many elements are equal between the two.
This routine is going to be used millions of times (a usual run is about 60 or 70 million times), so I need it to be as fast as possible. I'm working on C++ (C++Builder 2007, for the record)
Right now,... | UPDATE: This answer has been modified to make my comments match the source code provided below.
There is an optimization available if you have the capability to use SSE2 and popcnt instructions.
16 bytes happens to fit nicely in an SSE register. Using c++ and assembly/intrinsics, load the two 16 byte arrays into xmm ... | The key is to do the comparisons using the largest register your CPU supports, then fallback to bytes if necessary.
The below code demonstrates with using 4-byte integers, but if you are running on a SIMD architecture (any modern Intel or AMD chip) you could compare both arrays in one instruction before falling back t... | Fastest way to see how many bytes are equal between fixed length arrays | [
"",
"c++",
"arrays",
"optimization",
""
] |
How would one write a regular expression to use in Python to split paragraphs?
A paragraph is defined by two line breaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph.
I am using Python, so the solution can use Python's [regular expres... | Unfortunately there's no nice way to write "space but not a newline".
I think the best you can do is add some space with the `x` modifier and try to factor out the ugliness a bit, but that's questionable: `(?x) (?: [ \t\r\f\v]*? \n ){2} [ \t\r\f\v]*?`
You could also try creating a subrule just for the character class... | It is not a regexp, but it is really elegant:
```
from itertools import groupby
def paragraph(lines):
for group_separator, line_iteration in groupby(lines.splitlines(True), key = str.isspace):
if not group_separator:
yield ''.join(line_iteration)
for p in paragraph('p1\n\t\np2\t\n\tstill p2\t... | Python regular expression to split paragraphs | [
"",
"python",
"regex",
"parsing",
"text",
"split",
""
] |
I have a side project I do = in Java. It's a pretty straight-forward webapp. It runs in Tomcat on a Linux Server and uses a MySQL database. The majority of the code was written with the Spring Framework. It has a lot of Unit Tests in place. When I'm coding it's in Eclipse. When I deploy the application I run a few shel... | Your project does not sound like a project appropriate for Maven. You seem to have a working development environment. Why set up another one? It will just give you one more project file to maintain which breaks the good ol' [DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principle. | Maven would be a good fit for your project IMO. Maven is an all around build and deployment management tool. It's biggest strength is that it makes build scripts significantly eaiser to maintain than functionally comparable Ant files or shell scripts.
There are a lot of advantages to using maven the biggest being it's... | Thinking of learning Maven | [
"",
"java",
"maven-2",
""
] |
I am looking for a library that will allow me to look up the status of a windows service to verify that the service is started and running. I looked into the Sigar library, but it is GPL and therefor I cannot use it. A Commercial or BSD(ish) license is required as this will be bundled into commercial software. | If nothing else helps, try to think of a slightly different approach (if you can, of course), e.g.:
* There is a plenty of free/non-free software which does monitoring, including Windows service monitoring (e.g. nagios, Zabbix, etc.). These monitors typically have open API where your Java app could integrate into in a... | I don't think there is any pure-Java way to do this because some operating systems don't have the notion of "services" like Windows does. In our projects, we wrote a wrapper around calls to the "sc" command from the command line. To get the status of a service, you can do:
> sc \\some-computer query "my service name"
... | Is there any way, in java, to check on the status of a windows service? | [
"",
"java",
"windows-services",
"system-monitoring",
"system-status",
""
] |
In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application.
Thus myapp.war gets deployed to <http://example.com/myapp>.
The problem is that the webapp considers its "root" to be, well, "root", or simply "/", whereas HTML would consider t... | You can use JSTL for creating urls.
For example, `<c:url value="/images/header.jpg" />` will prefix the context root.
With CSS, this usually isn't an issue for me.
I have a web root structure like this:
/css
/images
In the CSS file, you then just need to use relative URLs (../images/header.jpg) and it doesn't ne... | For HTML pages, I just set the HTML `<base>` tag. Every relative link (i.e. not starting with scheme or `/`) will become relative to it. There is no clean way to grab it immediately by `HttpServletRequest`, so we need little help of JSTL here.
```
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@tagl... | Any clever ways of handling the context in a web app? | [
"",
"java",
"jsp",
"servlets",
"contextpath",
""
] |
PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature.
Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expec... | Actually for classes you can provide type hinting in PHP (5+).
```
<?php
class UsesBaseClass
{
function SetObject(InterfaceObject $obj)
{
}
}
?>
```
This will also work correctly with inheritance as you would expect it to.
As an aside, don't put the word 'object' in your class names... | as an addition to Eran Galperin's response you can also use the type hinting to force parameters to be arrays - not just objects of a certain class.
```
<?php
class MyCoolClass {
public function passMeAnArray(array $array = array()) {
// do something with the array
}
}
?>
```
As you can see you ca... | How do I prevent using the incorrect type in PHP? | [
"",
"php",
"oop",
"type-safety",
""
] |
How do I exit a script early, like the `die()` command in PHP? | ```
import sys
sys.exit()
```
details from the [`sys` module documentation](https://docs.python.org/2/library/sys.html#sys.exit):
> `sys.exit([arg])`
>
> Exit from Python. This is implemented by raising the
> [`SystemExit`](https://docs.python.org/2/library/exceptions.html#SystemExit "SystemExit") exception, so clean... | A simple way to terminate a Python script early is to use the built-in `quit()` function. There is no need to import any library, and it is efficient and simple.
Example:
```
#do stuff
if this == that:
quit()
``` | How do I terminate a script? | [
"",
"python",
"termination",
""
] |
I'm looking for an answer in MS VC++.
When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.
Example in pseudo code:
```
FunctionB()
{
...
throw e;
...
}
FunctionA()
{
...
Funct... | If you are just interested in where the exception came from, you could just write a simple macro like
```
#define throwException(message) \
{ \
std::ostringstream oss; \
oss << __FILE __ << " " << __LINE__ << " " \
<< __FUNC__ << " " << message; \
throw... | You pointed to a breakpoint in the code. Since you are in the debugger, you could set a breakpoint on the constructor of the exception class, or set Visual Studio debugger to break on all thrown exceptions (Debug->Exceptions Click on C++ exceptions, select thrown and uncaught options) | Finding out the source of an exception in C++ after it is caught? | [
"",
"c++",
"visual-studio",
"winapi",
"exception",
"visual-c++",
""
] |
Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.
For some reason I thought the following might work:
```
enum MY_ENUM : unsigned __int64
{
LARGE_VALUE = 0x1000... | I don't think that's possible with C++98. The underlying representation of enums is up to the compiler. In that case, you are better off using:
```
const __int64 LARGE_VALUE = 0x1000000000000000L;
```
As of C++11, it is possible to use enum classes to specify the base type of the enum:
```
enum class MY_ENUM : unsig... | C++11 supports this, using this syntax:
```
enum class Enum2 : __int64 {Val1, Val2, val3};
``` | 64 bit enum in C++? | [
"",
"c++",
"enums",
"64-bit",
""
] |
I have code that references a web service, and I'd like the address of that web service to be dynamic (read from a database, config file, etc.) so that it is easily changed. One major use of this will be to deploy to multiple environments where machine names and IP addresses are different. The web service signature wil... | When you generate a web reference and click on the web reference in the Solution Explorer. In the properties pane you should see something like this:

Changing the value to dynamic will put an entry in your app.conf... | If you are truly dynamically setting this, you should set the .Url field of instance of the proxy class you are calling.
Setting the value in the .config file from within your program:
1. Is a mess;
2. Might not be read until the next application start.
If it is only something that needs to be done once per installa... | How can I dynamically switch web service addresses in .NET without a recompile? | [
"",
"c#",
"visual-studio",
"web-services",
"url",
"wsdl",
""
] |
A couple of months ago I've coded a tiny tool that we needed at work for a specific task, and I've decided to share it on CodePlex. It's written in C# and honestly it's not big deal but since it's the first project I've ever built from scratch in that language and with the goal of opening it from the very beginning, on... | I know I sound like a broken record constantly posting this book, but just about everything you could ever need to know about running an open source project is [here](http://producingoss.com/en/index.html). In particular, pay attention to these two chapters:
* [Getting Started](http://producingoss.com/en/getting-start... | You should:
* Promote it where you think it would be relevant (forums,mailing lists etc.). Try not to spam though - it will create a backlash.
* continue to provide updates as to create the appearance of an active project until more people pick it up.
* Find project leaders, they are the sort of contributors that enco... | What should I do to keep a tiny Open Source project active and sustainable? | [
"",
"c#",
".net",
"open-source",
""
] |
We've got a Java server application that runs on a number of computers, all connected to the Internet, some behind firewalls. We need to remotely update the JAR files and startup scripts from a central site, with no noticeable interruption to the app itself.
The process has to be unattended and foolproof (i.e. we can'... | You didn't specify the type of server apps - I'm going to assume that you aren't running web apps (as deploying a WAR already does what you are talking about, and you very rarely need a web app to do pull type updates. If you are talking about a web app, the following discussion can still apply - you'll just implement ... | You should definitely take a look at OSGi, it was created just for these cases (especially for embedded products) and is used by a large number of companies. You can update jar "bundles", add and remove them, while the app is running. I haven't used it myself, so I don't know about the quality of the open source framew... | How do you remotely update Java applications? | [
"",
"java",
"release-management",
""
] |
Tomcat (version 5 here) stores session information in memory. When clustering this information is periodically broadcast to other servers in the cluster to keep things in sync. You can use a database store to make sessions persistant but this information is only written periodically as well and is only really used for ... | There definitely is a way. Though I'd strongly vote for sticky sessions - saves so much load for your servers/database (unless something fails)...
<http://tomcat.apache.org/tomcat-5.5-doc/config/manager.html> has information about SessionManager configuration and setup for Tomcat. Depending on your exact requirements ... | Take a look at [Terracotta](http://www.terracotta.org/), I think it can address your scaling issues without a major application redesign. | Is there a way to specify a different session store with Tomcat? | [
"",
"java",
"tomcat",
"session",
""
] |
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
---
Edit: I'm using python, but I assume that this is a fairly language-independent problem. | If you on a debian[-like] machine,
```
#!/bin/bash
echo -n "Enter a word: "
read input
grep "^$input" /usr/share/dict/words
```
Takes all of 0.040s on my P200. | Use a [trie](http://en.wikipedia.org/wiki/Trie).
Add your list of words to a trie. Each path from the root to a leaf is a valid word. A path from a root to an intermediate node represents a prefix, and the children of the intermediate node are valid completions for the prefix. | List all words in a dictionary that start with <user input> | [
"",
"python",
"list",
"dictionary",
""
] |
When I run a particular SQL script in Unix environments, I see a '^M' character at the end of each line of the SQL script as it is echoed to the command line.
I don't know on which OS the SQL script was initially created.
What is causing this and how do I fix it? | It's caused by the DOS/Windows line-ending characters. Like Andy Whitfield said, the Unix command dos2unix will help fix the problem. If you want more information, you can read the man pages for that command. | Fix line endings in `vi` by running the following:
`:set fileformat=unix`
`:w` | '^M' character at end of lines | [
"",
"sql",
"unix",
"newline",
"carriage-return",
"line-endings",
""
] |
Table:
```
UserId, Value, Date.
```
I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date.
How do I do this in SQL? (Preferably Oracle.)
I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date. | This will retrieve all rows for which the my\_date column value is equal to the maximum value of my\_date for that userid. This may retrieve multiple rows for the userid where the maximum date is on multiple rows.
```
select userid,
my_date,
...
from
(
select userid,
my_date,
...
max... | I see many people use subqueries or else window functions to do this, but I often do this kind of query without subqueries in the following way. It uses plain, standard SQL so it should work in any brand of RDBMS.
```
SELECT t1.*
FROM mytable t1
LEFT OUTER JOIN mytable t2
ON (t1.UserId = t2.UserId AND t1."Date" ... | Fetch the rows which have the Max value for a column for each distinct value of another column | [
"",
"sql",
"oracle",
"greatest-n-per-group",
""
] |
Working on a project that parses a log of events, and then updates a model based on properties of those events. I've been pretty lazy about "getting it done" and more concerned about upfront optimization, lean code, and proper design patterns. Mostly a self-teaching experiment. I am interested in what patterns more exp... | Well... for one thing rather than a single event class with a union of all the properties, or 61 event classes (1 base, 60 subs), in a scenario with that much variation, I'd be tempted to have a single event class that uses a property bag (dictionary, hashtable, w/e floats your boat) to store event information. The typ... | Consider a Flyweight factory of Strategy objects, one per 'class' of event.
For each line of event data, look up the appropriate parsing strategy from the flyweight factory, and then pass the event data to the strategy for parsing. Each of the 60 strategy objects could be of the same class, but configured with a diffe... | Appropriate design pattern for an event log parser? | [
"",
"java",
"logging",
""
] |
While googling, I see that using [`java.io.File#length()`](http://docs.oracle.com/javase/6/docs/api/java/io/File.html#length%28%29) can be slow.
[`FileChannel`](http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html) has a [`size()`](http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileCh... | Well, I tried to measure it up with the code below:
For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:
```
LENGTH sum: 10626, per Iteration: 10626.0
CHANNEL... | The benchmark given by GHad measures lots of other stuff (such as reflection, instantiating objects, etc.) besides getting the length. If we try to get rid of these things then for one call I get the following times in microseconds:
```
file sum___19.0, per Iteration___19.0
raf sum___16.0, per Iteration___16.0
... | java get file size efficiently | [
"",
"java",
"filesize",
""
] |
I'm using the ProgressBar control in a WPF application and I'm getting this old, Windows 3.1 Progress*Blocks* thing. In VB6, there was a property to show a *smooth* ProgressBar. Is there such a thing for WPF? | [This](http://support.microsoft.com/kb/323116) KB article seems to explain what you are looking for... there is a link to a VB version of the article too. | I was not able to find a direct solution for this. But I found something even better. In WPF, you can use Windows Themes. I am using Windows XP, and having Vista-Aero Theme on my WPF Application, making all controls look like Vista-Aero.
Here's the code...
Go to Application.xaml.vb and write...
```
Enum appThemes
... | Smooth ProgressBar in WPF | [
"",
"c#",
"wpf",
"progress-bar",
""
] |
I would like to call my unmanaged C++ libraries from my C# code. What are the potential pitfalls and precautions that need to be taken? Thank you for your time. | This question is too broad. The only reasonable answer is P/Invoke, but that's kind of like saying that if you want to program for Windows you need to know the Win32 API.
Pretty much entire books have been written about P/Invoke ([http://www.amazon.com/NET-COM-Complete-Interoperability-Guide/dp/067232170X](https://rad... | There are a couple routes you can go with this - one, you can update your unmanaged C++ libraries to have a managed C++ extensions wrapper around them and have C# utilize those classes directly. This is a bit time-consuming, but it provides a nice bridge to legacy unmanaged code. But be aware that managed C++ extension... | Mixing C# Code and umanaged C++ code on Windows with Visual Studio | [
"",
"c#",
"windows",
"visual-c++",
"unmanaged",
""
] |
I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status.
So I'm thinking:
```
UPDATE sales
SET s... | ```
SELECT DISTINCT a,b,c FROM t
```
is *roughly* equivalent to:
```
SELECT a,b,c FROM t GROUP BY a,b,c
```
It's a good idea to get used to the GROUP BY syntax, as it's more powerful.
For your query, I'd do it like this:
```
UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
SELECT id
FROM sales S
INNER JO... | If you put together the answers so far, clean up and improve, you would arrive at this superior query:
```
UPDATE sales
SET status = 'ACTIVE'
WHERE (saleprice, saledate) IN (
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING count(*) = 1
);
```
Which is *much* faste... | How do I (or can I) SELECT DISTINCT on multiple columns? | [
"",
"sql",
"postgresql",
"sql-update",
"duplicates",
"distinct",
""
] |
```
#include <iostream>
using namespace std;
int main()
{
double u = 0;
double w = -u;
cout << w << endl;
return 0;
}
```
Why does this great piece of code output `-0` and not `0`, as one would expect? | The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to be negative. [Wikipedia](http://en.wikipedia.org/wiki/IEEE_754) should be able to help explain this. | In IEEE floating point `0` and `-0` are both distinct values, from [here](http://steve.hollasch.net/cgindex/coding/ieeefloat.html) under "Special Values":
> Note that -0 and +0 are distinct
> values, though they both compare as
> equal. | cout prints "-0" instead of "0" | [
"",
"c++",
"floating-point",
""
] |
We have two versions of a managed C++ assembly, one for x86 and one for x64. This assembly is called by a .net application complied for AnyCPU. We are deploying our code via a file copy install, and would like to continue to do so.
Is it possible to use a Side-by-Side assembly manifest to loading a x86 or x64 assembly... | I created a simple solution that is able to load platform-specific assembly from an executable compiled as AnyCPU. The technique used can be summarized as follows:
1. Make sure default .NET assembly loading mechanism ("Fusion" engine) can't find either x86 or x64 version of the platform-specific assembly
2. Before the... | My version, similar to @Milan, but with several important changes:
* Works for ALL DLLs that were not found
* Can be turned on and off
* `AppDomain.CurrentDomain.SetupInformation.ApplicationBase` is used instead of `Path.GetFullPath()` because the current directory might be different, e.g. in hosting scenarios, Excel ... | Using Side-by-Side assemblies to load the x64 or x32 version of a DLL | [
"",
"c#",
".net",
"64-bit",
""
] |
Like the Delicious submission bookmark-let, I'd like to have some standard JavaScript I can use to submit any visited URL to a 3rd party site when that's possible by URL. Suggestions?
For example, I've been using
```
javascript:void(location.href="http://www.yacktrack.com/home?query="+encodeURI(location.href))
```
s... | Do you want something exactly like the Delicious bookmarklet (as in, something the user actively clicks on to submit the URL)? If so, you could probably just copy their code and replace the target URL:
```
javascript:(function(){
location.href='http://example.com/your-script.php?url='+
encodeURIComponent(windo... | ```
document.location = "http://url_submitting_to.com?query_string_param=" + window.location;
``` | What's cleanest, shortest Javascript to submit a URL the user is at to another process via URL? | [
"",
"javascript",
"url",
"submission",
""
] |
To make a JavaScript class with a public method I'd do something like:
```
function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something here
}
Restaurant.prototype.use_restroom = function(){
// something here
}
```
That way users of my class can:
```
var restaurant = new Restaurant();
re... | You can do it, but the downside is that it can't be part of the prototype:
```
function Restaurant() {
var myPrivateVar;
var private_stuff = function() { // Only visible inside Restaurant()
myPrivateVar = "I can set this here!";
}
this.use_restroom = function() { // use_restroom is visible ... | # Using self invoking function and call
JavaScript uses [prototypes](http://en.wikipedia.org/wiki/Prototype-based_programming) and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.
Wikipedia quote:
> Unlike many object-oriented langua... | JavaScript private methods | [
"",
"javascript",
"oop",
"private-methods",
""
] |
Does anyone know of a good tool to generate the WSDL for a service contract written in C# (i.e. set of methods that are tagged as "[OperationContract]" using WCF)? All the tools I've found work the other way around: create code stubs from a WSDL. I don't want to have to hand-jam a WSDL file. I've found tools for php an... | Easiest thing to do is host the service with a base address setup, and then just hit it from a browser with "?wsdl" appended to the end.
Here's an example of a service configuration with a base address specified. Note this goes in the `<configuration><services>` element in your config:
```
<service name="MyServiceN... | [svcutil](http://msdn.microsoft.com/en-us/library/aa702581.aspx) or just host it quickly and hit the MEX point :) | WSDL Generator for C# | [
"",
"c#",
"wcf",
"wsdl",
""
] |
When you call the `object.__repr__()` method in Python you get something like this back:
> ```
> <__main__.Test object at 0x2aba1c0cf890>
> ```
Is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out? | The [Python manual](https://docs.python.org/2/library/functions.html#id) has this to say about `id()`:
> Return the "identity'' of an object.
> This is an integer (or long integer)
> which is guaranteed to be unique and
> constant for this object during its
> lifetime. Two objects with
> non-overlapping lifetimes may ... | You could reimplement the default repr this way:
```
def __repr__(self):
return '<%s.%s object at %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self))
)
``` | Accessing Object Memory Address | [
"",
"python",
"object",
"memory-address",
"repr",
""
] |
I am attempting to use the 'tempfile' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as using 'shutil.copy'. However, I get a 'permission denied' IOError:
```
>>> import tempfile, shutil
>>> f = tempfile.TemporaryFile(mode ='w+t')
>>> ... | The file you create with `TemporaryFile` or `NamedTemporaryFile` is automatically removed when it's closed, which is why you get an error. If you don't want this, you can use `mkstemp` instead (see the docs for [tempfile](https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp)).
```
>>> import tempfile, shut... | hop is right, and dF. is incorrect on why the error occurs.
Since you haven't called `f.close()` yet, the file is **not** removed.
The [doc](http://docs.python.org/library/tempfile.html#tempfile.NamedTemporaryFile) for `NamedTemporaryFile` says:
> Whether the name can be used to open the file a second time, while th... | How do I persist to disk a temporary file using Python? | [
"",
"python",
"temporary-files",
""
] |
**I want to read the contents of a URL but don't want to "hang" if the URL is unresponsive. I've created a BufferedReader using the URL...**
```
URL theURL = new URL(url);
URLConnection urlConn = theURL.openConnection();
urlConn.setDoOutput(true);
BufferedReader urlReader = new BufferedReader(newInputStreamReader(urlC... | I think URLConnection.setReadTimeout is what you are looking for. | If you have java 1.4:
I assume the connection timeout (`URLConnection.setConnectTimeout(int timeout)` ) is of no use because you are doing some kind of streaming.
---**Do not kill the thread**--- It may cause unknown problems, open descriptors, etc.
Spawn a java.util.TimerTask where you will check if you have finish... | How can I set a timeout against a BufferedReader based upon a URLConnection in Java? | [
"",
"java",
"url",
"sockets",
""
] |
What things have to be done before I can honestly tell myself my web application is accessible by anyone? Or even better, convince Joe Clark. I don't have any video or audio to worry about, so I know I won't need transcripts. What else do I have to check? | Your question is very vague, but in short, you need to ensure that your site meets one of the three levels (A, AA, or AAA) of the [Web Content Accessibility Guidelines](http://www.w3.org/TR/WCAG10/).
FWIW, in my experience, if you are providing anything other than a purely static HTML site, aim for AA. Trying to follo... | You should also check out the WAI-ARIA stuff:
* <http://www.w3.org/WAI/intro/aria>
* <http://alistapart.com/articles/waiaria>
* <http://juicystudio.com/article/wai-aria-live-regions.php>
And, for a perspective on the challenges actually faced by users with various disabilities when they try to use the web, have a loo... | Make Web Application Accessible | [
"",
"javascript",
"html",
"usability",
"accessibility",
""
] |
What options are there for building automated tests for GUIs written in Java Swing?
I'd like to test some GUIs which have been written using the [NetBeans Swing GUI Builder](http://www.netbeans.org/features/java/swing.html), so something that works without requiring special tampering of the code under test would be id... | Recently I came across FEST which seemed promising, except that the developer [announced in 2012 that development would not continue](https://groups.google.com/forum/#!msg/easytesting/bAt1nWx55FM/e3DF0bxGUf8J).
[AssertJ](https://joel-costigliola.github.io/assertj/) is a fork of FEST that is working very well for me. I... | I'm currently using [FEST](http://code.google.com/p/fest/). It works with JUnit and will also take screenshots of failed tests.
It has default component hunting methods which look for the name of the component being tested (which need to be set manually), but you can also generate the testers for a given component by ... | Automated tests for Java Swing GUIs | [
"",
"java",
"swing",
"testing",
"automated-tests",
""
] |
I need to display many pages of news in a site. Should I do the pagination in the database query using `LIMIT` or with the PHP script after getting all the results? | Use limit in SQL! Every time!
Otherwise you're throwing around considerably more data than you need to, which makes your scripts unnecessarily slow, and will lead to scalability problems as the amount of data in your tables increases.
Limit is your friend! | Use limit - you don't want to transfer masses of data from the database to the scripting engine if you can avoid it. | What is the best way to paginate results in php | [
"",
"php",
"pagination",
""
] |
Today I stumbled about a Problem which seems to be a bug in the Zend-Framework. Given the following route:
```
<test>
<route>citytest/:city</route>
<defaults>
<controller>result</controller>
<action>test</action>
</defaults>
<reqs>
<city>.+</city>
</reqs>
</test>
```
and th... | The problem is the following:
> Using the /u pattern modifier prevents
> words from being mangled but instead
> PCRE skips strings of characters with
> code values greater than 127.
> Therefore, \w will not match a
> multibyte (non-lower ascii) word at
> all (but also won’t return portions of
> it). From the pcrepatte... | Please its working perfect for me
```
/^[\p{L}-. ]*$/u
```
* `^` Start of the string
* `[ ... ]*` Zero or more of the following:
* `\p{L}` Unicode letter characters
* `–` dashes
* `.` periods
* spaces
* `$` End of the string
* `/u` Enable Unicode mode in PHP
EXAMPLE:
```
$str= ‘Füße’;
if (!preg_match(“/^[\p{L}-. ]*... | Route-problem regarding Url-encoded Umlauts (using the Zend-framework) | [
"",
"php",
"zend-framework",
""
] |
Could you recommend me a way to place a coundown timer on ASP.NET page?
Now I use this code:
**Default.aspx**
```
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server">60</asp:Label>
... | OK, finally I ended with
```
<span id="timerLabel" runat="server"></span>
<script type="text/javascript">
function countdown()
{
seconds = document.getElementById("timerLabel").innerHTML;
if (seconds > 0)
{
document.getElementById("timerLabel").innerHTML = seconds - 1;
... | ```
time1 = (DateTime)ViewState["time"] - DateTime.Now;
if (time1.TotalSeconds <= 0)
{
Label1.Text = Label2.Text = "TimeOut!";
}
else
{
if (time1.TotalMinutes > 59)
{
Label1.Text = Label2.Text = string.Format("{0}:{1:D2}:{2:D2}",
time1... | Countdown timer on ASP.NET page | [
"",
"asp.net",
"javascript",
"asp.net-ajax",
""
] |
I'm working with PostSharp to intercept method calls to objects I don't own, but my aspect code doesn't appear to be getting called. The documentation seems pretty lax in the Silverlight area, so I'd appreciate any help you guys can offer :)
I have an attribute that looks like:
```
public class LogAttribute : OnMetho... | **This is not possible with the present version of PostSharp.**
PostSharp works by transforming assemblies prior to being loaded by the CLR. Right now, in order to do that, two things have to happen:
* The assembly must be about to be loaded into the CLR; you only get one shot, and you have to take it at this point.
... | I believe if you change AttributeTargetAssemblies to "PresentationFramework", it might work. (Don't have PostSharp down that well yet).
The Assembly for WPF is PresentationFramework.dll. The AttributeTargetAssemblies needs the dll that it should target. | Using PostSharp to intercept calls to Silverlight objects? | [
"",
"c#",
"postsharp",
""
] |
Never used a cache like this before. The problem is that I want to load 500,000 + records out of a database and do some selecting/filtering wicked fast.
I'm thinking about using a cache, and preliminarily found [EHCache](http://ehcache.org/) and [OSCache](https://java.net/projects/oscache/), any opinions? | They're both pretty solid projects. If you have pretty basic caching needs, either one of them will probably work as well as the other.
You may also wish to consider doing the filtering in a database query if it's feasible. Often, using a tuned query that returns a smaller result set will give you better performance t... | Judging by their [releases page](http://www.opensymphony.com/oscache/download.action), OSCache has not been actively maintained since 2007. This is not a good thing. EhCache, on the other hand, is under constant development. For that reason alone, I would choose EhCache.
Edit Nov 2013: OSCache, like the rest of OpenSy... | OSCache vs. EHCache | [
"",
"java",
"caching",
"ehcache",
"oscache",
""
] |
I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.
I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it alrea... | Treat the following as pseudo-code..
```
try:
from hashlib import sha as hasher
except ImportError:
# You could probably exclude the try/except bit,
# but older Python distros dont have hashlib.
try:
import sha as hasher
except ImportError:
import md5 as hasher
def hash_password(p... | dbr said:
> ```
> def hash_password(password):
> """Returns the hashed version of a string
> """
> return hasher.new( str(password) ).hexdigest()
> ```
This is a really insecure way to hash passwords. You *don't* want to do this. If you want to know why read the [Bycrypt Paper](http://www.openbsd.org/pape... | Python Authentication API | [
"",
"python",
"authentication",
"desktop",
""
] |
WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a [console documentation for Firebug](http://getfirebug.com/wiki/index.php/Console_API), but where can I find the console documentation for Safari/WebKit? | Supported methods were originally:
* `console.log()`
* `console.error()`
* `console.warn()`
* `console.info()`
Newer versions of WebKit also add the following methods making the WebKit console API almost identical to [Firebug's console API](http://getfirebug.com/wiki/index.php/Console_API):
* `console.count()`
* `co... | The console API is documented by Apple in the [Console](https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html) section of the Safari Developer Guide. | Where is the console API for WebKit/Safari? | [
"",
"javascript",
"console",
"safari",
""
] |
I'm developing a restful Web service that runs as a servlet (using blocking IO) in Jetty. Figuring out the optimal setting for max threads seems hard.
Is there a researched formula for deciding the max number of threads from some easily measurable characteristics of the rest of the setup? | Very simple and primitive one:
max\_number\_of\_threads = number\_of\_CPUs \* C
Where C depends on other factors of your application :-)
Ask yourself following questions:
* Will your application be CPU intensive (lower C) or spend most time waiting for a third systems (higher C)?
* Do you need quicker response time... | No there is not. Keep you number of threads limited and under control so you not exceed system resources, Java's limit is usually around 100-200 live threads.
Good way to do it is by using Executors from **java.util.concurrent**. | How to choose the max thread count for an HTTP servlet container? | [
"",
"java",
"http",
"optimization",
"servlets",
"concurrency",
""
] |
So I'm working on some legacy code that's heavy on the manual database operations. I'm trying to maintain some semblance of quality here, so I'm going TDD as much as possible.
The code I'm working on needs to populate, let's say a `List<Foo>` from a DataReader that returns all the fields required for a functioning Foo... | To make this less tedious, you will need to encapsulate/refactor the mapping between the DataReader and the Object you hold in the list. There is quite of few steps to encapsulate that logic out. If that is the road you want to take, I can post code for you. I am just not sure how practical it would be to post the code... | I thought about posting some code and then I remembered about JP Boodhoo's Nothin But .NET course. He has a [sample project](http://code.google.com/p/jpboodhoo/) that he is sharing that was created during one of his classes. The project is hosted on [Google Code](http://code.google.com/) and it is a nice resource. I am... | How should I test a method that populates a list from a DataReader? | [
"",
"c#",
"unit-testing",
"tdd",
"mocking",
""
] |
I have defined an interface in C++, i.e. a class containing only pure virtual functions.
I want to explicitly forbid users of the interface to delete the object through a pointer to the interface, so I declared a protected and non-virtual destructor for the interface, something like:
```
class ITest{
public:
virt... | It's more or less a bug in the compiler. Note that in more recent versions of the compiler this warning does not get thrown (at least in 4.3 it doesn't). Having the destructor be protected and non-virtual is completely legitimate in your case.
See [here](http://www.gotw.ca/publications/mill18.htm) for an excellent art... | Some of the comments on this answer relate to an earlier answer I gave, which was wrong.
A protected destructor means that it can only be called from a base class, not through delete. That means that an ITest\* cannot be directly deleted, only a derived class can. The derived class may well want a virtual destructor. ... | GNU compiler warning "class has virtual functions but non-virtual destructor" | [
"",
"c++",
"gcc",
""
] |
I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any e... | This is what I could find, maybe it solves your problem:
1. SP to get the current job activiity.
> ```
> exec msdb.dbo.sp_help_jobactivity @job_id = (your job_id here)
> ```
You can execute this SP and place the result in a temp table and get the required result from there.
Otherwise have a look at these tables:
... | --Copy in Query analizer and format it properly so you can understand it easyly
--To execute your task(Job) using Query
exec msdb.dbo.sp\_start\_job @job\_name ='Job Name',@server\_name = server name
-- After executing query to check weateher it finished or not
Declare @JobId as varchar(36)
Select @JobId = job\_id from... | SQL Job Status | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I recently started using Eclipse at work for my Java servlet projects. I've been using jEdit for years, which is a uber-powerful text editor. It has syntax highlighting, but it doesn't have any language-specific features like code completion and intelligent refactoring. I'm finding that's hindering my productivity. I *... | Try [NetBeans](http://www.netbeans.org/)
> A free, open-source Integrated
> Development Environment for software
> developers. You get all the tools you
> need to create professional desktop,
> enterprise, web, and mobile
> applications with the Java language,
> C/C++, and Ruby. | Eclipse works best if you leave the project folder structure to its management. We are working with 15 developers on a project of several thousand classes and even more XML and .properties files.
I agree there are problems with ANT integration, so for production and nightly builds I recommend an external build system ... | Is it me, or is Eclipse horribly unpredictable? | [
"",
"java",
"eclipse",
"ide",
"editor",
""
] |
Looking for suggestions on file system management tools. We have several terabytes of images, pdfs, excel sheets, etc.
We're looking at some sort of software that will help us to manage, archive, etc the images.
We don't store all the files information in a database but some are and we were hoping to maybe find an ap... | I have always seen these guys in the trade magazines. <http://www.dtsearch.com/> I believe they've been around long before even Google. Not sure if this is what you're looking for. | If some of the data is saved on disks perhaps a search application is more appropriate. You can use google, microsoft search or similar program. | File System Management Tools | [
"",
"sql",
"database",
"file",
"system",
""
] |
I'm developing a Mac App in Java that logs into any one of our client's databases. My users want to have several copies of this program running so they can log into a couple clients at the same time, rather than logging out and logging back in.
How can I allow a user to open several copies of my App at once?
I'm usin... | You've probably already gotten enough code that you don't want to hear this, but you should really not be starting up two instances of the same application. There's a reason that you're finding it so difficult and that's because Apple doesn't want you to do it.
The OSX way of doing this is to use the **Cocoa Document-... | From the Terminal (or in a script wrapper):
```
/Applications/TextEdit.app/Contents/MacOS/TextEdit &
```
Something like that should work for you.
To do this in Java:
```
String[] cmd = { "/bin/sh", "-c", "[shell commmand goes here]" };
Process p = Runtime.getRuntime().exec (cmd);
``` | Opening more than one of the same Mac Application at once | [
"",
"java",
"eclipse",
"macos",
""
] |
I'm running `Django 1.0` and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.
With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.
Any thoughts... | Automatically log your 500s, that way:
* You know when they occur.
* You don't need to rely on users sending you stacktraces.
Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktra... | As @zacherates says, you really don't want to display a stacktrace to your users. The easiest approach to this problem is what Django does by default if you have yourself and your developers listed in the ADMINS setting with email addresses; it sends an email to everyone in that list with the full stack trace (and more... | How do I include a stacktrace in my Django 500.html page? | [
"",
"python",
"django",
"templates",
"stack-trace",
""
] |
So, I've been reading through and it appears that the Boost libraries get used a lot in practice (not at my shop, though). Why is this? and what makes it so wonderful? | [Boost](http://www.boost.org/) is used so extensively because:
* It is open-source and peer-reviewed.
* It provides a [wide range](http://www.boost.org/doc/libs) of platform agnostic functionality that STL missed.
* It is a complement to STL rather than a replacement.
* Many of Boost developers are on the C++ standard... | From the home page:
> "...one of the most highly regarded and expertly designed C++ library projects in the world."
> — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards
>
> "Item 55: Familiarize yourself with Boost."
> — Scott Meyers, Effective C++, 3rd Ed.
>
> "The obvious solution for most programmers is to... | What are the advantages of using the C++ Boost libraries? | [
"",
"c++",
"boost",
""
] |
I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute? | 1. Add to the docs. it is downright crappy
2. Help out other users on the dev and user mailing lists.
3. TEST PYTHON. bugs in programming languages are real bad. And I have seen someone discover atleast 1 bug in python
4. Frequent the #python channel on irc.freenode.net | Build something cool in Python and share it with others. Small values of cool are still cool. Not everyone gets to write epic, world-changing software.
Every problem solved well using Python is a way of showing how cool Python is. | Contributing to Python | [
"",
"python",
""
] |
I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:
```
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
Aliquam rhoncus eros at a... | ~~Try [highlight: JavaScript text highlighting jQuery plugin](http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html).~~
**Warning: The source code available on this page contains a cryptocurrency mining script, either use the code below or remove the mining script ... | ```
function hiliter(word, element) {
var rgxp = new RegExp(word, 'g');
var repl = '<span class="myClass">' + word + '</span>';
element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
hiliter('dolor');
``` | Highlight a word with jQuery | [
"",
"javascript",
"jquery",
"html",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.