Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have already posted something similar [here](https://stackoverflow.com/questions/118051/c-grid-binding-not-update) but I would like to ask the question more general over here.
Have you try to serialize an object that implement INotifyPropertyChanged and to get it back from serialization and to bind it to a DataGridV... | Use the `DataContractSerializer` and create a method for OnDeserialized
```
[OnDeserialized]
private void OnDeserialized(StreamingContext c) {}
```
This will let you raise the PropertyChanged event when deserialization is complete | The trick of having it's own [Event and binding it after serialization](https://stackoverflow.com/questions/118051/c-grid-binding-not-update#118438) works but is not elegant because require an other event that I would not like to have... | C# serialization and event for data binding are lost | [
"",
"c#",
"data-binding",
"serialization",
""
] |
I have a string which contain tags in the form `< tag >`. Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like `"< tab >"` with the ascii equivelent of `'/t'`? | ```
string s = "...<tab>...";
s = s.Replace("<tab>", "\t");
``` | ```
using System.Text.RegularExpressions;
Regex.Replace(s, "TAB", "\t");//s is your string and TAB is a tab.
``` | C# string manipulation search and replace | [
"",
"c#",
"regex",
"string",
""
] |
What are the best practices for using Java's `@Override` annotation and why?
It seems like it would be overkill to mark every single overridden method with the `@Override` annotation. Are there certain programming situations that call for using the `@Override` and others that should never use the `@Override`? | Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warn... | I think it is most useful as a compile-time reminder that the intention of the method is to override a parent method. As an example:
```
protected boolean displaySensitiveInformation() {
return false;
}
```
You will often see something like the above method that overrides a method in the base class. This is an impo... | When do you use Java's @Override annotation and why? | [
"",
"java",
"annotations",
""
] |
I have a static library written in C++ and I have a structure describing data format, i.e.
```
struct Format{
long fmtId;
long dataChunkSize;
long headerSize;
Format(long, long, long);
bool operator==(Format const & other) const;
};
```
Some of data formats are widely used, like `{fmtId=0, dataC... | Don't use the static keyword on global declarations. [Here is an article explain the visibility of variables with/without static](http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx). The static gives globals internal linkage, that is, only visible in the translation unit they are declared in. | Are they defined in .cpp file as well? Roughly, it should look like:
```
struct Format
{
[...]
static Format gFmt128;
};
// Format.cpp
Format Format::gFmt128 = { 0, 128, 0 }
``` | Export variable from C++ static library | [
"",
"c++",
"export",
""
] |
I want to build an executable to distribute to people without python installed on their machines.
Is there an add-on to Eclipse that allows this? I couldn't find one.
If not, do you have a builder that you recommend that would make it easy to go to my python project directory created in Eclipse, and bundle it all up?... | [See](https://stackoverflow.com/questions/2933/an-executable-python-app) [these](https://stackoverflow.com/questions/106725/how-to-bundle-a-python-application-including-dependencies-for-windows) [questions](https://stackoverflow.com/questions/116657/how-do-you-create-an-osx-applicationdmg-from-a-python-package) | It's not eclipse, but ActiveState's [ActivePython FAQ](http://docs.activestate.com/activepython/2.5/faq/windows/index.html#where-is-freeze-for-windows) mentions the freeze utility, which sounds like it might be close to what you're asking for. | Is there an Eclipse add-on to build a python executable for distribution? | [
"",
"python",
"eclipse",
"bytecode",
""
] |
This came up in [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works. | `Ellipsis`, or `...` is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it.
So the syntax for it depends entirely on you, or someone else, having written code to understand it.
... | The ellipsis is used in numpy to slice higher-dimensional data structures.
It's designed to mean *at this point, insert as many full slices (`:`) to extend the multi-dimensional slice to all dimensions*.
**Example**:
```
>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)
```
Now, you have a 4-dimensio... | How do you use the ellipsis slicing syntax in Python? | [
"",
"python",
"numpy",
"subclass",
"slice",
"ellipsis",
""
] |
When a class field is accessed via a getter method by multiple threads, how do you maintain thread safety? Is the synchronized keyword sufficient?
Is this safe:
```
public class SomeClass {
private int val;
public synchronized int getVal() {
return val;
}
private void setVal(int val) {
... | If you use 'synchronized' on the setter here too, this code is threadsafe. However it may not be sufficiently granular; if you have 20 getters and setters and they're all synchronized, you may be creating a synchronization bottleneck.
In this specific instance, with a single int variable, then eliminating the 'synchro... | In addition to [Cowan's comment](https://stackoverflow.com/questions/118371/how-do-you-ensure-multiple-threads-can-safely-access-a-class-field#118388), you could do the following for a compare and store:
```
synchronized(someThing) {
int old = someThing.getVal();
if (old == 1) {
someThing.setVal(2);
... | How do you ensure multiple threads can safely access a class field? | [
"",
"java",
"multithreading",
"synchronized",
""
] |
I'm trying to write a query that will pull back the two most recent rows from the Bill table where the Estimated flag is true. The catch is that these need to be consecutive bills.
To put it shortly, I need to enter a row in another table if a Bill has been estimated for the last two bill cycles.
I'd like to do this ... | Assuming the rows have sequential IDs, something like this may be what you're looking for:
```
select top 1 *
from
Bills b1
inner join Bills b2 on b1.id = b2.id - 1
where
b1.IsEstimate = 1 and b2.IsEstimate = 1
order by
b1.BillDate desc
``` | ```
select top 2 *
from bills
where estimated = 1
order by billdate desc
``` | Find two consecutive rows | [
"",
"sql",
"sql-server",
"database",
""
] |
Does anyone know how to solve this java error?
```
java.io.IOException: Invalid keystore format
```
I get it when I try and access the certificate store from the Java option in control panels. It's stopping me from loading applets that require elevated privileges.
[Error Image](http://img72.imageshack.us/my.php?imag... | I was able to reproduce the error by mangling the trusted.certs file at directory
`C:\Documents and Settings\CDay\Application Data\Sun\Java\Deployment\security`.
Deleting the file fixed the problem. | Do not include special characters in organization name and unit | Java: Invalid Keystore format Error | [
"",
"java",
"keystore",
""
] |
In a destructor, is there a way to determine if an exception is currently being processed? | You can use std::uncaught\_exception(), but it might not do what you think it does: see [GoTW#47](http://www.gotw.ca/gotw/047.htm "GoTW#47") for more information. | As Luc said, you can use std::uncaught\_exception(). But why do you want to know? In any case, [destructors should never throw exceptions](http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.3)! | Is there a way to determine if an exception is occurring? | [
"",
"c++",
"exception",
"destructor",
""
] |
In my work I deal mostly with C# code nowadays, with a sprinkle of java from time to time. What I absolutely love about Eclipse (and I know people using it daily love it even more) is a sophisticated code formatter, able to mould code into any coding standard one might imagine. Is there such a tool for C#? Visual Studi... | For Visual Studio, take a look at [ReSharper](http://www.jetbrains.com/resharper). It's an awesome tool and a definite must-have. Versions after 4.0 have the code formatting and clean-up feature that you are looking for. There's also [plugin integration with StyleCop](http://stylecopforresharper.codeplex.com/), includi... | The [.NET Foundation](https://en.wikipedia.org/wiki/.NET_Foundation) just released their code formatting tool on GitHub
<https://github.com/dotnet/codeformatter>
It uses the [Roslyn](https://en.wikipedia.org/wiki/.NET_Compiler_Platform) compiler services to parse project documents and convert them to their expected f... | Is there an automatic code formatter for C#? | [
"",
"c#",
"formatting",
"build-automation",
""
] |
I thought I heard that [py2exe](http://www.py2exe.org/) was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?
Basically I'm thinking of it giving me a single executable file that does something like unzips itself to may... | [PyInstaller](http://www.pyinstaller.org/) will create a single .exe file with no dependencies; use the `--onefile` option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see [minty's answer](https://st... | The way to do this using py2exe is to use the bundle\_files option in your setup.py file. For a single file you will want to set `bundle_files` to 1, `compressed` to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.
Here is a more complete description of the bundl... | py2exe - generate single executable file | [
"",
"python",
"packaging",
"py2exe",
""
] |
I have a huge file, where I have to insert certain characters at a specific location. What is the easiest way to do that in C# without rewriting the whole file again. | Filesystems do not support "inserting" data in the middle of a file. If you really have a need for a file that can be written to in a sorted kind of way, I suggest you look into using an embedded database.
You might want to take a look at [SQLite](http://sqlite.org/) or [BerkeleyDB](http://www.oracle.com/technology/pr... | You will probably need to rewrite the file from the point you insert the changes to the end. You might be best always writing to the end of the file and use tools such as sort and grep to get the data out in the desired order. I am assuming you are talking about a text file here, not a binary file. | How to insert characters to a file using C# | [
"",
"c#",
".net",
"file",
"random-access",
""
] |
I have a given certificate installed on my server. That certificate has valid dates, and seems perfectly valid in the Windows certificates MMC snap-in.
However, when I try to read the certificate, in order to use it in an HttpRequest, I can't find it. Here is the code used:
```
X509Store store = new X509Store(Sto... | Try verifying the certificate chain using the [X509Chain](http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509chain.aspx) class. This can tell you exactly why the certificate isn't considered valid.
As erickson suggested, your X509Store may not have the trusted certificate from th... | Is the issuer's certificate present in the X509Store? A certificate is only valid if it's signed by someone you trust.
Is this a certificate from a real CA, or one that you signed yourself? Certificate signing tools often used by developers, like OpenSSL, don't add some important extensions by default. | Why is this X.509 certificate considered invalid? | [
"",
"c#",
"ssl",
"certificate",
"x509",
""
] |
Is it possible to call a COM API from Java (specifically the HP/Mercury Quality Center OTA API)? If so, what's the best way?
Is something like JACOB appropriate?
Code fragments would be helpful for the basics :-) | jacob : yes, <http://sourceforge.net/projects/jacob-project/> is an active project that will suite your purpose pretty well.
you can see multiple examples : <http://jacob-project.wiki.sourceforge.net/Event+Callbacks>
but if you want something that is more tested and are willing to pay money, then go for <http://www.n... | after a comparison of all the above, none was totally satisfactory.
the most complete solution is in
<https://github.com/java-native-access/jna>
now.
It supports,
* getting interface to a running COM object
* starting a new COM object and returning its interface
* calling COM methods and returning results
* optiona... | Is it possible to call a COM API from Java? | [
"",
"java",
"api",
"com",
"hp-quality-center",
""
] |
After a bind a method to an event of a Tkinter element is there a way to get the method back?
```
>>> root = Tkinter.Tk()
>>> frame = Tkinter.Frame(root, width=100, height=100)
>>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed
>>> frame.pack()
>>> bound_event_method = frame.???
``` | The associated call to do that for the tk C API would be [Get\_GetCommandInfo](http://linux.about.com/library/cmd/blcmdl3_Tcl_GetCommandInfo.htm) which
> places information about the command
> in the Tcl\_CmdInfo structure pointed
> to by infoPtr
However this function is not used anywhere in [\_tkinter.c](http://svn.... | The standard way to do this in Tcl/Tk is trivial: you use the same bind command but without the final argument.
```
bind .b <Button-1> doSomething
puts "the function is [bind .b <Button-1>]"
=> the function is doSomething
```
You can do something similar with Tkinter but the results are, unfortunately, not quite as u... | Get Bound Event Handler in Tkinter | [
"",
"python",
"user-interface",
"events",
"tkinter",
""
] |
Whenever I indent `HTML` in `PHP` mode, `emacs (22.1.1, basic install on Redaht Linux over Putty-SSH)` pops up a frame and tells me to get `MUMODE` or `somesuch` extra add-on. I installed `PHP` Mode without a big hassle, but I don't know how to get this multi-mode rolling.
---
I'd like to know 2 things
```
How to... | If you're running emacs 22, you should just be able to run:
```
M-x nxhtml-mumamo
```
when editing an html document. You might want to add it to your auto-mode-alist to get it to automatically load for html docs. See here for more info:
<http://www.emacswiki.org/cgi-bin/wiki/MuMaMo>
<http://www.emacswiki.org/cgi-b... | web-mode.el is available on <http://web-mode.org>
This major mode is designed to edit html php templates (with JS and CSS)
Add those two lines in your `.emacs`
```
(require 'web-mode)
(add-to-list 'auto-mode-alist '("\\.phtml$" . web-mode))
``` | How do I enable multimode emacs to program PHP without messing up my indents? | [
"",
"php",
"emacs",
""
] |
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.
I know that TcpClient will assign a new client side port when I open a connection to a given server.
Is there a simple way to find the next open TCP port in .NET?
I need the actual num... | Here is what I was looking for:
```
static int FreeTcpPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
``` | Use a port number of 0. The TCP stack will allocate the next free one. | Find the next TCP port in .NET | [
"",
"c#",
".net",
"wcf",
"networking",
"tcp",
""
] |
I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.
Does anyone know of a fix for this?
Thanks! | Apologies for the extra comment (I can't upvote or comment on Pavel's answer), but adding a DOCTYPE fixed this issue for me, and the slideUp/Down/Toggle effects now work correctly in IE7.
See [A List Apart](http://www.alistapart.com/articles/doctype/) for more information on DOCTYPES, or you can try specifying the fai... | Just let IE6 flicker. I don't think it's worth it to invest time in a dying browser when your base functionality works well enough. If you're worried about flickering for accessibility reasons, just sniff for IE6 and replace the animation with a generic show() and hide() instead. I recommend avoiding complicated code f... | How do you fix the flickering that occurs when you use slideToggle in jQuery? | [
"",
"javascript",
"jquery",
""
] |
I've got a sections table, and an items table.
The problem is each item may be in one or more sections, so a simple 'section\_id' for each item won't work, and sql doesn't have a way to store arrays where I can do say "WHERE 5 in section\_ids"...
I've considered storing the list of ids as a comma separated string, th... | You need an intermediate lookup table:
```
CREATE TABLE item_in_section (item_id int, section_id int)
```
(I'm guessing about your key types, use whatever ones are appropriate).
To find items in a section:
```
SELECT item.* from item, item_in_section WHERE item_in_section.item_id = item.item_id AND item_in_section.... | In order to represent a many-to-many relationship, you need a support table with SectionId and ItemId. Both should be foreign keys to their respective tables and the primary key of this table should be both columns.
From [Wikipedia](http://en.wikipedia.org/wiki/Many-to-many_(data_model)):
> Because most DBMSs only su... | Sql design problem - items in multiple sections | [
"",
"sql",
"database-design",
""
] |
I need to setup LookAndFeel Files in JDK 1.6.
I have two files:
1. napkinlaf-swingset2.jar
2. napkinlaf.jar
How can I set this up and use it?
I would like a GTK look and feel OR Qt look and feel, Are they available? | The class name for Naplin is `net.sourceforge.napkinlaf.NapkinLookAndFeel`. So to set it as default on the command line, use:
```
java -Dswing.defaultlaf=net.sourceforge.napkinlaf.NapkinLookAndFeel
```
To install it add `napkinlaf.jar` to the `lib/ext` direction and the lines:
```
swing.installedlafs=napkin
swing.in... | This page explains how the work with Look&Feels:
<http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html>
You can do it commandline:
```
java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp
```
Or in code:
```
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
``... | How can I setup LookAndFeel Files in Java? | [
"",
"java",
"swing",
"qt",
"gtk",
"look-and-feel",
""
] |
I'm developing a C# assembly which is to be called via COM from a Delphi 7 (iow, native win32, not .net) application.
So far, it seems to work. I've exported a TLB file, imported that into my Delphi project, and I can create my C# object and call its functions.
So that's great, but soon I'm going to **really** want t... | In the VS2008 project properties page, on the Debug tab, there's an option to set a different Start Action.
This can be used to run an external program (e.g. your Delphi app) when you press F5. | Place the following in the method you wish to debug:
```
#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
Debugger.Launch();
#endif
```
When you want to debug, build a debug version and use that in your application. When this code runs, a dialog pops up asking if you want to attach a debugger. | How can I debug a C# COM assembly when it's being called from a native win32 application? | [
"",
"c#",
".net",
"windows",
"delphi",
"com",
""
] |
How cheap can MySQL be compared to MS SQL when you have tons of data (and joins/search)? Consider a site like stackoverflow full of Q&As already and after getting dugg.
My ASP.NET sites are currently on SQL Server Express so I don't have any idea how cost compares in the long run. Although after a quick research, I'm ... | MSSQL Standard Edition (32 or 64 bit) will cost around $5K *per CPU socket*. 64 bit will allow you to use as much RAM as you need. Enterprise Edition is not really necessary for most deployments, so don't worry about the $20K you would need for that license.
MySQL is only free if you forego a lot of the useful tools o... | The performance benefits of MS SQL over MySQL are fairly negligible, especially if you mitigate them with server and client side optimzations like server caching (in RAM), client caching (cache and expires headers) and gzip compression. | Scaling cheaply: MySQL and MS SQL | [
"",
"sql",
"mysql",
"sql-server",
"scalability",
"scaling",
""
] |
If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?
Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?
I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:... | Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the [email](https://docs.python.org/2/library/email.html) package, construct the mail with that, serialise it, and send it to `/usr/sbin/sendmail` using the [subprocess](https://docs.python.org/2/library/subproc... | This is a simple python function that uses the unix sendmail to deliver a mail.
```
def sendMail():
sendmail_location = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % sendmail_location, "w")
p.write("From: %s\n" % "from@somewhere.com")
p.write("To: %s\n" % "to@somewhereelse.com")
p... | Sending mail via sendmail from python | [
"",
"python",
"email",
"sendmail",
""
] |
I've got the following situation
* A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality
* Lot of nice javascript written using jQuery (for a separate application)
I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and ... | ```
jQuery.noConflict();
```
Then use jQuery instead of $ to refer to jQuery. e.g.,
```
jQuery('div.foo').doSomething()
```
If you need to adapt jQuery code that uses $, you can surround it with this:
```
(function($) {
...your code here...
})(jQuery);
``` | I believe it's `jQuery.noConflict()`.
You can call it standalone like this:
```
jQuery.noConflict();
jQuery('div').hide();
```
Or you can assign it to another variable of your choosing:
```
var $j = jQuery.noConflict();
$j('div').hide();
```
Or you can keep using jQuery's `$` function inside a block like this:
... | Combining Scriptaculous and jQuery in a Rails application | [
"",
"javascript",
"jquery",
"ruby-on-rails",
"ruby",
"scriptaculous",
""
] |
In ASPNET, I grew to love the Application and Cache stores. They're awesome. For the uninitiated, you can just throw your data-logic objects into them, and hey-presto, you only need query the database once for a bit of data.
By far one of the best ASPNET features, IMO.
I've since ditched Windows for Linux, and theref... | Serializing is quite safe and commonly used. There is an alternative however, and that is to cache to memory. Check out [memcached](http://pecl.php.net/package/memcache) and [APC](http://www.php.net/manual/en/book.apc.php), they're both free and highly performant. [This article](http://blog.digitalstruct.com/2008/02/27... | ### Re: Is there another persist-to-file method that I'm forgetting?
It's of limited utility but if you have a particularly beefy database query you could write the serialized object back out to an indexed database table. You'd still have the overhead of a database query, but it would be a simple select as opposed to ... | Methods for caching PHP objects to file? | [
"",
"php",
"caching",
""
] |
This question comes out of the discussion on [tuples](https://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c).
I started thinking about the hash code that a tuple should have.
What if we will accept KeyValuePair class as a tuple? It doesn't override the Get... | It seems that I have a clue now.
I thought KeyValuePair is a reference type, but it is not, it is a struct. And so it uses ValueType.GetHashCode() method. MSDN for it says: "One or more fields of the derived type is used to calculate the return value".
If you will take a real reference type as a "tuple-provider" you'... | Don't override GetHashcode() and Equals() on mutable classes, only override it on immutable classes or structures, else if you modify a object used as key the hash table won't function properly anymore (you won't be able to retrieve the value associated to the key after the key object was modified)
Also hash tables do... | How does c# figure out the hash code for an object? | [
"",
"c#",
"hash",
"internals",
""
] |
The questions says everything, take this example code:
```
<ul id="css-id">
<li>
<something:CustomControl ID="SomeThingElse" runat="server" />
<something:OtherCustomControl runat="server" />
</li>
</ul>
```
Now if an error gets thrown somewhere inside these controlls (that are located in a master page... | You can catch all exception not handled elswhere in the Global.asax page / class.
Look at:
```
protected void Application_Error(Object sender, EventArgs e)
```
method. | Unfortunately an unhandled exception will always error your site.
YOu can prevent this a few ways though.
* Use the section in your web.config to show a user friendly message
* In your Global.asax - or a Custom Handler - catch your unhandled exception and react accordingly - [like this](http://www.webdude.co.za/archiv... | Catching exceptions within .aspx and .ascx pages | [
"",
"c#",
".net",
"asp.net",
"exception",
"error-handling",
""
] |
I have a pretty complicated Linq query that I can't seem to get into a LinqDataSsource for use in a GridView:
```
IEnumerable<ticket> tikPart = (
from p in db.comments where
p.submitter == me.id &&
p.ticket.closed == DateTime.Parse("1/1/2001") &&
p.ticket.originating_group != me.sub_unit... | You can setup your Gridview with no Datasource. Setup the gridview columns, and in codebehind bind that result to the grid view. | ```
gridview.DataSource = tikPart.ToList();
gridview.DataBind();
``` | Getting a Linq-toSQL query to show up on a GridView | [
"",
"c#",
"linq",
"linq-to-sql",
"gridview",
""
] |
Does anybody use anything else to document their `PHP` code than `PHPDoc?`
Are there any tools that read the same documentation syntax but give richer output? | I´ll go for doxygen too.
Here are several reasons :
* compatible with phpdoc tags and other popular ones : it´s interoperable
* works with various programming languages : a better time investment
* there is alternative syntaxes : can choose the commenting style that suit you
* very efficient with advanced formating /... | You could try DocBlox; which is intended to be an alternative for phpDocumentor but with support for additional features of which full PHP 5.3 support is one. An additional benefit is that is it quite fast and uses relatively little memory.
You can read more on <http://www.docblox-project.org> or see a demo at <http:/... | Anything better than PHPDoc out there? | [
"",
"php",
"documentation",
"documentation-generation",
"phpdoc",
""
] |
I'm doing some Android development, and I much prefer Visual Studio, but I'll have to use *Eclipse* for this.
Has anyone made a tool which can make *Eclipse* look and behave more like visual studio? I mainly can't stand its **clippyesqe** suggestions on how I should program (Yes, I know I have not yet used that privat... | There are also other choices for Java IDEs. You've obviously found Eclipse, but you also may want to check out [IntelliJ](http://www.jetbrains.com/idea/index.html) and [NetBeans](http://www.netbeans.org/). IntelliJ is not free, but has a 30 day evaluation period and a Visual Studio key map :)
Shop around, find one tha... | Have you tried using the Visual Studio keybindings available in Eclipse Ganymede (3.4)?
(You may want to know that "IntelliSense" is a Visual Studio-term, an probably unknown to anyone without Visual Studio-experience. "Autocompletion" is probably a more widely used term.) | Making Eclipse behave like Visual Studio | [
"",
"java",
"android",
"eclipse",
"visual-studio",
"ide",
""
] |
I often refactor code first by creating an inner class inside the class I'm working on--When I'm done, I move the entire thing into a new class file. This makes refactoring code into the new class extremely easy because A) I'm only dealing with a single file, and B) I don't create new files until I have a pretty good i... | I'm sorry I gave the wrong answer before. I rechecked, and it didn't do quite want you want. I did find a solution for you though, again, in 3.4.
Highlight the class, do a copy CTRL-C or cut CTRL-X, click on the package you want the class do go into, and do a paste, CTRL-V. Eclipse will auto generate the class for you... | In Eclipse 3.6, you can do: Refactor -> Move type to new file | Can eclipse extract a second class in class file to its own file | [
"",
"java",
"eclipse",
"refactoring",
""
] |
I attempted to open a C#/VB form in designer mode, and instead of the form, I got an ugly error message saying "The path is not of a legal form". This form used to work! What happened?
---
*Thanks to all who have answered. This question is a problem I hit a while back, and I struggled with it for a long time, until I... | I don't know what this error message means, but it seems to be associated with third-party controls on the form. Anyway, the solution is almost as absurd as the problem:
1. Close the designer/error message.
2. Open the form code.
3. Right-click on the form code and select "View Designer".
Presto! The designer opens! | Debugging design mode would help. From [here](http://blog.lab49.com/archives/244):
1. List item
2. In visual studio, select the project you want to debug.
3. Right click -> Properties.
4. Select the debugging tab.
5. Change the debug mode to Program.
6. Set the “Start Application” to be your visual studio IDE (C:\Prog... | Open .NET form in designer mode - get "The path is not of a legal form" | [
"",
"c#",
"vb.net",
"visual-studio",
"winforms",
""
] |
I am using [cxxtest](http://cxxtest.tigris.org/) as the test framework for my C++ classes, and would like to figure out a way to simulate sending data to classes which would normally expect to receive it from standard input. I have several different files which I would like to send to the classes during different tests... | The appropriate method is to rewrite your classes so that they are testable. They should accept as a parameter the handle, stream or file from which they are supposed to read data - in your test framework, you can then mock in the stream or supply the path to the file containing the test data. | You should be able to use freopen() to point stdin to an arbitrary file. | How to redirect data to stdin within a single executable? | [
"",
"c++",
""
] |
I've seen some people use `EXISTS (SELECT 1 FROM ...)` rather than `EXISTS (SELECT id FROM ...)` as an optimization--rather than looking up and returning a value, SQL Server can simply return the literal it was given.
Is `SELECT(1)` always faster? Would Selecting a value from the table require work that Selecting a li... | For google's sake, I'll update this question with the same answer as this one ([Subquery using Exists 1 or Exists \*](https://stackoverflow.com/questions/1597442/subquery-using-exists-1-or-exists/)) since (currently) an incorrect answer is marked as accepted. Note the SQL standard actually says that EXISTS via \* is id... | In SQL Server, it does not make a difference whether you use `SELECT 1` or `SELECT *` within `EXISTS`. You are not actually returning the contents of the rows, but that rather the set determined by the `WHERE` clause is not-empty. Try running the query side-by-side with `SET STATISTICS IO ON` and you can prove that the... | SQL Server: Is SELECTing a literal value faster than SELECTing a field? | [
"",
"sql",
"sql-server",
""
] |
```
uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
//...
```
doesn't work. What am i doing wrong? | Try
```
Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment
``` | You can use an overloaded `TryParse()` which adds a NumberStyle parameter to the `TryParse` call which provides parsing of Hexadecimal values. Use `NumberStyles.HexNumber` which allows you to pass the string as a hex number.
**Note**: The problem with `NumberStyles.HexNumber` is that it *doesn't* support parsing value... | How to parse hex values into a uint? | [
"",
"c#",
""
] |
I want to call a few "static" methods of a CPP class defined in a different file but I'm having linking problems. I created a test-case that recreates my problem and the code for it is below.
(I'm completely new to C++, I come from a Java background and I'm a little familiar with C.)
```
// CppClass.cpp
#include <ios... | It's obvious you come from a Java background because you haven't yet grasped the concept of header files. In Java the process of defining something is usually in one piece. You declare and define at the same time. In C/C++ it's a two-step process. **Declaring** something tells the compiler "something exists with this t... | You're defining the class twice, which I'm pretty sure doesn't work.
Try something like this:
First a header CppClass.h file:
```
// CppClass.h
using namespace std;
class CppClass
{
public:
static void Start();
static void Stop();
static void Join();
private:
void *run_thread(void *pthread_args);
... | Problem Linking "static" Methods in C++ | [
"",
"c++",
"linker",
"g++",
""
] |
I've looked for this a few times in the past, to no avail. I would like a simple `php/ajax` web chat interface, that, and this is the critical part, will interface with my `IM client (Pidgin)` ... via Jabber or Aim. `Plugoo` is almost what I want, except it is hosted, and flash based. Flash-based would be OK if not ide... | This wouldn't be that hard, if you implement the Oscar protocol that AIM uses. It's not very complex, and that would allow you to build a nice web based AIM client for your website. There may be a 3rd party solution that you could use, but as far as I know, Oscar is pretty trivial. | (Disclaimer: I work for [Jabber, Inc.](http://www.jabber.com/), the commercial company behind the product I'm about to pimp.)
[](https://i.stack.imgur.com/tuKFA.png)
(source: [jabber.com](http://www.jabber.com/images/GroupChatAJAXThumb.png))
The [JabberWerx AJA... | Simple web "live chat" software (LAMP stack) that integrates with Jabber/Aim | [
"",
"php",
"ajax",
"chat",
"xmpp",
""
] |
How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call? | From the controller you can just return a JsonResult:
```
public ActionResult MyAction()
{
... // Populate myObject
return new JsonResult{ Data = myObject };
}
```
The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like:
```
$.getJSON("/controll... | Depending on your syntax preferences, the following also works:
```
public ActionResult MyAction()
{
return Json(new {Data = myObject});
}
``` | JSON and ASP.NET MVC | [
"",
"c#",
"asp.net-mvc",
"ajax",
"json",
""
] |
I'm looking for an extremely fast atof() implementation on IA32 optimized for US-en locale, ASCII, and non-scientific notation. The windows multithreaded CRT falls down miserably here as it checks for locale changes on every call to isdigit(). Our current best is derived from the best of perl + tcl's atof implementatio... | What is your accuracy requirement? If you truly need it "correct" (always gets the nearest floating-point value to the decimal specified), it will probably be hard to beat the standard library versions (other than removing locale support, which you've already done), since this requires doing arbitrary precision arithme... | This implementation I just finished coding runs twice as fast as the built in 'atof' on my desktop. It converts 1024\*1024\*39 number inputs in 2 seconds, compared 4 seconds with my system's standard gnu 'atof'. (Including the setup time and getting memory and all that).
**UPDATE:**
Sorry I have to revoke my twice as ... | Where can I find the world's fastest atof implementation? | [
"",
"c++",
"c",
"performance",
"assembly",
"floating-point",
""
] |
I have the following string and I would like to remove `<bpt *>*</bpt>` and `<ept *>*</ept>` (notice the additional tag content inside them that also needs to be removed) without using a XML parser (overhead too large for tiny strings).
```
The big <bpt i="1" x="1" type="bold"><b></bpt>black<ept i="1"></b></ept> <bpt ... | If you just want to remove all the tags from the string, use this (C#):
```
try {
yourstring = Regex.Replace(yourstring, "(<[be]pt[^>]+>.+?</[be]pt>)", "");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
```
EDIT:
I decided to add on to my solution with a better option. The prev... | I presume you want to drop the tag entirely?
```
(<bpt .*?>.*?</bpt>)|(<ept .*?>.*?</ept>)
```
The ? after the \* makes it non-greedy, so it will try to match as few characters as possible.
One problem you'll have is nested tags. stuff would not see the second because the first matched. | Regular expression to remove XML tags and their content | [
"",
"c#",
".net",
"xml",
"vb.net",
"regex",
""
] |
Ok, so we have clients and those clients get to customize their web facing page. One option we are giving them is to be able to change the color of a graphic (it's like a framish-looking bar) using one of those hex wheels or whatever.
So, I've thought about it, and I don't know where to start. I am sending comps out t... | I'm sort of intuiting that you'll have a black on white bitmap that you use as the base image. The client can then select any other color combination. This may not be exactly your situation, but it should get us started. (The code below is VB -- it's what I know, but converting to C# should be trivial for you.)
```
Im... | What exactly will be changing? Depending on what's changing you may be able to overlay a transparent png on top of an html background color. Just change the background color and the logo color will change. Of course this limits what you can change, but you'd be surprised how much you can get away with.
And yes, the al... | Implementing User-Controlled Style Changes in ASP.NET | [
"",
"c#",
"asp.net",
"html",
".net-3.5",
""
] |
I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid.
Is there another way to obtain the PID? | If you have [procfs](http://en.wikipedia.org/wiki/Procfs) installed, you can find the process id via the /proc/self symlink, which points to a directory whose name is the pid (there are also files here with other pertinent information, including the PID, but the directory is all you need in this case).
Thus, with Java... | Only tested in Linux using Sun JVM. Might not work with other JMX implementations.
```
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
``` | How do I find my PID in Java or JRuby on Linux? | [
"",
"java",
"linux",
"jruby",
"pid",
""
] |
GWT's serializer has limited `java.io.Serializable` support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example [this FAQ entry](http://www.gwtproject.org/doc/latest/FAQ_Server.html#Does_the_GWT_RPC_system_support_the_use_of_java.io.Serializable) says that any ... | Any specific types that you include in your service interface and any types that they reference will be automatically whitelisted, as long as they implement java.io.Serializable, eg:
```
public String getStringForDates(ArrayList<java.util.Date> dates);
```
Will result in ArrayList and Date both being included on the ... | There's a workaround: define a new `Dummy` class with member fields of all the types that you want to be included in serialization. Then add a method to your RPC interface:
```
Dummy dummy(Dummy d);
```
The implementation is just this:
```
Dummy dummy(Dummy d) { return d; }
```
And the async interface will have thi... | How do I add a type to GWT's Serialization Policy whitelist? | [
"",
"java",
"serialization",
"gwt",
"whitelist",
""
] |
So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.
```
class PageAtrributes
{
private $db_connection;
private $page_title;
public function __construct($db_connection)
{
$this->db_connection = $db_connection;
$this->page_title = '';
}
publ... | It means that `$objPage` is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of [PHPs type-hinting feature*Docs*](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) to get the error whe... | There's an easy way to produce this error:
```
$joe = null;
$joe->anything();
```
Will render the error:
> Fatal error: Call to a member function `anything()` on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23
It would be a lot better if **PHP** would just say,
> Fat... | Call to a member function on a non-object | [
"",
"php",
""
] |
In Python there is a really neat function called `zip` which can be used to iterate through two lists at the same time:
```
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for v1, v2 in zip(list1, list2):
print v1 + " " + v2
```
The above code should produce the following:
```
1 a
2 b
3 c
```
I wonder if there is a m... | Update: It is built-in in C# 4 as [System.Linq.Enumerable.Zip<TFirst, TSecond, TResult> Method](https://msdn.microsoft.com/en-us/library/vstudio/dd267698(v=vs.110).aspx)
Here is a C# 3 version:
```
IEnumerable<TResult> Zip<TResult,T1,T2>
(IEnumerable<T1> a,
IEnumerable<T2> b,
Func<T1,T2,TResult> combine... | As far as I know there is not. I wrote one for myself (as well as a few other useful extensions and put them in a project called [NExtension](http://www.codeplex.com/nextension) on Codeplex.
Apparently the Parallel extensions for .NET have a Zip function.
Here's a simplified version from NExtension (but please check ... | Is there a zip-like method in .Net? | [
"",
".net",
"python",
"list",
"iteration",
""
] |
I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver.
I'm currently using a bi... | CDC and CBitmap appears to only support device dependant bitmaps, you might have more luck creating your bitmap with [::CreateDIBSection](http://msdn.microsoft.com/en-us/library/ms532292(VS.85).aspx), then attaching a CBitmap to that. The raw GDI interfaces are a little hoary, unfortunately.
You probably won't have mu... | This is unusual as I often created a DC based on the screen that will be used for a bitmap image that is much larger than the screen - 3000 pixels plus in some cases - with no problems at all. Do you have some sample code showing this problem in action? | How to create a very big bitmap in C++/MFC / GDI | [
"",
"c++",
"mfc",
"bitmap",
"gdi",
"cdc",
""
] |
Can anyone point me to a library for 2D game physics, etc for programming gravity, jumping actions, etc for a 2d platform/sidescrolling game ?
Or could you suggest some algorithms for side scroller like mario, sonic etc? | It sounds like [Chipmunk](http://chipmunk-physics.net/) might meet your needs. | Your best bet is most likely [Box2D](http://www.box2d.org/). It does 2D physics, has tons of options, and is very easy to integrate into an existing project. It does CCD by default for fixed bodies, but any rigid body can be selectively included in the CCD calculation. | 2d game physics? | [
"",
"c++",
"physics",
""
] |
Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes? | [Microsoft Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx), which are part of .NET Framework since 4.0 CTP and are available for earlier .NET Framework versions as a stand-alone package, allow to specify coding assumptions. This includes specifying pre-conditions which can verify parameters.
An ... | The Microsoft Enterprise Library has the Microsoft.Practices.EnterpriseLibrary.Validation library/namespace which allows validation using attributes. | Is there a standard framework for .NET parameter validation that uses attributes? | [
"",
"c#",
".net",
"validation",
"attributes",
"parameters",
""
] |
Right now I'm making an extremely simple website- about 5 pages. Question is if it's overkill and worth the time to integrate some sort of database mapping solution or if it would be better to just use plain old JNDI. I'll have maybe a dozen things I need to read/write from the database. I guess I have a basic understa... | Short answer: It depends on the complexity you want to support.
Long answer:
First of all, ORM ( object relational mapping - database mapping as you call it - ) and JNDI ( Java Naming and Directory Interfaces ) are two different things.
The first as you already know, is used to map the Database tables to classes and... | It does seem like it would be overkill for a very simple application, especially if you don't have plans to expand on it ever. However, it also seems like it could be worthwhile to use those with this simple application so that you have a better understanding of how they work for next time you have something that could... | When to use Hibernate/JPA/Toplink? | [
"",
"java",
"hibernate",
"orm",
"jpa",
"toplink",
""
] |
Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented? | I like this piece of the `bind` source:
```
template<class R, class F, class L> class bind_t
{
public:
typedef bind_t this_type;
bind_t(F f, L const & l): f_(f), l_(l) {}
#define BOOST_BIND_RETURN return
#include <boost/bind/bind_template.hpp>
#undef BOOST_BIND_RETURN
};
```
Tells you almost all you need ... | By the way, if `bind_t` is collapsed and simplified by including `boost/bind/bind_template.hpp` , it becomes easier to understand like the following :
```
template<class R, class F, class L>
class bind_t
{
public:
typedef bind_t this_type;
bind_t(F f, L const & l): f_(f), l_(l) {}
typed... | How does boost bind work behind the scenes in general? | [
"",
"c++",
"boost",
"boost-bind",
""
] |
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms.
Thus splitting the respective string by the space-character is not sufficient anymore.
Example:
```
input : 'foo bar "lorem ipsum" baz'
output: ['foo', 'bar', 'lorem ipsum', 'baz']
```
I wonder whether this could be a... | ```
var str = 'foo bar "lorem ipsum" baz';
var results = str.match(/("[^"]+"|[^"\s]+)/g);
```
... returns the array you're looking for.
Note, however:
* Bounding quotes are included, so can be removed with `replace(/^"([^"]+)"$/,"$1")` on the results.
* Spaces between the quotes will stay intact. So, if there are... | Try this:
```
var input = 'foo bar "lorem ipsum" baz';
var R = /(\w|\s)*\w(?=")|\w+/g;
var output = input.match(R);
output is ["foo", "bar", "lorem ipsum", "baz"]
```
Note there are no extra double quotes around lorem ipsum
Although it assumes the input has the double quotes in the right place:
```
var input2 = '... | parsings strings: extracting words and phrases [JavaScript] | [
"",
"javascript",
"regex",
"parsing",
""
] |
I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?
```
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
... | Try something like this instead;
```
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
illegal = illegal.Replace(c.ToString(), "");
}
```
But I have to agree... | The original question asked to "remove illegal characters":
```
public string RemoveInvalidChars(string filename)
{
return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));
}
```
You may instead want to replace them:
```
public string ReplaceInvalidChars(string filename)
{
return string.Join("_"... | How to remove illegal characters from path and filenames? | [
"",
"c#",
"string",
"path",
"directory",
""
] |
What is the best way to layout a large django project? The tutorials provide simple instructions for setting up apps, models, and views, but there is less information about how apps and projects should be broken down, how much sharing is allowable/necessary between apps in a typical project (obviously that is largely d... | The major guidelines are similar to any other large code project. Apps should address a single, clearly-defined responsibility. The name "application" is a misnomer; Django apps should be thought of more as reusable components which can be plugged together to create a real application. Tests for each app should be cont... | I found Zachary's layout quite useful
[Zachary Voase’s Blog » Django Project Conventions, Revisited.](http://zacharyvoase.com/2010/02/03/django-project-conventions/) | Project design / FS layout for large django projects | [
"",
"python",
"django",
""
] |
I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor.
Why would this be something not to do? | When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class ([see Eric Lippert's blog for details as to why this is](https://learn.microsoft.com/en-us/archi... | In order to answer your question, consider this question: what will the below code print out when the `Child` object is instantiated?
```
class Parent
{
public Parent()
{
DoSomething();
}
protected virtual void DoSomething()
{
}
}
class Child : Parent
{
private string foo;
p... | Virtual member call in a constructor | [
"",
"c#",
"constructor",
"warnings",
"resharper",
"virtual-functions",
""
] |
Hey, I've been developing an application in the windows console with Java, and want to put it online in all of its console-graphics-glory.
Is there a simple web applet API I can use to port my app over?
I'm just using basic System.out and System.in functionality, but I'm happy to rebuild my I/O wrappers.
I think som... | Sure, just make into an applet, put a small swing UI on it with a JFrame with two components - one for writing output to, and one for entering inputs from. Embed the applet in the page. | I did as [Lars](https://stackoverflow.com/questions/138157/java-console-like-web-app#138206) suggested and wrote my own.
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.awt.Font;
public class Applet extends JFrame {
static final long serialVersionUID = 1;
/... | Java - Console-like web applet | [
"",
"java",
"api",
"console",
"applet",
""
] |
I'm new to PHP and I'm confused seeing some examples calling a function with a @ prefix like @mysql\_ping().
What is it for? Googling / searching is not much of a help since @ gets discarded and 'alias' is not good enough keyword. | @ suppresses errors, warnings and notices.
You can use it for good purpose if you complement it with a custom [error handler](http://php.net/manual/en/function.set-error-handler.php) or with due check of $php\_errormsg variable so you can handle errors properly.
In my experience, this proper usage is not seen very mu... | It suppresses the output of error messages.
Contrary to another commentator here, I think that it is good programming practice to use it (especially if you are developing a web app, where the output would be mixed in the html of the output page).
Functions like mysql\_connect return a resource identifier, or FALSE on ... | PHP alias @ function | [
"",
"php",
"operators",
"error-suppression",
""
] |
I want to have my PHP application labeled with the revision number which it uses, but I don't want to use [CruiseControl](http://en.wikipedia.org/wiki/CruiseControl) or update a file and upload it every time. How should I do it? | SVN keywords is not a good solution. As others pointed out adding $Revision$ in a file only affects **the specific file**, which may not change for a long time.
Remembering to "edit" a file (by adding or removing a blank line) before every commit is pointless. You could as well just type the revision by hand.
One goo... | Assuming your webroot is a checked-out copy of the subversion tree, you could parse the /.svn/entries file and hook out the revision number (4th line here)...
In PHP:
```
$svn = File('.svn/entries');
$svnrev = $svn[3];
unset($svn);
``` | How can I get the Subversion revision number in PHP? | [
"",
"php",
"svn",
"revision",
""
] |
Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year?
```
myDate = new Date();
year = myDate.getYear();
```
year = 108? | It's a [Y2K](http://en.wikipedia.org/wiki/Y2K) thing, only the years since 1900 are counted.
There are potential compatibility issues now that `getYear()` has been deprecated in favour of `getFullYear()` - from [quirksmode](http://www.quirksmode.org/js/introdate.html):
> To make the matter even more complex, date.get... | Since getFullYear doesn't work in older browsers, you can use something like this:
```
Date.prototype.getRealYear = function()
{
if(this.getFullYear)
return this.getFullYear();
else
return this.getYear() + 1900;
};
```
Javascript prototype can be used to extend existing objects, much like C... | Why does Javascript getYear() return a three digit number? | [
"",
"javascript",
"date",
""
] |
I believe any programmer who has been dealing with database requests in a gui application has run into some or all of the following problems:
* Your GUI freezes because you call
database layer from within the event
dispatch thread
* When you have multiple windows/panels/jframes where user can start a db request yo... | Such a thing should be found in Netbeans for example. See RequestProcessor. But in simpler cases this is not required. Last time I need something like thread scheduling and control I simply used new concurrency packages included in J5 (I used J6). With its ExecutorFactory-ies you can simply achieve basic control over t... | Naked Objects facilitate a clean domain model and they also have a GUI 2 DB mapping layer -- <http://www.nakedobjects.org/home/index.shtml> | Are there any frameworks for handling database requests in swing applications? | [
"",
"java",
"database",
"multithreading",
"swing",
""
] |
I use several referenced tables with integer primary keys. Now I want to change ints to GUIDs leaving all references intact. What is the easiest way to do it?
Thank you!
**Addition**
I do understand the process in general, so I need more detailed advices, for example, how to fill new GUID column. Using default value... | * Create a new column for the guid
value in the master table. Use the
uniqueidentifier data type, make it
not null with a newid() default so
all existing rows will be populated.
* Create new uniqueidentifier columns
in the child tables.
* Run update statements to build the guild relationships using the exisit... | Firstly: Dear God why?!?!?
Secondly, you're going to have to add the GUID column to all your tables first, then populate them based on the int value. Once done you can set the GUIDs to primary/foreign keys then drop the int columns.
To update the value you'd do something like
1. Set the new GUIDs in the primary key ... | Moving from ints to GUIDs as primary keys | [
"",
"sql",
"sql-server",
"foreign-keys",
"primary-key",
"guid",
""
] |
I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)... | Your Mac comes with both an Apache Web Server and a build of PHP. It's one of the big reasons the platform is well loved by web developers.
Since you're using Code Igniter, you'll want PHP 5, which is the default version of PHP shipped with 10.5. If you're on a previous version of the OS hop on over to [entropy.ch](ht... | Sorry Kyle, I don't have enough cred to respond directly to your comment. But if you want to have each project be served on a different port, try setting up your virtual host config exactly like Kelly's above (minus the DNS stuff) except instead of 80, give each virtual host its own port number, assuming that you've ad... | Set up Apache for local development/testing? | [
"",
"php",
"codeigniter",
"apache",
""
] |
I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource. | Run this SQL:
```
select * from v$version;
```
And you'll get a result like:
```
BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for Solaris: Version 10.2.0.... | Two methods:
```
select * from v$version;
```
will give you:
```
Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production
PL/SQL Release 11.1.0.6.0 - Production
CORE 11.1.0.6.0 Production
TNS for Solaris: Version 11.1.0.6.0 - Production
NLSRTL Version 11.1.0.6.0 - Production
```
OR [Identifying ... | How can I confirm a database is Oracle & what version it is using SQL? | [
"",
"sql",
"oracle",
""
] |
I am trying to use the Google Maps API in a ColdFusion template that is a border type cflayoutarea container. However, the map simply doesn't show up:
```
<cfif isdefined("url.lat")>
<cfset lat="#url.lat#">
<cfset lng="#url.lng#">
</cfif>
<head>
<script src= "http://maps.google.com/m... | Success! (sort of...)
Finally got it working, but not in the way Adam suggested:
```
<script src= "http://maps.google.com/maps?file=api&v=2&key=xxxx" type="text/javascript"></script>
<script type="text/javascript">
getMap=function(lat,lng){
if (GBrowserIsCompatible()){
v... | > So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container?
It should be possible reference an element loaded via AJAX -- just not until the element is on screen (so not on page load). It looks like getMap() triggers everything. (Is that right?)
T... | Using Google Maps in ColdFusion | [
"",
"javascript",
"google-maps",
"coldfusion",
""
] |
I was writing a database handler class in PHP using the mysqli class and prepared statements. I was attempting to print out the result. It didn't work right off the bat so I decided to do some debugging. I tried to use the `num_rows()` method from the `mysqli_statement` class, but it kept returning 0. I decided to writ... | I wonder if num\_rows() is reporting relative to the current resultset. Try capturing num\_rows() prior to fetching the data. e.g.
```
if($statement->prepare($query))
{
$statement->execute();
$statement->store_result();
echo $statement->num_rows();
$statement->bind_result($name);
$statement->fetch(... | `num_rows` is not a method, it's a property. | mysqli_stmt::num_rows() returns the wrong value | [
"",
"php",
"mysql",
"mysqli",
""
] |
I have an application that tracks high scores in a game.
I have a **user\_scores** table that maps a user\_id to a score.
I need to return the 5 highest scores, but only 1 high score for any *specific* user.
So if user X has the 5 highest scores on a purely numerical basis, I simply return the highest one and then t... | This should work:
```
SELECT user_id, MAX(score)
FROM user_scores
GROUP BY user_id
ORDER BY MAX(score) DESC
LIMIT 5
``` | ```
SELECT user_id, MAX(score) AS score
FROM user_scores
GROUP BY user_id
ORDER BY score DESC
LIMIT 5
```
Should do the job for you... though don't forget to create indexes... | Selecting values grouped to a specific identifer | [
"",
"mysql",
"sql",
"database",
""
] |
In what scenarios is it better to use a `struct` vs a `class` in C++? | The differences between a `class` and a `struct` in C++ are:
* `struct` members and base classes/structs are `public` by default.
* `class` members and base classes/structs are `private` by default.
Both classes and structs can have a mixture of `public`, `protected` and `private` members, can use inheritance, and ca... | As everyone else notes there are really only two actual language differences:
* `struct` defaults to public access and `class` defaults to private access.
* When inheriting, `struct` defaults to `public` inheritance and `class` defaults to `private` inheritance. (Ironically, as with so many things in C++, the default ... | When should you use a class vs a struct in C++? | [
"",
"c++",
"oop",
"class",
"struct",
"ooad",
""
] |
Along the lines of my previous [question](https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat), how can i join a list of strings into a string such that values get quoted cleanly. Something like:
```
['a', 'one "two" three', 'foo, bar', """both"'"""]
```
into:
```
a... | Using the `csv` module you can do that way:
```
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)
```
If you need a string just use `StringIO` instance as a file:
```
f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()
```
The output: `a,"one ""... | On a related note, Python's [builtin encoders](http://docs.python.org/lib/standard-encodings.html) can also do string escaping:
```
>>> print "that's interesting".encode('string_escape')
that\'s interesting
``` | How can I join a list into a string (caveat)? | [
"",
"python",
"string",
"list",
"csv",
""
] |
In [PostgreSQL](http://en.wikipedia.org/wiki/PostgreSQL), I can do something like this:
```
ALTER SEQUENCE serial RESTART WITH 0;
```
Is there an Oracle equivalent? | Here is a good procedure for resetting any sequence to 0 from Oracle guru [Tom Kyte](http://asktom.oracle.com). Great discussion on the pros and cons in the links below too.
```
tkyte@TKYTE901.US.ORACLE.COM>
create or replace
procedure reset_seq( p_seq_name in varchar2 )
is
l_val number;
begin
execute immedia... | A true restart is not possible [AFAIK](http://en.wiktionary.org/wiki/AFAIK). (Please correct me if I'm wrong!).
However, if you want to set it to 0, you can just delete and recreate it.
If you want to set it to a specific value, you can set the INCREMENT to a negative value and get the next value.
That is, if your s... | How do I reset a sequence in Oracle? | [
"",
"sql",
"database",
"oracle",
"sequence",
""
] |
I'm now in search for a Java Text to Speech (TTS) framework. During my investigations I've found several JSAPI1.0-(partially)-compatible frameworks listed on [JSAPI Implementations page](http://java.sun.com/products/java-media/speech/reference/codesamples/index.html), as well as a pair of Java TTS frameworks which do n... | I've actually had pretty good luck with [FreeTTS](http://freetts.sourceforge.net/) | Google Translate has a secret tts api:
<https://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World> | Java: Text to Speech engines overview | [
"",
"java",
"text-to-speech",
""
] |
How can I detect, using php, if the machine has oracle `(oci8 and/or pdo_oci)` installed?
I'm working on a `PHP` project where some developers, such as myself, have it installed, but there's little need for the themers to have it. How can I write a quick function to use in the code so that my themers are able to work ... | if the oci extension isn't installed, then you'll get a fatal error with farside.myopenid.com's answer, you can use function\_exists('oci\_connect') or extension\_loaded('oci8') (or whatever the extension's actually called) | The folks here have pieces of the solution, but let's roll it all into one solution.
For just a single instance of an oracle function, testing with `function_exists()` is good enough; but if the code is sprinkled throughout to OCI calls, it's going to be a huge pain in the ass to wrap every one in a `function_exists()... | How can I detect, using php, if the machine has oracle (oci8 and/or pdo_oci) installed? | [
"",
"php",
"oracle",
""
] |
I have a ASP.NET application running on a remote web server and I just started getting this error. I can't seem to reproduce it in my development environment:
```
Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
```
Could this be due to some misconfiguration of .NET Framework or IIS 6?
Upda... | This was caused by a bug in the aspnet merge tool which incorrectly merged optimized assemblies. It can be solved by either not merging the assemblies or not optimizing them. | Are the .NET versions on both systems the same inc. the same service pack? | ASP.NET: ICollection Constructor Not Found? | [
"",
"c#",
"asp.net",
""
] |
What are the differences in implementing interfaces **implicitly** and **explicitly** in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
---
Microsoft's official guidelines (from first edition [Framework Design Guidelines](https://rads.stackover... | **Implicit** is when you define your interface via a member on your class. **Explicit** is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: `IList.CopyTo` would be implicitly implemented as:
```
public void CopyTo(Array array, int index)
{
throw new ... | Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
... | C# Interfaces. Implicit implementation versus Explicit implementation | [
"",
"c#",
".net",
"interface",
""
] |
I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.
What would be the best approach? | try using split
```
list($hh,$mm,$ss)= split(':',$duration);
``` | Something like this?
```
$vals = explode(':', $duration);
if ( $vals[0] == 0 )
$result = $vals[1] . ' minutes, ' . $vals[2] . ' seconds';
else
$result = $vals[0] . 'hours, ' . $vals[1] . ' minutes, ' . $vals[2] . ' seconds';
``` | How do you convert 00:00:00 to hours, minutes, seconds in PHP? | [
"",
"php",
"date",
""
] |
I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO\_SETTINGS\_MODULE environment variable?
If I run the following code:
```
>>> import django.template
>>> from django.te... | An addition to what other wrote, if you want to use Django Template on Django > 1.7, you must give your settings.configure(...) call the TEMPLATES variable and call django.setup() like this :
```
from django.conf import settings
settings.configure(TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.... | The solution is simple. It's actually [well documented](http://docs.djangoproject.com/en/dev/ref/templates/api/#configuring-the-template-system-in-standalone-mode), but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.)
The following code works:
```
>>> from... | How do I use Django templates without the rest of Django? | [
"",
"python",
"django",
"templates",
"django-templates",
"template-engine",
""
] |
I am 90% sure I saw this answer on stackoverflow before, in fact I had never seen the "int?" syntax before seeing it here, but no matter how I search I can't find the previous post, and it's driving me crazy.
It's possible that I've been eating the funny mushrooms by accident, but if I'm not, can someone please point ... | int? is shorthand for `Nullable<int>`.
[This](https://stackoverflow.com/questions/110229/how-do-nullable-types-work-in-c) may be the post you were looking for. | int? is Nullable.
MSDN: [Using Nullable Types (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/using-nullable-types) | What's the difference between 'int?' and 'int' in C#? | [
"",
"c#",
"syntax",
"types",
"nullable",
""
] |
Is it possible to throw an exception in a JSP without using scriptlet code? | You really shouldn't be doing anything at the JSP layer that explicitly throws exceptions. The reason you don't want to use scriptlets in JSPs is because that puts application logic in your view. Throwing an exception is inherently application logic, so it doesn't belong in your JSP, scriptlet or not. | You can throw an exception if you do this:
```
<c:out value="${1/0}" />
```
or something that is similarly "illegal"
Ideally though, since JSPs are associated with the view...you don't want to throw an exception. You want to catch them with `<c:catch>` | throw exception from a JSP | [
"",
"java",
"exception",
"jsp",
""
] |
I need to randomly fade my background images in and out.
It will be a timed function, like once every 5 seconds.
I need to do it with ASP.NET, Javascript, CSS or all three.
Please help me out here guys. Thank you. | Cycle, a jQuery plugin is a very flexible image rotating solution: <http://malsup.com/jquery/cycle/> | **This is the Answer:** never mind guys, after making a bit more exact search on Google. I found a good solution.
```
<html>
<head>
<!--
This file retrieved from the JS-Examples archives
http://www.js-examples.com
1000s of free ready to use scripts, tutorials, forums.
Author: Steve S - http://jsmadeeasy.com/
-->
<st... | How to rotate and fade background images in and out with javascript/ASP.NET/CSS | [
"",
"asp.net",
"javascript",
"css",
"image-manipulation",
""
] |
Okay, so this probably sounds terribly nefarious, but I need such capabilities for my senior project. Essentially I'm tasked with writing something that will cut down outbound spam on a zombified pc through a system of packet interception and evaluation. We have a number of algorithms we'll use on the captured messages... | Sounds like you need to write a [Winsock LSP](http://en.wikipedia.org/wiki/Layered_Service_Provider).
> Once in the stack, a Layered Service Provider can intercept and modify inbound and outbound Internet traffic. It allows processing all the TCP/IP traffic taking place between the Internet and the applications that a... | Use Snort, stripped down, if this is a long-term thing. It's built to watch for particular packets flying by, examining payload where needed, recording data and launching alerts.
It's intended for intrusion detection, but it makes a surprisingly good network monitor for particular things over long term use. | Best OS App for Outbound SMTP Packet Capture? | [
"",
"c++",
"windows",
"smtp",
"packet-capture",
"spam-prevention",
""
] |
I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3.
Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles.
My question is : i... | When possible, you should not store the entire contents of a file to be served in memory. Instead, aquire an InputStream for the data, and copy the data to the Servlet OutputStream in pieces. For example:
```
ServletOutputStream out = response.getOutputStream();
InputStream in = [ code to get source input stream ];
St... | Why wouldn't you just point them to the S3 url? Taking an artifact from S3 and then streaming it through your own server to me defeats the purpose of using S3, which is to offload the bandwidth and processing of serving the images to Amazon. | Streaming large files in a java servlet | [
"",
"java",
"java-io",
""
] |
In effect, if I have a `class c` and instances of `$c1` and `$c2`
which might have different private variable amounts but all their public methods return the same values I would like to be able to check that `$c1 == $c2?`
Does anyone know an easy way to do this? | You can also implement a equal($other) function like
```
<?php
class Foo {
public function equals($o) {
return ($o instanceof 'Foo') && $o.firstName()==$this.firstName();
}
}
```
or use foreach to iterate over the public properties (this behaviour might be overwritten) of one object and compare them t... | It's difficult to follow exactly what you're after. Your question seems to imply that these public methods don't require arguments, or that if they did they would be the same arguments.
You could probably get quite far using the inbuilt reflection classes.
Pasted below is a quick test I knocked up to compare the retu... | PHP: How do I check if all public methods of two classes return the same values? | [
"",
"php",
"oop",
""
] |
Sorry the title isn't more help. I have a database of media-file URLs that came from two sources:
(1) RSS feeds and (2) manual entries.
I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table '`urls`' has columns `'url, feed_id, timestamp'`.
`feed_id=''` for any URL th... | Assuming feed\_id = 0 is the manually entered stuff this does the trick:
```
select p.* from programs p
left join
(
select max(id) id1 from programs
where feed_id <> 0
group by feed_id
order by max(id) desc
limit 10
) t on id1 = id
where id1 is not null or feed_id = 0
order by id desc
limit 10;
`... | Assuming this table
```
CREATE TABLE feed (
feed varchar(20) NOT NULL,
add_date datetime NOT NULL,
info varchar(45) NOT NULL,
PRIMARY KEY (feed,add_date);
```
**this query should do what you want**. The inner query selects the last entry by feed and picks the 10 most recent, and then the outer query return... | MySQL Query: Select most-recent items with a twist | [
"",
"sql",
"mysql",
""
] |
I'm giving a presentation to a Java User's Group on Groovy and I'm going to be doing some coding during the presentation to show some side-by-side Java/Groovy. I really like the GroovyConsole as it's simple and I can resize the text easily.
I'm wondering if there is anything similar for Java? I know I could just use E... | [DrJava](http://www.drjava.org/) is your best bet. It also has an [Eclipse plugin](http://www.drjava.org/eclipse.shtml) to use the interactions pane like GroovyConsole. | try beanshell. its a scripting wrapper over java. <http://www.beanshell.org/> | Is there a Java Console/Editor similar to the GroovyConsole? | [
"",
"java",
"editor",
""
] |
What are some general tips to make sure I don't leak memory in C++ programs? How do I figure out who should free memory that has been dynamically allocated? | Instead of managing memory manually, try to use smart pointers where applicable.
Take a look at the [Boost lib](http://www.boost.org/), [TR1](http://en.wikipedia.org/wiki/Technical_Report_1), and [smart pointers](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm).
Also smart pointers are now a part ... | I thoroughly endorse all the advice about RAII and smart pointers, but I'd also like to add a slightly higher-level tip: the easiest memory to manage is the memory you never allocated. Unlike languages like C# and Java, where pretty much everything is a reference, in C++ you should put objects on the stack whenever you... | General guidelines to avoid memory leaks in C++ | [
"",
"c++",
"memory",
"memory-management",
"raii",
""
] |
Being a C# developer since version 1.0, F# has captured my free time for the past few weeks. Computers are now sold with 2, 4 .. Cores and multi-threading is not always simple to accomplish.
At the moment I see that F# has great potential for complicated and or heavy workloads.
Do you think that F# will (once RTM) bec... | I think regardless of whether F# becomes import for Enterprise Software being able to isolate pure functional portions of code in any language will be key to using the potential of multi-core computers. For instance Microsoft's Parallel Extensions for .NET are great, but there is still a lot of room to make mistakes by... | I think F# has great opportunity to make inroads some of the niche areas of enterprise applications such as mathematical modelling (e.g. for banking/trading applications). Removing side effects from functions also leads to great opportunities for parallelism and memoization. Its hard to say if these languages will ever... | F# and Enterprise Software | [
"",
"c#",
"f#",
"functional-programming",
"enterprise",
""
] |
In C++0x I would like to write a function like this:
```
template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
//Put things into the tuple
}
```
I first tried to use a for loop on `int i` and then do:
```
get<i>(my_tuple);
```
And then store some value in the result. However, `get` onl... | Since the "i" in
```
get<i>(tup)
```
needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values. Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too. | [Boost.Fusion](http://www.boost.org/doc/libs/release/libs/fusion/doc/html/index.html) is worth a look. It can 'iterate' over `std::pair`, `boost::tuple`, some other containers and its own tuple types, although I don't think it supports `std::tuple` yet. | In C++, can you have a function that modifies a tuple of variable length? | [
"",
"c++",
"tuples",
""
] |
I have tried:
1. Xdebug and Eclipse. Eclipse launches a web browser, but the browser tries to access a non-existent file in Eclipse's .app bundle.
2. Xdebug and NetBeans. It does a little bit better; a browser opens a page in /tmp which says "Launching. Please wait…" but nothing happens beyond that.
3. Xdebug and debu... | You may want to look into [MacGDBp](http://www.bluestatic.org/software/macgdbp/). It's new, free, and the UI looks great. It utilizes the Xdebug PHP extension as well. You can find instructions in the [help](http://www.bluestatic.org/software/macgdbp/help.php) section, which includes Xdebug configurations, and there's ... | Here's how I did it:
1 - Copy the latest version of xdebug.so from <http://aspn.activestate.com/ASPN/Downloads/Komodo/RemoteDebugging> to /usr/libexec.
2 - Add the following to the global php.ini:
```
zend_extension="/usr/libexec/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
... | PHP debugging on OS X - hopeless? | [
"",
"php",
"debugging",
"macos",
""
] |
As a beginner to TDD I am trying to write a test that assumes a property has had its value changed on a PropertyGrid (C#, WinForms, .NET 3.5).
Changing a property on an object in a property grid does not fire the event (fair enough, as it's a UI raised event, so I can see why changing the owned object may be invisible... | To unit test your code you will need to mock up an object of the UI interface element. There are many tools you can use to do this, and I can't recommend one over another. There's a good comparison between MoQ and Rhino Mocks here [at Phil Haack's blog](http://haacked.com/archive/2008/03/23/comparing-moq-to-rhino-mocks... | Microsoft has UI Automation built into the .Net Framework. You may be able to use this to simulate a user utilising your software in the normal way.
There is an MSDN article "[Using UI Automation for Automated Testing](http://msdn.microsoft.com/en-us/library/aa348551.aspx "MSDN - Using UI Automation for Automated Test... | Firing UI control events from a Unit Test | [
"",
"c#",
"winforms",
"unit-testing",
""
] |
In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.
My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception ... | The [MSDN guidelines](http://msdn.microsoft.com/en-us/library/ms229021(VS.80).aspx) state:
* Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.
* Do create and throw custom exceptions if you have an error condition that can be programmatically handled in... | You really should define your own exception : DataNotFoundException.
You should not use the basic class Exception, since when you will catch it in calling code, you will write something like
```
try
{
int i;
GetData(i);
}
catch(Exception e) //will catch many many exceptions
{
//Handle gracefully the "D... | What Exception should be thrown when an ADO.NET query cannot retrieve the requested data? | [
"",
".net",
"sql",
"exception",
"ado.net",
""
] |
The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.
I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedu... | Forget about `mysqli`, it's much harder to use than PDO and should have been already removed. It is true that it introduced huge improvements over mysql, but to achieve the same effect in mysqli sometimes requires enormous effort over PDO i.e. associative `fetchAll`.
Instead, take a look at [PDO](http://www.php.net/ma... | @michal kralik - unfortunately there's a bug with the MySQL C API that PDO uses which means that running your code as above with some versions of MySQL results in the error:
> "Syntax error or access violation: 1414 OUT or INOUT argument $parameter\_number for routine $procedure\_name is not a variable or NEW pseudo-v... | Stored Procedures, MySQL and PHP | [
"",
"php",
"mysql",
"stored-procedures",
""
] |
Here's my first question at SO.
I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish.
The problem is the applications is **very slow**.
How do I go about finding out what's slowin... | I've used [XDebug profiling](http://www.xdebug.org/docs/profiler) recently in a similiar situation. It outputs a full profile report that can be read with many common profiling apps ( Can't give you a list though, I just used the one that came with slackware ). | As Juan mentioned, xDebug is excellent. If you're on Windows, [WinCacheGrind](http://sourceforge.net/projects/wincachegrind/) will let you look over the reports. | Find out where your PHP code is slowing down (Performance Issue) | [
"",
"php",
"mysql",
"performance",
"profiling",
""
] |
If I open an image with `open("image.jpg")`, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?
Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?
I would prefer if I didn't have to download any additional libraries. | It's probably best to use the [Python Image Library](http://www.pythonware.com/products/pil/) to do this which I'm afraid is a separate download.
The easiest way to do what you want is via the [load() method on the Image object](https://web.archive.org/web/20201111195341/http://effbot.org/imagingbook/image.htm#tag-Ima... | Using [Pillow](http://python-pillow.github.io/) (which works with Python 3.X as well as Python 2.7+), you can do the following:
```
from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())
```
Now you have all pixel values. If it is RGB or another mode can be r... | How to read the RGB value of a given pixel in Python? | [
"",
"python",
"graphics",
"rgb",
"pixel",
""
] |
How do I have a Python script that can accept user input and how do I make it read in arguments if run from the command line? | To read user input you can try [the `cmd` module](https://docs.python.org/dev/library/cmd.html) for easily creating a mini-command line interpreter (with help texts and autocompletion) and [`raw_input`](https://docs.python.org/2/library/functions.html#raw_input) ([`input`](https://docs.python.org/dev/library/functions.... | ```
var = raw_input("Please enter something: ")
print "you entered", var
```
Or for Python 3:
```
var = input("Please enter something: ")
print("You entered: " + var)
``` | User input and command line arguments | [
"",
"python",
"input",
"command-line-arguments",
""
] |
I've recently read the Yahoo manifesto [Best Practices for Speeding Up Your Web Site](http://developer.yahoo.com/performance/rules.html#postload). They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.
But where exactly and when?
Should we put it before closing `</html>` or after ?... | There are two possibilities for truly unobtrusive scripts:
* including an external script file via a script tag in the head section
* including an external script file via a script tag at the bottom of the body (before `</body></html>`)
The second one can be faster as the original Yahoo research showed some browsers ... | It's never so cut and dry - Yahoo recommends putting the scripts just before the closing `</body>` tag, which will create the illusion that the page loads faster on an empty cache (since the scripts won't block downloading the rest of the document).
However, if you have some code you want to run on page load, it will o... | Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code? | [
"",
"javascript",
"performance",
"optimization",
"coding-style",
""
] |
I have a database with two tables (`Table1` and `Table2`). They both have a common column `[ColumnA]` which is an `nvarchar`.
How can I select this column from both tables and return it as a single column in my result set?
So I'm looking for something like:
```
ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Res... | ```
SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1
```
Also, if you know the contents of Table1 and Table2 will **NEVER** overlap, you can use UNION ALL in place of UNION instead. Saves a little bit of resources that way.
-- Kevin Fairchild | Do you care if you get dups or not?
UNION will be slower than UNION ALL because UNION will filter out dups | SQL: Select like column from two tables | [
"",
"sql",
""
] |
I am looking for a simple JavaScript example that updates DOM.
Any suggestions? | Here is a short pure-javascript example. Assume you have a div with the id "maincontent".
```
var newnode = document.createTextNode('Here is some text.');
document.getElementById('maincontent').appendChild(newnode);
```
Of course, things are a lot easier (especially when you want to do more complicated things) with j... | [@Ravi](https://stackoverflow.com/questions/44190?sort=newest#44250)
Here's working example of your code
```
<html>
<head>
<title>Font Detect please</title>
<script src="prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function changeTD()
{
$(... | Looking for a simple JavaScript example that updates DOM | [
"",
"javascript",
"dom",
""
] |
Any recommended crypto libraries for Java. What I need is the ability to parse X.509 Certificates to extract the information contained in them.
Thanks | In Java, java.security.cert.CertificateFactory.
"A certificate factory for X.509 must return certificates that are an instance of java.security.cert.X509Certificate" | There's a lot more in most certificates than what's handled by `java.security.cert.X509Certificate`. If you need to parse extension values, check out the [Bouncy Castle Crypto API](http://www.bouncycastle.org/index.html). (C# version is offered too.) | x509 certificate parsing libraries for Java | [
"",
"java",
"certificate",
"x509",
""
] |
In MySQL, If I have a list of date ranges (range-start and range-end). e.g.
```
10/06/1983 to 14/06/1983
15/07/1983 to 16/07/1983
18/07/1983 to 18/07/1983
```
And I want to check if another date range contains ANY of the ranges already in the list, how would I do that?
e.g.
```
06/06/1983 to 18/06/1983 = IN LIST
10... | This is a classical problem, and it's actually easier if you reverse the logic.
Let me give you an example.
I'll post one period of time here, and all the different variations of other periods that overlap in some way.
```
|-------------------| compare to this one
|---------| ... | Taking your example range of 06/06/1983 to 18/06/1983 and assuming you have columns called **start** and **end** for your ranges, you could use a clause like this
```
where ('1983-06-06' <= end) and ('1983-06-18' >= start)
```
i.e. check the start of your test range is before the end of the database range, and that t... | Comparing date ranges | [
"",
"sql",
"mysql",
"date",
""
] |
I've been thinking a lot lately about a music-oriented project I'd like to work on. Kind of like a game... kind of like a studio workstation (FL Studio, Reason).
I guess the best way to describe it would be: like "Guitar Hero", but with no canned tracks. All original music--composed by you, on the fly--but the softwar... | Have you checked out [JFugue](http://www.jfugue.org/)? It's an "open-source Java API for programming music without the complexities of MIDI".
**Additional information:** Found a couple of other resources referenced in the [JFugue documentation (pdf)](http://www.jfugue.org/jfugue-chapter1.pdf):
* [Audio Synthesis Engi... | Yeah, I noticed JFugue a few years ago. It's on my list of interesting computer/music bookmarks:
<http://delicious.com/BenjiSmith/computermusic>
<http://delicious.com/BenjiSmith/programming.java.libraries.music>
But JFugue is all about the structure of the music itself... the melodies, harmonies, rhythms, etc....
Wh... | Software Synth Library for Java | [
"",
"java",
"audio",
""
] |
When asking about [common undefined behavior in C](https://stackoverflow.com/questions/98340/what-are-the-common-undefinedunspecified-behavior-for-c-that-you-run-into), people sometimes refer to the strict aliasing rule.
What are they talking about? | A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to `uint32_t`s or `uint16_t`s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you ... | The best explanation I have found is by Mike Acton, [Understanding Strict Aliasing](http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html). It's focused a little on PS3 development, but that's basically just GCC.
From the article:
> "Strict aliasing is an assumption, made by the C (o... | What is the strict aliasing rule? | [
"",
"c++",
"c",
"undefined-behavior",
"strict-aliasing",
"type-punning",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.