Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I need to determine the current year in Java as an integer. I could just use `java.util.Date()`, but it is deprecated. | For Java 8 onwards:
```
int year = Year.now().getValue();
```
For older version of Java:
```
int year = Calendar.getInstance().get(Calendar.YEAR);
``` | Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use [the `Year::now` method](https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#now--):
```
int year = Year.now().getValue();
``` | Get integer value of the current year in Java | [
"",
"java",
"datetime",
"date",
""
] |
Not sure how to ask a followup on SO, but this is in reference to an earlier question:
[Fetch one row per account id from list](https://stackoverflow.com/questions/94930/fetch-one-row-per-account-id-from-list)
The query I'm working with is:
```
SELECT *
FROM scores s1
WHERE accountid NOT IN (SELECT accountid FROM sco... | If you're only interested in the accountid and the score, then you can use the simple GROUP BY query given by Paul above.
```
SELECT accountid, MAX(score)
FROM scores
GROUP BY accountid;
```
If you need other attributes from the scores table, then you can get other attributes from the row with a query like the foll... | ```
select accountid, max(score) from scores group by accountid;
``` | Fetch one row per account id from list, part 2 | [
"",
"sql",
"mysql",
"database",
""
] |
I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window.
Is this possible, using C++ / MFC? | Charlie hit on the answer with `WM_NCPAINT`. If you're using MFC, the code would look something like this:
```
// in the message map
ON_WM_NCPAINT()
// ...
void CMainFrame::OnNcPaint()
{
// still want the menu to be drawn, so trigger default handler first
Default();
// get menu bar bounds
MENUBARINFO me... | In order to draw in the non-client area, you need to get the "window" DC (rather than "client" DC), and draw in the "window" DC. | How to draw in the nonclient area? | [
"",
"c++",
"mfc",
"drawing",
"nonclient",
""
] |
Obviously the [Java API](http://java.sun.com/j2se/1.5.0/docs/api/) reference, but what else is there that you all use?
I've been doing web development my entire career. Lately I've been messing around a lot with [Groovy](http://groovy.codehaus.org) and I've decided to do a small application in [Griffon](http://groovy.... | [The Swing Tutorial](http://java.sun.com/docs/books/tutorial/uiswing/) is very good. Apart from that, the Swing API is obviously *the* reference, however it's also a treasure trove of fairly good source code! Add the API source to your IDE and you can jump directly to the implementation to all the Swing classes. This i... | The Sun Java tutorials are pretty good. I cannot vouch specifically for the Swing one as it has been ages since I've done any Swing development and I have not read it myself.
[Creating a GUI with JFC/Swing](http://java.sun.com/docs/books/tutorial/uiswing/) | What's the definitive Java Swing starter guide and reference? | [
"",
"java",
"swing",
"groovy",
"griffon",
""
] |
I am coming from Java and am currently working on a C# project. What is the recommended way to go about a) unit testing existing C# code and b) accomplishing TDD for C# development?
Also is there an equivalent to EMMA / EclEmma (free yet powerful code coverage tool) for Visual Studio and C# code? | 1 [Nunit](http://www.nunit.org/)
2 [NCover](http://ncover.org/) or
3 [PartCover](http://sourceforge.net/projects/partcover/) (I never used it) | [NUnit](http://www.nunit.org/index.php) is patterned after JUnit, but if you're using Visual Studio 2008 then consider the built-in unit testing framework. | What is the equivalent to JUnit in C#? | [
"",
"c#",
"unit-testing",
"junit",
""
] |
I'm trying to use a link to open an overlay instead of in a separate popup window. This overlay should consist of a semi-transparent div layer that blocks the whole screen from being clicked on. I also aim to disable scrolling at this point. Not matter where you are on the main page, when the link is clicked, the overl... | You might want to check out an old JS lib I wrote, called [SubModal](http://code.google.com/p/submodal/).
Easy to understand and modify. Go to town ;)
Once you've modded it, use [Minify](http://code.google.com/p/minify/) in combination with gzip on your server. The lib size will be teeny tiny. | [Shadowbox](http://mjijackson.com/shadowbox/) is a nice script for inline "popups". It can work with any of the usual JS libraries if you use any (jQuery, Prototype, etc) or on its own, has a pretty comprehensive skinning system so you can adapt the looks without having to go into the source code itself.
It is also t... | How can I create a Netflix-style iframe overlay without a huge javascript library? | [
"",
"javascript",
"css",
"overlay",
""
] |
I was curious if anyone had any problems creating unit tests around using the ResourceManager. I am using Visual Studio test edition and it appears that the satellite assemblies don't get loaded during the test. When I try to get a resource for another culture, the test always fails and the resource manager always fall... | I've had similar problems in the past with satellite assemblies. Try
adding the satellite assemblies to the unit projects dependecies. In Visual Studio
Test -- Edit Test Run configuration. Select Deployment and add the files
here.
On executing all applications, dlls, etc are copied to a special directory.
Strong named... | That got me going in the right direction. Adding the files to the deployment config didn't help, but disabling deployment did work.
For future reference, Visit [this blog post](http://stephenwalther.com/blog/archive/2008/03/20/tdd-test-driven-development-with-visual-studio-2008-unit-tests.aspx) and scroll down to the ... | ResourceManager and Unit Testing | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"resources",
""
] |
Seeing as Java doesn't have nullable types, nor does it have a TryParse(),
how do you handle input validation without throwing an exceptions?
The usual way:
```
String userdata = /*value from gui*/
int val;
try
{
val = Integer.parseInt(userdata);
}
catch (NumberFormatException nfe)
{
// bad data - set to sentin... | That's pretty much it, although returning MIN\_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.
Might also be useful (depending on the application) to log the bad input so yo... | I asked [if there were open source utility libraries that had methods to do this parsing for you](https://stackoverflow.com/questions/16698647/java-library-that-has-parseint-parselong-parsedouble-etc-that-accept-default) and the answer is yes!
From [Apache Commons Lang](http://commons.apache.org/proper/commons-lang/) ... | String to Int in java - Likely bad data, need to avoid exceptions | [
"",
"java",
"parsing",
"numbers",
""
] |
I'm writing a GUI in C#, Visual Studio 2008, using the Designer and WinForms. I've got a ComboBox control, and I'd like it to only allow to select from the provided options and not to accept a user-entered string. It doesn't appear to have a ReadOnly property, and disabling it hinders the readability of the control (as... | Set DropDownStyle to "DropDownList" | Set the ComboBox.DropDownStyle property to ComboBoxStyle.DropDownList. | Readonly ComboBox in WinForms | [
"",
"c#",
"winforms",
"combobox",
"readonly",
""
] |
Several frameworks for writing web-based desktop-like applications have recently appeared. E.g. [SproutCore](http://www.sproutcore.com/) and [Cappuccino](http://cappuccino.org/). Do you have any experience using them? What's your impression? Did I miss some other framework?
I've seen [related](https://stackoverflow.co... | Due to the speed issues these high-level frameworks cause for many larger (as in: non-trivial) applications, we only use plain jQuery. In our tests, all high-level frameworks broke down in situations where there are many draggable objects or many drop targets, and in situation where long lists (with >1000 entries) were... | To my point of view, Cappuccino is an example of what NOT to do. They implemented another language on top of JavaScript, which already bring slowliness while browser developer are already fighting hard against, and, what is worst, they don't rely at all on the browser widget, breaking all the user navigation experience... | What framework would you recommend for making desktop-like apps for the web? | [
"",
"javascript",
"web-applications",
"frameworks",
""
] |
I need to copy several tables from one DB to another in SQL Server 2000, using C# (VS 2005). The call needs to be parameterized - I need to be able to pass in the name of the database to which I am going to be copying these tables.
I could use DTS with parameters, but I can't find any sample code that does this from C... | For SQL Server 7.0 and 2000, we have SQLDMO for this. For SQL Server 2005 there is SMO. This allows you do to pretty much everything related to administering the database, scripting objects, enumerating databases, and much more. This is better, IMO, than trying a "roll your own" approach.
SQL 2000:
[Developing SQL-DMO... | If the destination table is being dropped every time then why not do SELECT INTO? Doesn't seem like a kludge at all.
If it works just fine and ticks all the requirements boxes why create a days worth of work growing code to do exactly the same thing?
Let SQL do all the heavy lifting for you. | How do you copy a MS SQL 2000 database programmatically using C#? | [
"",
"c#",
".net",
"sql-server",
"dts",
""
] |
Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?
**Answer** - As I had suspected, the solution was to wrap it in a BufferedInputStrea... | For a general InputStream, I would wrap it in a BufferedInputStream and do something like this:
```
BufferedInputStream bis = new BufferedInputStream(inputStream);
bis.mark(2);
int byte1 = bis.read();
int byte2 = bis.read();
bis.reset();
// note: you must continue using the BufferedInputStream instead of the inputStre... | You might find PushbackInputStream to be useful:
<http://docs.oracle.com/javase/6/docs/api/java/io/PushbackInputStream.html> | How do I peek at the first two bytes in an InputStream? | [
"",
"java",
"inputstream",
"bufferedinputstream",
""
] |
I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1\*1000 + Part2).
I normalized that column, but I cannot change the old values.
So now I have
```
select ID from table order by ID
ID
100001
100002
101001
...
```
I want to find the "holes" in the table (m... | ```
select ID +1 From Table t1
where not exists (select * from Table t2 where t1.id +1 = t2.id);
```
not sure if this version would be faster than the one you mentioned originally. | ```
SELECT (ID+1) FROM table AS t1
LEFT JOIN table as t2
ON t1.ID+1 = t2.ID
WHERE t2.ID IS NULL
``` | How to find "holes" in a table | [
"",
"sql",
""
] |
If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that? Or is it not possible?
This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation. | On PostgreSQL (and many other RDBMS), you can do it with regular `ALTER TABLE` statement:
```
=> SELECT * FROM Test1;
id | foo | bar
----+-----+-----
2 | 1 | 2
=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE
=> SELECT * FROM Test1;
id | baz | bar
----+-----+-----
2 | 1 | 2
``` | Specifically for SQL Server, use [`sp_rename`](http://msdn.microsoft.com/en-us/library/ms188351.aspx)
```
USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO
``` | How do I rename a column in a database table using SQL? | [
"",
"sql",
"database",
"rename",
""
] |
What is the difference between `ROWNUM` and `ROW_NUMBER` ? | ROWNUM is a "pseudocolumn" that assigns a number to each row returned by a query:
```
SQL> select rownum, ename, deptno
2 from emp;
ROWNUM ENAME DEPTNO
---------- ---------- ----------
1 SMITH 99
2 ALLEN 30
3 WARD 30
4 JONES ... | From a little reading, ROWNUM is a value automatically assigned by Oracle to a rowset (prior to ORDER BY being evaluated, so don't **ever** `ORDER BY ROWNUM` or use a `WHERE ROWNUM < 10` with an `ORDER BY`).
[ROW\_NUMBER()](http://download.oracle.com/docs/cd/B10500_01/server.920/a96540/functions105a.htm) appears to be... | In an Oracle database, what is the difference between ROWNUM and ROW_NUMBER? | [
"",
"sql",
"oracle",
"row-number",
"rownum",
""
] |
I have a PHP script that is called from a cron job every minute. This script takes some info from the database and then calls another PHP script using the System function (passing it some parameters).
That means that I can start up to 10 scripts from this "main" one. And what I would like to do is that I would call th... | You may be able to use [`proc_open()`](http://www.php.net/manual/en/function.proc-open.php), [`stream_select()`](http://www.php.net/manual/en/function.stream-select.php) and [`stream_set_blocking()`](http://www.php.net/manual/en/function.stream-set-blocking.php) in concert to achieve this kind of thing.
If that sounds... | If your OS supports it, you can use the [pcntl\_fork()](http://www.php.net/manual/en/function.pcntl-fork.php) function to spin off child processes that the parent doesn't wait for. Be careful though, it is easy to accidentally create too many child processes, especially if they take longer than expected to run! | Don't wait for the process to exit | [
"",
"php",
""
] |
How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an `os.chdir()`, the cwd will not be changed after the function is called. | The [path.py](https://github.com/jaraco/path.py) module (which you really should use if dealing with paths in python scripts) has a context manager:
```
subdir = d / 'subdir' #subdir is a path object, in the path.py module
with subdir:
# here current dir is subdir
#not anymore
```
(credits goes to [this blog post]... | The answer for a decorator has been given; it works at the function definition stage as requested.
With Python 2.5+, you also have an option to do that at the function *call* stage using a context manager:
```
from __future__ import with_statement # needed for 2.5 ≤ Python < 2.6
import contextlib, os
@contextlib.con... | How do I write a decorator that restores the cwd? | [
"",
"python",
"decorator",
"cwd",
""
] |
I'd like to use the Wiimote (accelerometers, gyroscopes, infrared camera, etc, etc, etc) on various applications.
It's a bluetooth device, and I know others have connected it to their computer.
* What's the easiest way to start using it in my software - are there libraries for C#, for instance?
* I want my software t... | Have you seen [Johnny Chung Lee's 'Procrastineering' Blog](http://procrastineering.blogspot.com/)? He's written a lot on the subject of using wii remotes and has some fantastic demonstration videos. **[Edit]** I just found out Mr Lee did [a TED talk](http://www.ted.com/index.php/talks/johnny_lee_demos_wii_remote_hacks.... | Coding4Fun had a managed C# library up that would allow you to interface with it but it seems their site is down right now. Though I think they used the Robotics Studio so that may be a place to start.
Found it... <http://www.codeplex.com/WiimoteLib>
Oh and I forgot to post a link to these videos I saw quite some tim... | Wiimote example programs | [
"",
"c#",
"user-interface",
"wiimote",
"wii",
""
] |
Is there a manual for cross-compiling a C++ application from Linux to Windows?
Just that. I would like some information (links, reference, examples...) to guide me to do that.
I don't even know if it's possible.
My objective is to compile a program in Linux and get a .exe file that I can run under Windows. | The basics are not too difficult:
```
sudo apt-get install mingw32
cat > main.c <<EOF
int main()
{
printf("Hello, World!");
}
EOF
i586-mingw32msvc-cc main.c -o hello.exe
```
Replace `apt-get` with `yum`, or whatever your Linux distro uses. That will generate a `hello.exe` for Windows.
Once you get your head ar... | It depends on what you mean (I couldn't really say).
1. If you mean that you want to use an existing Linux application on Windows, then you could try compiling it using [Cygwin](http://en.wikipedia.org/wiki/Cygwin) on Windows. This however does not give you a Windows executable free from all dependencies towards Cygwi... | Manual for cross-compiling a C++ application from Linux to Windows? | [
"",
"c++",
"windows",
"linux",
"cross-compiling",
""
] |
I'm witting a WCF service for a customer to send part information to our application. We have multiple customers that will have one or many locations, and part information is scoped to each location for the customer. When the customer calls our service they will need to specify the location.
Options that we have consi... | I would say if it's only one or two operations that need it, make it part of the data contract - sort of like making it a parameter to a method call. If every operation requires it, put it in the header, since it's just as much context as username, roles, tenant, or other authentication information - sort of like somet... | Do you need to use a message contract? I use Data contracts unless I need to stream something back, so everything just ends up in the body. But, even for a message contract I would put that information in the body, I tend to reserve the header for authentication information. | WCF customheader or messagebody for context? | [
"",
"c#",
"wcf",
""
] |
I am trying to write a simple networked chat program in Java. I have almost no networking experience. I was wondering what resources I should begin looking at (beside here of course).
Sticking with the core Java API would be best for now. | I found a great tutorial into networking and java from sun's own website: <http://download.oracle.com/javase/tutorial/networking/TOC.html>
The socket section even has you write a mini client / server chat demo. | I recommend you to first learn networking. If you have time read the [Tanenbaum book](https://rads.stackoverflow.com/amzn/click/com/0133499456), the greatest reference in networking. If you want a quick leard, here is a road map:
* OSI layers
* UDP and TCP/IP
* Sockets
* Broadcast and Multicast
* Network security
The... | Java: Best Place to Begin Learning Basic Networking | [
"",
"java",
"networking",
""
] |
I am looking for a (preferably pure) python library to do AES 256 encryption and decryption.
This library should support the CBC cipher mode and use PKCS7 padding [according to the answer to an earlier question of mine](https://stackoverflow.com/questions/172392/what-symmetric-cypher-to-use-for-encrypting-messages).
... | ~~[PyCrypto](http://www.dlitz.net/software/pycrypto/) should be the one for you.~~
Edit 02/10/2020: unfortunately I cannot delete this post, since it's the accepted answer. As people pointed out in the comments, this library is not mantained anymore and probably also vulnerable from a security point of view. So please... | <https://github.com/caller9/pythonaes>
That is pure python with PKCS7 padding. Supports CBC, CFB, and OFB modes.
The problem is that python is not super fast for this type of thing. The code from serprex's fork is a little bit inscrutable, but much faster than mine due to using all kinds of tricks to squeeze every la... | What (pure) Python library to use for AES 256 encryption? | [
"",
"python",
"encryption",
"aes",
""
] |
The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When have you needed to use a `WeakHashMap` or `WeakReference` and how was it used? | > One problem with strong references is
> caching, particular with very large
> structures like images. Suppose you
> have an application which has to work
> with user-supplied images, like the
> web site design tool I work on.
> Naturally you want to cache these
> images, because loading them from disk
> is very expen... | # `WeakReference` versus `SoftReference`
One distinction to be clear on is the difference between a [`WeakReference`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ref/WeakReference.html) and a [`SoftReference`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ref/SoftRef... | When would you use a WeakHashMap or a WeakReference? | [
"",
"java",
"weak-references",
""
] |
*<flavor> I want to create a spelling test program for my grade schoolers that would let them enter and record their spelling words then test them on them through out the week.</flavor>*
What's a good Delphi API with which I could select a recording device, capture and save sound files, then play them back?
I'm also ... | An alternative to recording would be to use the MS Speech API with C#, enter the words via keyboard, and have it state what was keyed in.
Just a thought... Good luck on your app -- it sounds like a really cool program! | I've found [New Audio Components](http://symmetrica.net/newac/) to be quite good for Delphi. | What's a good API for recording/capturing and playing back sound in Delphi and/or C#? | [
"",
"c#",
"delphi",
"desktop-application",
""
] |
What resources have to be manually cleaned up in *C#* and what are the consequences of not doing so?
For example, say I have the following code:
```
myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
// Use Brush
```
If I don't clean up the brush using the dispose method, I'm assuming the garbage c... | Technically anything that inherits from IDisposable should be proactively disposed. You can use the 'using' statement to make things easier.
<http://msdn.microsoft.com/en-us/library/yh598w02.aspx>
Sometimes you will see inconsistent use of IDisposable derived objects in documentation sample code as well as code that ... | * Handles to internal windows data structures.
* Database connections.
* File handles.
* Network connections.
* COM/OLE references.
The list goes on.
It's important to call `Dispose` or even better yet, use the `using` pattern.
```
using (SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black)... | Resources that have to be manually cleaned up in C#? | [
"",
"c#",
"memory-management",
"resources",
"garbage-collection",
""
] |
I use [XFire](http://xfire.codehaus.org/) to create a webservice wrapper around my application. XFire provides the webservice interface and WSDL at runtime (or creates them at compile time, don't know exactly).
Many of our customers don't know webservices very well and additionally they simply don't read any external ... | XFire is slowly headed for /dev/null. Use [CXF](http://cxf.apache.org/) instead. In other words, XFire is being deprecated in favor of CXF - it's pretty much the same developers.
Since you use the Java-first approach, I suggest you generate you WSDL once and for all with CXF's `java2wsdl` tool, then you put your docum... | > And my last hint regarding CXF - use Aegis for data binding instead of JAXB. It doesn't work for complex POJO.
In my experience we have no problem with complex POJO and JAXB, the only problem is that the code starts to be cluttered with JAXBElements. On the other hand, Aegis documentation is pretty sparse and not we... | How to create documented WSDL using XFire | [
"",
"java",
"web-services",
"documentation",
"wsdl",
"xfire",
""
] |
How do I get a list of all files (and directories) in a given directory in Python? | This is a way to traverse every file and directory in a directory tree:
```
import os
for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in... | You can use
```
os.listdir(path)
```
For reference and more os functions look here:
* Python 2 docs: <https://docs.python.org/2/library/os.html#os.listdir>
* Python 3 docs: <https://docs.python.org/3/library/os.html#os.listdir> | Directory-tree listing in Python | [
"",
"python",
"file",
"directory",
"subdirectory",
"directory-tree",
""
] |
I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.
The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted q... | Make sure you are using lists and no shell expansion:
```
subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)
``` | Try quoting the argument that contains the &
```
wget "http://foo.com/?bar=baz&baz=bar"
```
Is usually what has to be done in a Linux shell | Python subprocess issue with ampersands | [
"",
"python",
"windows",
"subprocess",
"command-line-arguments",
""
] |
I'm trying to run SQuirreL SQL.
I've downloaded it and installed it, but when I try to run it I get this error message:
> Java Virtual Machine Launcher.
> Could not find the main class.
> Program will exit.
I get the gist of this, but I have not idea how to fix it. Any help?
### more info:
* I'm on Windows XP... | Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type 'java' from the command line do you get back a list of instructions or do you get something like "java is not recognized as a .....")?
You could try try running `squirrel-sql.jar` from the command line (from t... | The classpath is the path that the system will follow when trying to find the classes that you're trying to run. In the batch file you're trying to execute it probably has a variable like CLASSPATH=blah;blah;etc or a java command that looks similar to
```
java -classpath "c:\directory\lib\squirrel-sql.jar" com.some.sq... | "Could not find the main class. Program will exit" | [
"",
"java",
"squirrel-sql",
""
] |
I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'.
I've been using the 'Process' class which works... | i would suggest some code that would save your environment variables to an external file, and then you can retrieve these variables via the external file at the start of following processes. | Environment variables are never set and cannot be set for the parent process (\*). Only for the current process and the ones it creates - that is part of the concept.
(\*) apart from, maybe, messing around with OS-internals. | How do I run a series of processes in C# and keep their environment settings? | [
"",
"c#",
"build-process",
"makefile",
"environment",
"auto-build",
""
] |
Last time [I asked about the reverse process](https://stackoverflow.com/questions/169506/get-form-input-fields-with-jquery), and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding f... | When I did this for a project, I found that setting the value of select fields, radio buttons and checkboxes necessitated more complex code, something along the lines of:
```
jQuery.each(data, function (name,value) {
jQuery("input[name='"+name+"'],select[name='"+name+"']").each(function() {
switch (this.nodeName... | If your form elements have their ID set to the fieldname:
```
$.each(myAssocArry, function(i,val) { $('#'+i).val(val); });
``` | Populate a form with data from an associative array with jQuery | [
"",
"javascript",
"jquery",
""
] |
I'll go first.
I'm 100% in the set-operations camp. But what happens when the set logic
on the entire desired input domain leads to a such a large retrieval that the query slows down significantly, comes to a crawl, or basically takes infinite time?
That's one case where I'll use a itty-bitty cursor (or a while loop)... | Sure, there are a number of places where cursors might be better than set-based operations.
One is if you're updating a lot of data in a table (for example a SQL Agent job to pre-compute data on a schedule) then you might use cursors to do it in multiple small sets rather than one large one to reduce the amount of con... | I've got plenty of cases where rows from a configuration table have to be read and code generated and executed, or in many meta-programming scenarios.
There are also cases when cursors simply outperform because the optimizer is not smart enough. In those cases, either there is meta-information in your head which is si... | SQL Cursors...Any use cases you would defend? | [
"",
"sql",
"sql-server",
"t-sql",
"set",
""
] |
In my base page I need to remove an item from the query string and redirect. I can't use
```
Request.QueryString.Remove("foo")
```
because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it? | You'd have to reconstruct the url and then redirect. Something like this:
```
string url = Request.RawUrl;
NameValueCollection params = Request.QueryString;
for (int i=0; i<params.Count; i++)
{
if (params[i].GetKey(i).ToLower() == "foo")
{
url += string.Concat((i==0 ? "?" : "&"), params[i].GetKey(i), ... | You can avoid touching the original query string by working on a copy of it instead. You can then redirect the page to the a url containing your modified query string like so:
```
var nvc = new NameValueCollection();
nvc.Add(HttpUtility.ParseQueryString(Request.Url.Query));
nvc.Remove("foo");
string... | How do I remove items from the query string for redirection? | [
"",
"c#",
"asp.net",
"webforms",
""
] |
Ok I give up, I've been trying to write a regexp in ant to replace the version number from something that I have in a properties file. I have the following:
```
<?xml version="1.0" encoding="UTF-8"?>
<feature
id="some.feature.id"
label="Some test feature"
version="1.0.0"
pro... | Assuming you're using the `replaceregexp` task:
```
<replaceregexp file="whatever"
match="(<feature\b[^<>]+?version=\")[^\"]+"
replace="\1${feature.version}" />
```
I'm also assuming there's only the one `<feature>` element. | The following regex may do what you want...
```
(?<=<feature[^>]{*,1000}version=")[^"]*(?=")
```
Which, in human speak, roughly means
> I want to match text that immediately
> follows the string "<feature", followed by up to a thousand
> characters not the greater-than bracket, and
> "version=""; the text to match i... | Regexp: Substituting a version number in an XML file | [
"",
"java",
"regex",
"ant",
""
] |
What does it take to get C++ **tr1** members (shared\_ptr especially, but we'd like function and bind and ALL the others) working with **GCC 3.4.4** (for the Nokia **N810** tablet computer).
Has anyone done this? Attempted this?
It may **not** be feasible for us to upgrade to GCC 4.x to cross-compile for this device ... | For shared\_ptr from boost, at least, the number of dependencies is pretty small. You can use [bcp](http://www.boost.org/doc/libs/1_36_0/tools/bcp/bcp.html) to extract subsets from boost as well, so you don't need the whole of boost to compile your application. | Are you able to use [Boost](http://www.boost.org/) ([Smart Pointers](http://www.boost.org/libs/smart_ptr/), [Bind](http://www.boost.org/libs/bind/), [Function](http://www.boost.org/libs/function/)) directly? From the [GCC changelogs](http://gcc.gnu.org/gcc-4.0/changes.html), the actual `std::tr1` stuff is only availabl... | C++ tr1 on GCC 3.4.4 (for the Nokia N810 tablet computer) | [
"",
"c++",
"gcc",
"tr1",
""
] |
I have this code:
```
chars = #some list
try:
indx = chars.index(chars)
except ValueError:
#doSomething
else:
#doSomethingElse
```
I want to be able to do this because I don't like knowfully causing Exceptions:
```
chars = #some list
indx = chars.index(chars)
if indx == -1:
#doSomething
else:
#d... | Note that the latter approach is going against the generally accepted "pythonic" philosophy of [EAFP, or "It is Easier to Ask for Forgiveness than Permission."](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Exceptions), while the former follows it. | ```
if element in mylist:
index = mylist.index(element)
# ... do something
else:
# ... do something else
``` | Do I have to cause an ValueError in Python | [
"",
"python",
"exception",
"list",
""
] |
I have have some code which adds new cells to a table and fills them with text boxes.
The way I've coded it so far works fine:
```
TableCell tCell1 = new TableCell();
TableCell tCell2 = new TableCell();
TableCell tCell3 = new TableCell();
TableCell tCell4 = new TableCell();
Tab... | I think this should do it:
```
for (int i = 0; i < 7; i++)
{
TableCell tCell = new TableCell();
TextBox txt = new TextBox();
tCell.Controls.Add(txt);
tRow.Cells.Add(tCell);
}
```
Make sure that 6 is changed to a 7. | This should work fine?
```
for (int i = 0; i < 6; i++)
{
TableCell tCell = new TableCell();
TextBox txt = new TextBox();
tCell.Controls.Add(txt);
tRow.Cells.Add(tCell);
}
```
I don't really get what you need the names for though.
Do you plan on using the "txt5" name as a reference to that specific t... | Creating controls within a Loop | [
"",
"c#",
"asp.net",
".net-2.0",
""
] |
Why is it bad to name a variable `id` in Python? | `id()` is a fundamental built-in:
> Help on built-in function `id` in module
> `__builtin__`:
>
> ```
> id(...)
>
> id(object) -> integer
>
> Return the identity of an object. This is guaranteed to be unique among
> simultaneously existing objects. (Hint: it's the object's memory
> address.)
> ```
I... | In **PEP 8 - Style Guide for Python Code**, the following guidance appears in the section [Descriptive: Naming Styles](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles) :
> * `single_trailing_underscore_` : used by convention to avoid conflicts
> with Python keyword, e.g.
>
> `Tkinter.Toplevel(m... | 'id' is a bad variable name in Python | [
"",
"python",
""
] |
I want to write a raw byte/byte stream to a position in a file.
This is what I have currently:
```
$fpr = fopen($out, 'r+');
fseek($fpr, 1); //seek to second byte
fwrite($fpr, 0x63);
fclose($fpr);
```
This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". ... | `fwrite()` takes strings. Try `chr(0x63)` if you want to write a `0x63` byte to the file. | That's because fwrite() expects a string as its second argument. Try doing this instead:
```
fwrite($fpr, chr(0x63));
```
chr(0x63) returns a string with one character with ASCII value 0x63. (So it'll write the number 0x63 to the file.) | How can I use the PHP File api to write raw bytes? | [
"",
"php",
"file-io",
""
] |
I am creating an HTTP handler that listens for calls to a specific file type, and handles it accordingly. My HTTP Handler listens for .bcn files, then writes a cookie to the user's computer and sends back an image... this will be used in advertising banners so that the user is tagged as seeing the banner, and we can th... | You can access the Response object from the HttpContext object passed to the ProcessRequest method from IHttpHandler. This is the same object exposed by Page.Response. | the ProcessRequest() method defined in IHttpHandler is passed a HttpContext reference. This HttpContext object will have a property named Response and Request, which you can use. | Writing a cookie from an ASP.Net HTTPHandler - Page.Response object? | [
"",
"c#",
"asp.net",
"cookies",
"asp.net-1.1",
""
] |
I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.
How do I ignore this exception (and ignore the protected ... | You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):
```
using System;
using System.IO;
static class Program
{
static void Main()
{
... | Since .NET Standard 2.1 (.NET Core 3+, .NET 5+), you can now just do:
```
var filePaths = Directory.EnumerateFiles(@"C:\my\files", "*.xml", new EnumerationOptions
{
IgnoreInaccessible = true,
RecurseSubdirectories = true
});
```
According to the [MSDN docs](https://learn.microsoft.com/en-us/dotnet/api/system.... | Ignore folders/files when Directory.GetFiles() is denied access | [
"",
"c#",
"getfiles",
""
] |
This code produces a FileNotFoundException, but ultimately runs without issue:
```
void ReadXml()
{
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
//...
}
```
Here is the exception:
---
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Additional in... | This is how I managed to do it by modifying the MSBUILD script in my .CSPROJ file:
First, open your .CSPROJ file as a file rather than as a project. Scroll to the bottom of the file until you find this commented out code, just before the close of the Project tag:
```
<!-- To modify your build process, add your task i... | As Martin has explained in [his answer](https://stackoverflow.com/a/264464/94928), turning on generation of the serialization assembly through the project properties is not enough because the SGen task is adding the `/proxytypes` switch to the sgen.exe command line.
Microsoft has a [documented MSBuild property](http:/... | Generating an Xml Serialization assembly as part of my build | [
"",
"c#",
"xml",
"xml-serialization",
""
] |
```
function returnsAnArray ()
{
return array ('test');
}
echo returnsAnArray ()[0];
```
generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable? | Here's one way, using the [list](http://www.php.net/list) language construct
```
function returnsAnArray ()
{
return array ('test');
}
list($foo)=returnsAnArray();
```
You could grab a sequence of elements from an offset by combining this with [array\_slice](http://www.php.net/array_slice)
```
list($third,$fourth... | Define a new function for returning a specific index from an array.
```
function arr_index($arr, $i) { return $arr[$i]; }
```
You might want to add some error and type checking there.
And then use it like this:
```
echo arr_index(returnsAnArray(), 0);
```
Happy Coding :) | Most efficient way to index a returned array? | [
"",
"php",
""
] |
I want to build a site where the user can enter text and format it in Markdown. The reason I'd like a Javascript solution is because I want to display a live preview, just like on StackOverflow.
My site is not targeted at developers, however, so an editor control would be ideal.
I gather that on StackOverflow, the WM... | If you're not averse to using Ajax to generate the live preview, then another option is [markItUp!](http://markitup.jaysalvat.com/home/). markItUp! is a universal markup-editor, and very flexible. It does provide
an easy way of creating a markup editor, but unlike WMD, it doesn't provide its own live preview.
I used m... | We've been pretty happy with WMD. There are a few niggling bugs in it, however. Nothing major, but I would *love* if John Fraser (the author) made the code open source so we can fix some of them. He's promised to do so but other real life projects are getting in the way.
~~I do follow up with John every week. I'll pos... | Is there any good Markdown Javascript library or control? | [
"",
"javascript",
"controls",
"markdown",
""
] |
I'm trying to use the `this` keyword in a static method, but the compiler won't allow me to use it.
Why not? | That's an easy one. The keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class. There is a much more [in depth explanation](http://msdn.microsoft.com/en-us/l... | As an additional note, from a Static method, you can access or static members of that class. Making the example below valid and at times quite useful.
```
public static void StaticMethod(Object o)
{
MyClass.StaticProperty = o;
}
``` | Why can't you use the keyword 'this' in a static method in .Net? | [
"",
"c#",
".net",
""
] |
Assume the following:
*models.py*
```
class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
```
*admin.py*
```
class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
```
I... | For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not.
Consider this example:
```
def save(self):
from django.tem... | I'm not sure what you're asking for IS possible. Your best bet is probably to hide the slug from the admin interface completely by specifying your fieldsets, and than overriding the save method to copy the slug from the tile, and potentially slugifying it... | Is there a way to define which fields in the model are editable in the admin app? | [
"",
"python",
"django",
""
] |
SQL to find duplicate entries (within a group)
I have a small problem and I'm not sure what would be the best way to fix it, as I only have limited access to the database (Oracle) itself.
In our Table "EVENT" we have about 160k entries, each EVENT has a GROUPID and a normal entry has exactly 5 rows with the same GROUP... | You can get the answer with a join instead of a subquery
```
select
a.*
from
event as a
inner join
(select groupid
from event
group by groupid
having count(*) <> 5) as b
on a.groupid = b.groupid
```
This is a fairly common way of obtaining the all the information out of the rows in a grou... | A classic problem for analytic queries to solve:
```
select eventid,
groupid,
typeid
from (
Select eventid,
groupid,
typeid,
count(*) over (partition by group_id) count_by_group_id
from EVENT
)
where count_by_group_id <> 5
``` | SQL to find duplicate entries (within a group) | [
"",
"sql",
"oracle",
"join",
""
] |
I have a basic C# console application that reads a text file (CSV format) line by line and puts the data into a HashTable. The first CSV item in the line is the key (id num) and the rest of the line is the value. However I've discovered that my import file has a few duplicate keys that it shouldn't have. When I try to ... | ```
if (myHashtable.ContainsKey(key))
duplicates.Add(key);
else
myHashtable.Add(key, value);
``` | A better solution is to call ContainsKey to check if the key exist before adding it to the hash table instead. Throwing exception on this kind of error is a performance hit and doesn't improve the program flow. | C# Exception Handling continue on error | [
"",
"c#",
"exception",
"csv",
""
] |
Sybase db tables do not have a concept of self updating row numbers. However , for one of the modules , I require the presence of rownumber corresponding to each row in the database such that max(Column) would always tell me the number of rows in the table.
I thought I'll introduce an int column and keep updating this... | ## Delete trigger
```
CREATE TRIGGER tigger ON myTable FOR DELETE
AS
update myTable
set id = id - (select count(*) from deleted d where d.id < t.id)
from myTable t
```
## To avoid locking problems
You could add an extra table (which joins to your primary table) like this:
```
CREATE TABLE rowCounter
(id int... | You can easily assign a unique number to each row by using an identity column. The identity can be a numeric or an integer (in ASE12+).
This will *almost* do what you require. There are certain circumstances in which you will get a gap in the identity sequence. (These are called "identity gaps", the best discussion on... | Row number in Sybase tables | [
"",
"sql",
"sybase",
""
] |
I am looking for a pseudo random number generator which would be specialized to work fast when it is given a seed before generating each number. Most generators I have seen so far assume you set seed once and then generate a long sequence of numbers. The only thing which looks somewhat similar to I have seen so far is ... | Seems like you're asking for a hash-function rather than a PRNG. Googling 'fast hash function' yields several promising-looking results.
[For example](http://burtleburtle.net/bob/hash/integer.html):
```
uint32_t hash( uint32_t a)
a = (a ^ 61) ^ (a >> 16);
a = a + (a << 3);
a = a ^ (a >> 4);
a = a * 0x... | Yep, you are looking for a fast integer hash algorithm rather than a PRNG.
This [page](http://www.concentric.net/~Ttwang/tech/inthash.htm) has a few algorithms, I'm sure you'll find plenty more now you know the correct search terms.
**Edit**: The original page has been removed, a live version can be [found on GitHub]... | Fast pseudo random number generator for procedural content | [
"",
"c++",
"x86",
"random",
""
] |
I recently began profiling an osgi java application that I am writing using VisualVM. One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate. The Heap size and the PermGen size remains constant, however. The numbe... | > Are you dynamically creating new classes on the fly somehow?
Thanks for your help. I figured out what the problem is. In one of my classes, I was using Jaxb to create an XML string. In doing this, JAXB ueses reflection to create a new class.
```
JAXBContext context = JAXBContext.newInstance(this.getClass());
```
S... | You might find some hotspot flags to be of use in understanding this behavior like:
* -XX:+TraceClassLoading
* -XX:+TraceClassUnloading
This is a good reference:
<http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp> | Possible Memory leak in Number of Loaded classes in Java Application | [
"",
"java",
"profiling",
""
] |
What's a simple way to implement a c++ Win32 program to...
- display an 800x600x24 uncompressed bitmap image
- in a window without borders (the only thing visible is the image)
- that closes after ten seconds
- and doesn't use MFC | You can:
* Create a dialog in your resource file
* Have it contain a Picture control
* Set the picture control type to Bitmap
* Create/import your bitmap in the resource file and set that bitmap ID to the picture control in your dialog
* Create the window by using CreateDialogParam
* Handle the WM\_INITDIALOG in order... | If you're targeting modern versions of Windows (Windows 2000) and above, you can use the [UpdateLayeredWindow](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-updatelayeredwindow) function to display any bitmap (including one with an alpha channel, if so desired).
I [blogged a four-part series](... | Quickest way to implement a C++ Win32 Splash Screen | [
"",
"c++",
"winapi",
""
] |
When viewing someone else's webpage containing an applet, how can I force Internet Explorer 6.0 to use a a particular JRE when I have several installed? | If you mean when you are not the person writing the web page, then you could disable the add ons you do not wish to use with the [Manage Add-Ons](http://windowsxp.mvps.org/addons.htm) IE Options screen added in Win XP SP2 | First, disable the currently installed version of Java. To do this, go to **Control Panel > Java > Advanced > Default Java for Browsers** and uncheck **Microsoft Internet Explorer**.
Next, enable the version of Java you want to use instead. To do this, go to (for example) **C:\Program Files\Java\*jre1.5.0\_15*\bin** (... | Force Internet Explorer to use a specific Java Runtime Environment install? | [
"",
"internet-explorer",
"internet-explorer-6",
"java",
"plugins",
""
] |
How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.
I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it. | Here's my suggestion:
```
[Flags]
public enum ThreadAccess : int
{
TERMINATE = (0x0001),
SUSPEND_RESUME = (0x0002),
GET_CONTEXT = (0x0008),
SET_CONTEXT = (0x0010),
SET_INFORMATION = (0x0020),
QUERY_INFORMATION = (0x0040),
SET_THREAD_TOKEN = (0x0080),
IMPERSONATE... | Thanks to Magnus
After including the Flags, I modified the code a bit to be an extension method in my project. I could now use
```
var process = Process.GetProcessById(param.PId);
process.Suspend();
```
Here is the code for those who might be interested.
```
public static class ProcessExtension
{
[DllImport("ke... | Suspend Process in C# | [
"",
"c#",
".net",
""
] |
I have a class that looks like this
```
public class SomeClass
{
public SomeChildClass[] childArray;
}
```
which will output XML from the XMLSerializer like this:
```
<SomeClass>
<SomeChildClass>
...
</SomeChildClass>
<SomeChildClass>
...
</SomeChildClass>
</SomeClass>
```
But I want the... | The best approach would be to do what you said and add a property to the "SomeChildClass" like this
```
[XmlAttribute("Index")]
public int Order
{ { get; set; } }
```
Then however you are adding these items to your array, make sure that this property get's set. Then when you serialize....Presto! | You may need to look into implementing System.Xml.Serialization.IXmlSerializable to accomplish this. | Including arrary index in XML Serialization | [
"",
"c#",
".net",
"xml-serialization",
""
] |
I have returned to php development from [Moose](http://www.iinteractive.com/moose/) and I really miss CLOS like object model for php. Is there some kind of syntaxtic sugar which would allow me to write **less code** in php when dealing with objects?
Just to stress this requirement a bit more. I don't want to write one... | There is also new project <http://github.com/huberry/phuby> which implements roles in php! | There are no mixins in php yet but there is an RFC for traits which will work roughly the same. <http://wiki.php.net/rfc/traits>
Using overloading for \_\_call can allow you to dispatch methods to other classes and have it look like a mixin. | CLOS like object model for PHP | [
"",
"php",
"oop",
"moose",
"clos",
""
] |
What is the difference between g++ and gcc? Which one of them should be used for general c++ development? | `gcc` and `g++` are compiler-drivers of the GNU Compiler *Collection* (which was once upon a time just the GNU *C Compiler*).
Even though they automatically determine which backends (`cc1` `cc1plus` ...) to call depending on the file-type, unless overridden with `-x language`, they have some differences.
The probably... | GCC: GNU Compiler Collection
* Referrers to all the different languages that are supported by the GNU compiler.
`gcc`: GNU C Compiler
`g++`: GNU C++ Compiler
The main differences:
1. `gcc` will compile: `*.c\*.cpp` files as C and C++ respectively.
2. `g++` will compile: `*.c\*.cpp` files but they will all be... | What is the difference between g++ and gcc? | [
"",
"c++",
"gcc",
"g++",
""
] |
From [Wikipedia](http://en.wikipedia.org/wiki/Generic_programming):
> Generic programming is a style of
> computer programming in which
> algorithms are written in terms of
> to-be-specified-later types that are
> then instantiated when needed for
> specific types provided as parameters
> and was pioneered by Ada whic... | C# and VB have generics to take advantage of generics support in the underlying CLR (or is the other way around?). They allow you to write code ina statically-typed language that can apply to more than one kind of type without rewriting the code for each type you use them for (the runtime will do that for you) or other... | Personally, I think they allows to save a lot of time. I'm still using .NET Framework 1.1 and every time you want a specific collection, you need to create a strongly typed collection by implementing CollectionBase. With Generics, you just need to declare your collection like that `List<MyObject>` and it's done. | Why do C# and VB have Generics? What benefit do they provide? Generics, FTW | [
"",
"c#",
".net",
"vb.net",
"generics",
""
] |
I just want a simple tool that will help me quickly write scripts/packages that I can schedule to run. My transform requirements are pretty simple (changing column names, merging/splitting tables, and date conversions). I'll sacrifice flexibility for speed of development on this one.
Any come to mind? | SQL Server 2005? SSIS (but I wouldn't call it simple, but then again out of the list of things you gave, only the naming is really simple)
You can actually script package creation using C# (.NET/whatever, presumably even PowerShell).
Resources [here](http://blogs.conchango.com/jamiethomson/archive/2007/03/28/SSIS_3A0... | I like the Pentaho Data Integration tool (also known as kettle) - although that might be a bit "too big for you .. but worth checking out! | Tool: ETL from an ODBC to SQL 05? | [
"",
"sql",
"database",
"odbc",
"etl",
""
] |
When I try this with a generic class where this.value is T:
```
if (this.value.GetType() == typeof(int))
{
((int)this.value)++;
}
else
{
throw new InvalidOperationException
("T must be an int to perform this operation");
}
```
I get a compile-time error: "Cannot convert type 'T' to 'int'"
What sh... | Unfortunately, it is very hard to convince the compiler about specific T implementations. One (nasty) approach is to cast to object in the middle (note this will box and unbox value-types):
```
int i = (int)(object)this.value;
i++;
this.value = (T)(object)i;
```
Ugly but it works. In .NET 3.5 I have some better wrapp... | In my opinion, type-specific code in a generic class is a code smell. I would refactor it to get something like this:
```
public class MyClass<T>
{
...
}
public class IntClass : MyClass<int>
{
public void IncrementMe()
{
this.value++;
}
}
``` | Typing generic values (C#) | [
"",
"c#",
"generics",
""
] |
It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list:
* Window position same as it was
+ Unless the screen has resized and the old position is now off screen.
* Splitters should retain their position
* ... | My other option is to write more custom code around the application settings and execute it on formLoad and formClosed. This doesn't use data binding.
Drawbacks:
* More code to write.
* Very fiddly. The order you set the properties on formLoad is confusing. For example, you have to make sure you've set the window siz... | The sample below shows how I do it
* SavePreferences is called when closing the form and saves the form's size, and a flag indicating if it's maximized (in this version I don't save if it's minimized - it will come back up restored or maximized next time).
* LoadPreferences is called from OnLoad.
* First save the desi... | How to record window position in Windows Forms application settings | [
"",
"c#",
".net",
"winforms",
"settings",
""
] |
I am looking for a toolkit that will allow me to design widgets containing 2D graphics for an elevator simulation in Java. Once created, those widgets will be integrated with SWT, Swing, or QtJambi framework.
Background information:
I am developing an Elevator Simulator for fun. My main goal is to increase my knowled... | You can use an SWT canvas (or Swing canvas, or OpenGL canvas via JOGL, ...), and set it up as an Observer of your simulation, and whenever the simulation state changes, you can redraw the new state. | You could get some abstract graphics out of a Graph visualisation tool such as [JGraph](http://jgraph.com/). You could use this to visualise which state your elevator is in. However, i'm not sure how flexible these sort of graph visualisation tools are and whether you can add your own graphics and animations. | Selecting proper toolkit for a 2D simulation project in Java | [
"",
"java",
"graphics",
"simulation",
""
] |
Is it possible to retrieve items from a Python dictionary in the order that they were inserted? | The standard Python `dict` does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python).
On older versions of Python you can use [`collections.OrderedDict`](https://docs.python.org/library/collections.html#ordereddict-objects). | As of Python 3.7, the standard dict preserves insertion order. From the [docs](https://docs.python.org/3.7/library/stdtypes.html#mapping-types-dict):
> Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.
So, you should be able to i... | How do you retrieve items from a dictionary in the order that they're inserted? | [
"",
"python",
"dictionary",
""
] |
How would I have a [JavaScript](http://en.wikipedia.org/wiki/JavaScript) action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?
It would also be nice if the back button would reload the original URL.
I am try... | With HTML 5, use the [`history.pushState` function](http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html). As an example:
```
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElem... | If you want it to work in browsers that don't support `history.pushState` and `history.popState` yet, the "old" way is to set the fragment identifier, which won't cause a page reload.
The basic idea is to set the `window.location.hash` property to a value that contains whatever state information you need, then either ... | Change the URL in the browser without loading the new page using JavaScript | [
"",
"javascript",
"url",
"html5-history",
"fragment-identifier",
"hashchange",
""
] |
Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page\_Load event through codebehind works, but is less clear than... | `**`*just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.*
Every ASP.NET page (2.0 and greater) comes with a [ClientScriptManager](http://msdn.microsoft.com/en-us/library/... | You can add the events through Javascript to the HTML elements that you want. This is the cleanest way, since it doesn't mix the server&client technologies. Furthermore, this way many handlers can be registered to the same event (in contrast to the onclick attribute).
Basically, the code would be
```
document.getElem... | Using Javascript With ASP.Net controls | [
"",
"asp.net",
"javascript",
"events",
""
] |
I am creating a decoupled WMI provider in a class library. Everything I have read points towards including something along these lines:
```
[System.ComponentModel.RunInstaller(true)]
public class MyApplicationManagementInstaller : DefaultManagementInstaller { }
```
I gather the purpose of this installation is because... | As I understand, DefaultManagementInstaller is ran by installutil.exe - if you don't include it, the class is not installed in WMI. Maybe it is possible to create a 'setup project' or 'installer project' that runs it, but I'm not sure because I don't use Visual Studio.
[edit]
for remote instalation, an option could b... | I use something like this to call InstallUtil programmatically:
```
public static void Run( Type type )
{
// Register WMI stuff
var installArgs = new[]
{
string.Format( "//logfile={0}", @"c:\Temp\sample.InstallLog" ), "//... | The RunInstaller attribute in a WMI provider assembly | [
"",
"c#",
"windows",
"wmi",
""
] |
Say I have two tables I want to join.
Categories:
```
id name
----------
1 Cars
2 Games
3 Pencils
```
And items:
```
id categoryid itemname
---------------------------
1 1 Ford
2 1 BMW
3 1 VW
4 2 Tetris
5 2 Pong
6 3 Fo... | Just done a quick test. This seems to work:
```
mysql> select * from categories c, items i
-> where i.categoryid = c.id
-> group by c.id;
+------+---------+------+------------+----------------+
| id | name | id | categoryid | name |
+------+---------+------+------------+----------------+
| ... | Mysql lets you to have columns not included in grouping or aggregate, in which case they've got random values:
```
select category.id, category.name, itemid, itemname
inner join
(select item.categoryid, item.id as itemid, item.name as itemname
from item group by categoryid)
on category.id = c... | MySQL Query: LIMITing a JOIN | [
"",
"mysql",
"sql",
"join",
"greatest-n-per-group",
""
] |
I am trying to write a Windows Form and ASP.NET C# front-end and MSAccess backend for a pretty small database concept I have.
I have written this application once before in just MSAccess but I now need the app and database to be in different places. I have now figured out (thanks to a StackOverflow user) that ADO will... | I haven't used this but it looks like it might be a good fit:
<http://www.codeproject.com/KB/database/DBaseFactGenerics.aspx> | Take a look at the MySQL .net connector. It is the nuts and bolts of how the ADO.net classes talk to the DB engine. ADO.net as a whole does not keep connections open. Certain higher level classes do. Technically the lower level objects such as the connection and command objects are part of ADO.net, but you have a high ... | Where can I find an open source C# project that uses ADO.NET? | [
"",
"c#",
"database",
"open-source",
"ado.net",
""
] |
I would like to add a typing speed indicator just below the textarea we use on our contact form. It is just for fun and to give the user some interactivity with the page while they are completing the form.
It should display the average speed while typing and keep the last average when the keystrokes are idle. When the... | Here's a tested implementation,which seems ok, but I don't guarantee the math.
A Demo: <http://jsfiddle.net/iaezzy/pLpx5oLf/>
And the code:
```
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns... | It's my own ego involvement:
```
<textarea id="b" onblur="clc();"></textarea>
<script>
t=0;
document.getElementById('b').onkeypress=function()
{
t==0 ? s=new Date() : e=new Date();
t=1;
}
function clc()
{
d = e.getTime() - s.getTime();
c = b.value.length;
b.value += "\n"+c+"s in "+d+"ms: "+c/d+" cpms";
}
</script>
```... | How can you display Typing Speed using Javascript or the jQuery library? | [
"",
"javascript",
""
] |
If I open a file using urllib2, like so:
```
remotefile = urllib2.urlopen('http://example.com/somefile.zip')
```
Is there an easy way to get the file name other then parsing the original URL?
EDIT: changed openfile to urlopen... not sure how that happened.
EDIT2: I ended up using:
```
filename = url.split('/')[-1]... | Did you mean [urllib2.urlopen](http://www.python.org/doc/2.5.2/lib/module-urllib2.html#l2h-3928)?
You could potentially lift the *intended* filename *if* the server was sending a Content-Disposition header by checking `remotefile.info()['Content-Disposition']`, but as it is I think you'll just have to parse the url.
... | If you only want the file name itself, assuming that there's no query variables at the end like <http://example.com/somedir/somefile.zip?foo=bar> then you can use os.path.basename for this:
```
[user@host]$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
Type "help", "copyright", "credits" or "license" for mo... | urllib2 file name | [
"",
"python",
"url",
"urllib2",
""
] |
I have an application that seems to throw exceptions only after the program has been closed. And it is very inconsistent. (We all know how fun inconsistent bugs are...)
My guess is there is an error during the clean up process. But these memory read/write errors seem to indicate something wrong in my "unsafe" code usa... | If your app is multi-threaded you could be getting errors from worker threads which aren't properly terminating and trying to access disposed objects. | I had this problem using AcrobarReader COM component. Every now and then after application exit I had "Application.vshost.exe - Application Error" "memory could not be read". GC.Collect() and WaitForPendingFinalizers() didn't help.
My google-fu lead me to this page: <http://support.microsoft.com/kb/826220>. I modified... | Exceptions Thrown (Errors Encountered) After Program Termination | [
"",
"c#",
"vb.net",
"unsafe",
""
] |
I have a class holding complex scientific computations. It is set up to only allow a user to create a properly instantiated case. To properly test the code, however, requires setting internal state variables directly, since the reference documents supply this data in their test cases. Done improperly, however, it can i... | Suppose you want to test this object by manipulating its fields.
```
public class ComplexCalculation
{
protected int favoriteNumber;
public int FavoriteNumber
{
get { return favoriteNumber; }
}
}
```
Place this object in your test assembly/namespace:
```
public class ComplexCalculationTest : ... | You can use [InternalsVisibleToAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) to mark internal members as visible to your test assembly. It seems to shine when used in this context, though its not quite "friend".
1. Mark your `DangerousSet` function... | Hiding a function | [
"",
"c#",
"visual-studio",
"intellisense",
""
] |
I encountered the following ddl in a pl/sql script this morning:
create index genuser.idx$$\_0bdd0011
...
My initial thought was that the index name was generated by a tool...but I'm also not a pl/sql superstar so I could very well be incorrect. Does the double dollar sign have any special significance in this statem... | Your initial thought seems to be correct. That would look to be an index name generated by a tool (but not assigned by Oracle because an index name wasn't specified). Dollar signs don't have any particular meaning other than being valid symbols that are rarely used by human developers and so are handy to reduce the ris... | No special meaning or significance.
```
SQL> create table t (col number)
2 /
Table created.
SQL> create index idx$$_0bdd0011 on t(col)
2 /
Index created.
```
Note: CREATE INDEX is a DDL statement which is usually executed in a SQL script, not in PL/SQL. | pl/sql dollar operator? | [
"",
"sql",
"database",
"oracle",
""
] |
I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date.
I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest... | Here's a solution using only standard SQL, not ISNULL(). That function is not standard SQL, and may not work on other brands of RDBMS.
```
SELECT * FROM myTable
WHERE ...
ORDER BY CASE WHEN myDate IS NULL THEN 1 ELSE 0 END, myDate;
``` | ```
SELECT * FROM myTable
WHERE ...
ORDER BY ISNULL(myDate), myDate
``` | Possible to use SQL to sort by date but put null dates at the back of the results set? | [
"",
"sql",
"mysql",
""
] |
I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution:
```
Vector itemsVector = getItems();
Collections.shuffle(itemsVector);
itemsVector.setSize(5);
``... | Jon Bentley discusses this in either 'Programming Pearls' or 'More Programming Pearls'. You need to be careful with your N of M selection process, but I think the code shown works correctly. Rather than randomly shuffle all the items, you can do the random shuffle only shuffling the first N positions - which is a usefu... | @Jonathan,
I believe this is the solution you're talking about:
```
void genknuth(int m, int n)
{ for (int i = 0; i < n; i++)
/* select m of remaining n-i */
if ((bigrand() % (n-i)) < m) {
cout << i << "\n";
m--;
}
}
```
It's on page 127 of Programming Pearls b... | best way to pick a random subset from a collection? | [
"",
"java",
"algorithm",
"collections",
"random",
"subset",
""
] |
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.
Example:
```
public class MyGenericClass<T> {
public void doSomething() {
// Snip...
// Call to a 3rd party lib
... | Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :
```
public class MyGenericClass<T> {
private final Class<T> clazz;
public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
... | I was just pointed to this solution:
```
import java.lang.reflect.ParameterizedType;
public abstract class A<B> {
public Class<B> g() throws Exception {
ParameterizedType superclass =
(ParameterizedType) getClass().getGenericSuperclass();
return (Class<B>) superclass.getActualTypeArgu... | How to determine the class of a generic type? | [
"",
"java",
"generics",
""
] |
I have a photo website and i want to support tags as my original category bucketing is starting to fail (some pictures are family and vacations, or school and friends). Is there an agreed tagging db schema?
I still want to support having photos as part of an album.
Right now i have a few tables:
**Photos**
* PhotoI... | There are various schemas which are effective, each with their own performance implications for the common queries you'll need as the number of tagged items grows:
* <http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/>
* <http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/>
Personall... | I've done this in a small system without very many users, but I've wondered before if there was an "accepted" way to manage tags. After reading through the links posted by insin and plenty of other blog posts on tagging, it seems that the accepted way is to store it fully normalized and cache certain things if your dat... | Is there an agreed ideal schema for tagging | [
"",
"sql",
"schema",
"tagging",
""
] |
I'd like to eliminate dependencies on hardcoded paths for configuration data in my Java apps, I understand that using ResourceBundle will help me use the classloader to find resources.
Can someone tell me how I would replace a hardcoded path to a resource (say a .properties configuration data file required by a class)... | Prior to Java 6, ResourceBundle typically allowed:
* Strings from a group of localised properties files, using [PropertyResourceBundle](http://java.sun.com/javase/6/docs/api/java/util/PropertyResourceBundle.html)
* Objects from a group of localised classes, using [ListResourceBundle](http://java.sun.com/javase/6/docs/... | You will want to examine [Resource.getBundle(String)](http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.html#getBundle(java.lang.String) "Resource Bundle Javadoc"). You pass it the fully qualified name of a resource on the classpath to load as a properties file. | How do I use ResourceBundle to avoid hardcoded config paths in Java apps? | [
"",
"java",
"config",
"resourcebundle",
""
] |
I am supposed to provide my users a really simple way of capturing video clips out of my OpenGL application's main window. I am thinking of adding buttons and/or keyboard shortcuts for starting and stopping the capture; when starting, I could ask for a filename and other options, if any. It has to run in Windows (XP/Vi... | There are two different questions here - how to grab frames from an OpenGL application, and how to turn them into a movie file.
The first question is easy enough; you just grab each frame with glReadPixels() (via a PBO if you need the performance).
The second question is a little harder since the cross-platform solut... | [This](http://www.codeproject.com/KB/audio-video/avigenerator.aspx) does look pretty relevant for merging into an AVI (as suggested by Andrew), however I was really hoping to avoid the LPBITMAPINFOHEADERs etc.
Thanks for the answers, I will report on the success if there is going to be any :)
In the meantime, additio... | Capturing video out of an OpenGL window in Windows | [
"",
"c++",
"opengl",
"video",
"screenshot",
"video-capture",
""
] |
I have fname and lname in my database, and a name could be stored as JOHN DOE or john DOE or JoHN dOE, but ultimately I want to display it as John Doe
fname being John and lname being Doe | seeing it is tagged PHP:
either
> `string ucfirst ( string $str );`
to uppercase first letter of the first word
or
> `string ucwords ( string $str );`
to uppercase the first letter of every word
you might want to use those in combination with
> `string strtolower ( string $str );`
to normalize all names to lo... | Be aware that there are other capitalisation formats, such as John McDoe, John D'Oe, John de O, and John van den Doe. | How do I display the first letter as uppercase? | [
"",
"php",
"mysql",
""
] |
I'm attempting to use extension methods to add an operater overload to the C# `StringBuilder` class. Specifically, given `StringBuilder` `sb`, I'd like `sb += "text"` to become equivalent to `sb.Append("text")`.
Here's the syntax for creating an extension method for `StringBuilder`:
```
public static class sbExtensio... | This is not currently possible, because extension methods must be in static classes, and static classes can't have operator overloads. But the [feature is being discussed for *some* future release of C#](https://github.com/dotnet/csharplang/issues/192). Mads talked a bit more about implementing it [in this video from 2... | If you control the places where you want to use this "extension operator" (which you normally do with extension methods anyway), you can do something like this:
```
class Program {
static void Main(string[] args) {
StringBuilder sb = new StringBuilder();
ReceiveImportantMessage(sb);
Console.WriteLine(sb... | Operator Overloading with C# Extension Methods | [
"",
"c#",
"extension-methods",
"operator-overloading",
""
] |
I have a project that I'm working on and I need to be able to print out ID cards from the program. Are there any products out there that are reasonably priced so I can design a document for print and use it in .NET? I'm trying to avoid using System.Drawing from having to do it manually because when the company I work f... | You could use Adobe Acrobat and one of the libraries out there for writing PDFs. That would let you design the document template in Adobe Acrobat, fill it out in code, and print it in code. There are some open source PDF writers and some commercial ones. The differences lie in the feature sets.
I've used [PDFWriter](h... | I've done something similar using a PowerPoint document as a template. I put fields or labels on the PP document and then programmatically fill them in. Obviously, adding or removing fields would require code changes, but the layout of the PP document could be changed easily. | Visual Print Design for .NET | [
"",
"c#",
".net",
"vb.net",
"printing",
""
] |
C++ preprocessor `#define` is totally different.
Is the PHP `define()` any different than just creating a var?
```
define("SETTING", 0);
$something = SETTING;
```
vs
```
$setting = 0;
$something = $setting;
``` | 'define' operation itself is rather slow - confirmed by xdebug profiler.
Here is benchmarks from <http://t3.dotgnu.info/blog/php/my-first-php-extension.html>:
* pure 'define'
380.785 fetches/sec
14.2647 mean msecs/first-response
* constants defined with 'hidef' extension
930.783 fetches/sec
6.30279 me... | In general, the idea of a constant is to be *constant*, (Sounds funny, right? ;)) inside your *program*. Which means that the compiler (interpreter) will replace "FOOBAR" with FOOBAR's value throughout your entire script.
So much for the theory and the advantages - if you compile. Now PHP is pretty dynamic and in most... | How efficient is define in PHP? | [
"",
"php",
"c-preprocessor",
""
] |
If I have two dates (ex. `'8/18/2008'` and `'9/26/2008'`), what is the best way to get the number of days between these two dates? | If you have two date objects, you can just subtract them, which computes a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object.
```
from datetime import date
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)
```
The relevant section of the docs:
<htt... | Using the power of datetime:
```
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print(delta.days)
# that's it how to calculate number of days between two given dates
``` | How to calculate number of days between two given dates | [
"",
"python",
"date",
"datetime",
""
] |
I've written a small service (plain Win32) and I'd like to know if it's possible to run multiple instances of it when multiple users are logged on.
Basically, let's say we've got UserA and UserB for UserA the service would log on as "domain\UserA" and for UserB the service would log on as "domain\UserB" - this is from... | Win32 services are designed to be system-wide, and start running before any user is logged in. If you want something to run on a per-user basis, it's probably better to design it as a regular application and run it from the user's Startup group. | Running with different accounts is possible. In fact, this is common. See svchost.exe, which implements a bunch of OS services.
I just don't get how you determine which accounts. In a big company, many PCs are set up so all 100.000+ employees could use it. You don't want to run your service as the logged-in users, nor... | Multiple services from the same executable | [
"",
"c++",
"winapi",
"service",
""
] |
last time I asked how to populate a data structure [here](https://stackoverflow.com/questions/144474/java-arrays-vectors). Now I would like to know if there's something in Java, like the [print\_r](http://www.php.net/print_r) I use in PHP, to represent what I have populated in the Maps and lists without having to do my... | Calling `toString` on the collection should return a string containing all the elements string representations.
This won't work with built-in arrays though, as they don't have a `toString` override and will just give you a memory address. | There is really difference between toString() in java and print\_r() in PHP.
Note that there is also \_\_toString() in php which is equivalent to toString() in java, so this is not really the answer.
print\_r is used when we have a structure of objects and we like quickly to see the complete graph of objects with thei... | Equivalent of PHP's print_r in Java? | [
"",
"java",
"data-structures",
""
] |
If you are creating a 1d array in Python, is there any benefit to using the NumPy package? | It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the [array](https://docs.python.org/3/library/array.html) module will do just fine.
If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide... | Small bootstrapping for the benefit of whoever might find this useful (following the excellent answer by @dF.):
```
import numpy as np
from array import array
# Fixed size numpy array
def np_fixed(n):
q = np.empty(n)
for i in range(n):
q[i] = i
return q
# Resize with np.resize
def np_class_resize... | array.array versus numpy.array | [
"",
"python",
"arrays",
"numpy",
""
] |
I have an application written in java, and I want to add a flash front end to it. The flash front end will run on the same computer as the java app in the stand alone flash player. I need two way communication between the two parts, and have no idea how to even start going about this. I suppose I could open a socket be... | [AMF](http://en.wikipedia.org/wiki/Action_Message_Format) is a messaging protocol commonly used to talk between flash and a backend system. There're several Java implementations, but I haven't used any of them so can't tell you which is best.
* [Blaze DS](http://labs.adobe.com/technologies/blazeds/)
* [Red5](http://ww... | There is also **[OpenAMF](http://sourceforge.net/projects/openamf/)**. It is *very* mature, stable, simple and lightweight relative to Blaze, Red5 and Granite.
**BUT**, it is also dated (AMF0 protocol only) and the project is no longer active. Lots of people are still using it out in the wild. And the documentation is... | Getting java and flash to talk to each other | [
"",
"java",
"flash",
""
] |
I'm using the wxGlade designer to generate the GUI for a small application.
It generates a class, inherited from wxFrame, which is the main application window.
In order to facilitate the maintenance, I'd like to avoid writing additional code in this generated class.
But all the widgets created with the wxGlade are act... | All classes inherited from wxWindow (wxFrame being one of them) have a function "[GetChildren](http://docs.wxwidgets.org/stable/wx_wxwindow.html#wxwindowgetchildren)", which returns a list of child windows that you can then enumerate over. If you are looking for a specific field by name then use the "[FindWindow](http:... | Actually I found the answer myself:
```
wxWindowList & children = myframe->GetChildren();
for ( wxWindowList::Node *node = children.GetFirst(); node; node = node->GetNext() )
{
wxWindow *current = (wxWindow *)node->GetData();
// .. do something with current
}
``` | Is it possible to enumerate the wxFrame children in wxWidgets? | [
"",
"c++",
"user-interface",
"wxwidgets",
"wxglade",
""
] |
Specifically MSSQL 2005. | Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005.
```
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
```
To understand how it works we have to look at the [dateadd()](... | ```
SELECT DATEADD(M, DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), '1990-01-31T00:00:00.000')
```
Explanation:
General approach: use temporal functionality.
```
SELECT '1990-01-01T00:00:00.000', '1990-01-31T00:00:00.000'
```
These are DATETIME literals, being the first time granule on the first day an... | How do I calculate the last day of the month in SQL? | [
"",
"sql",
"sql-server",
"t-sql",
"date",
""
] |
I'm getting an unexpected T\_CONCAT\_EQUAL error on a line of the following form:
```
$arg1 .= "arg2".$arg3."arg4";
```
I'm using PHP5. I could simply go an do the following:
```
$arg1 = $arg1."arg2".$arg3."arg4";
```
but I'd like to know whats going wrong in the first place. Any ideas?
Thanks,
sweeney | This would happen when $arg1 is undefined (doesn't have a value, was never set.) | So the most accurate reason is that the above posted line of code:
```
$arg1 .= "arg2".$arg3."arg4";
```
was actually as follows in my source:
```
arg1 .= "arg2".$arg3."arg4";
```
The $ was missing from arg1. I dont know why the interpreter did not catch that first, but whatever. Thanks for the input Jeremy and Bai... | unexpected T_CONCAT_EQUAL | [
"",
"php",
"string",
"concatenation",
""
] |
I have a an HTML form which contains the YAHOO rich text editor on it.
When I display the form I want the YAHOO editor to have focus so that the cursor is ready to accept input without the user having to click on it or tab into it | I got this from the documenation over at the [YUI library](http://developer.yahoo.com/yui). Specifically at a sample titled [Editor - Basic Buttons](http://developer.yahoo.com/yui/examples/editor/editor_adv_editor.html)
> `var myEditor = new YAHOO.widget.Editor('editor', {focusAtStart:true});`
> `myEditor.render();`... | Like roenving, I have never used the YAHOO rich text editor, but it should work with the `window.onload` event.
Let's say you specified `id="yahoo_text_editor"` for your YAHOO rich text editor.
Then, do
```
<body onload="document.getElementById('yahoo_text_editor').focus()">
```
Hope this helps. | How can I set the focus inside the Yahoo Rich Text Editor | [
"",
"javascript",
"html",
"richtext",
""
] |
I would like to format a price in JavaScript. I'd like a function which takes a `float` as an argument and returns a `string` formatted like this:
```
"$ 2,500.00"
```
How can I do this? | Ok, based on what you said, I'm using this:
```
var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);
var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (... | # [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/NumberFormat)
JavaScript has a number formatter (part of the Internationalization API).
```
// Create our number formatter.
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
/... | How to format numbers as currency strings | [
"",
"javascript",
"formatting",
"currency",
""
] |
Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.
Particular order doesn't matter much here.
I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask. | ```
#include <stdint.h>
#include <stdio.h>
union ui64 {
uint64_t one;
uint16_t four[4];
};
int
main()
{
union ui64 number = {0x123456789abcdef0};
printf("%x %x %x %x\n", number.four[0], number.four[1],
number.four[2], number.four[3]);
return 0;
}
``` | ```
(unsigned short)((((unsigned long long int)value)>>(x))&(0xFFFF))
```
where `value` is your `long long int`, and `x` is 0, 16, 32 or 48 for the four shorts. | How to extract four unsigned short ints from one long long int? | [
"",
"c++",
"c",
"64-bit",
"bit-manipulation",
""
] |
Is there a way to make a popup window maximised as soon as it is opened? If not that, at least make it screen-sized? This:
```
window.open(src, 'newWin', 'fullscreen="yes"')
```
apparently only worked for old version of IE. | Use `screen.availWidth` and `screen.availHeight` to calculate a suitable size for the height and width parameters in `window.open()`
Although this is likely to be close, it will not be maximised, nor accurate for everyone, especially if all the toolbars are shown. | What about this:
```
var popup = window.open(URL);
if (popup == null)
alert('Please change your popup settings');
else {
popup.moveTo(0, 0);
popup.resizeTo(screen.width, screen.height);
}
``` | How to show fullscreen popup window in javascript? | [
"",
"javascript",
"html",
"popup",
""
] |
I am am trying to load a SQL table from a flat file. The flat i am talking about is a comma separated file. This has all the data required to populate a table will each column separated by a comma ",". I need some way by which i can load this content into the table faster. | If you are using SQL Server, use [`BULK INSERT`](http://msdn.microsoft.com/en-us/library/ms188365.aspx)
If you are using Oracle, see my answer [here](https://stackoverflow.com/questions/120001/load-excel-data-sheet-to-oracle-database#120021) | Regardless of what database management system you are using, you could use a scripting language (such as perl or php) to set up a connection to your database, parse the file, and then insert the data into your database. Of course, you would have to know a scripting language... | LOAD SQL Table from flat file | [
"",
"sql",
"sql-server-2005",
""
] |
In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture.
I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If th... | Why are you choosing one block over the other? If your decision is based on the size of a pointer, use `sizeof(void*) == 8`. If your decision is based on the size of an integer, use `sizeof(int) == 8`.
My point is that the name of the architecture itself should rarely make any difference. You check only what you need ... | An architecture-independent way to detect 32-bit and 64-bit builds in C and C++ looks like this:
```
// C
#include <stdint.h>
// C++
#include <cstdint>
#if INTPTR_MAX == INT64_MAX
// 64-bit
#elif INTPTR_MAX == INT32_MAX
// 32-bit
#else
#error Unknown pointer size or missing size macros!
#endif
``` | How can I detect if I'm compiling for a 64bits architecture in C++ | [
"",
"c++",
"64-bit",
"c-preprocessor",
""
] |
What is the easiest way to test (using reflection), whether given method (i.e. java.lang.Method instance) has a return type, which can be safely casted to List<String>?
Consider this snippet:
```
public static class StringList extends ArrayList<String> {}
public List<String> method1();
public ArrayList<String> metho... | Solving this in general is really not easy to do yourself using only the tools provided by Java itself. There are a lot of special cases (nested classes, type parameter bounds,...) to take care of.
That's why I wrote a library to make generic type reflection easier: [gentyref](http://code.google.com/p/gentyref/). I add... | I tried this code and it returns the actual generic type class so it seems the type info can be retrieved. However this only works for method 1 and 2. Method 3 does not seem to return a list typed String as the poster assumes and therefore fails.
```
public class Main {
/**
* @param args the command line arguments
*... | How to test whether method return type matches List<String> | [
"",
"java",
"generics",
"reflection",
""
] |
Often, I found OutOfMemoryException on IBM Websphere Application Server.
I think this exception occur because my application retrieve Huge data from database. So, I limit all query don't retreive data more than 1000 records and set JVM of WAS follow
```
+ Verbose garbage collection
+ Maximum Heap size = 1024 (RAM on m... | The answer to this is dependent on the message associated with the OutOfMemoryException. You can also try -XX:MaxPermSize=... and set it to something larger like 256m.
Also, if you have a recursive function somewhere, that may be causing a stack overflow.
If you can, please post the message associated with the except... | If you want to look at the heap dump files, IBM offers tools to analyze them [here](http://publib.boulder.ibm.com/infocenter/tivihelp/v3r1/index.jsp?topic=/com.ibm.itcamwas_b.doc_6.1/pdmst_basic56.htm). | IBM Websphere OutOfMemoryException | [
"",
"java",
"web-services",
"jakarta-ee",
"websphere",
""
] |
Is there a way to find the maximum and minimum defined values of an enum in c++? | No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example,
```
enum MyPretendEnum
{
Apples,
Oranges,
Pears,
Bananas,
First = Apples,
Last = Bananas
};
```
The... | No, not in standard C++. You could do it manually:
```
enum Name
{
val0,
val1,
val2,
num_values
};
```
`num_values` will contain the number of values in the enum. | Max and min values in a C++ enum | [
"",
"c++",
"enums",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.