Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like
```
- url: (.*)/
static_files: static\1/index.html
upload: static/index.html
- url: /
static_dir: static
```
with all the static html/jpg files stored under the static dir... | You need to register a catch-all script handler. Append this at the end of your app.yaml:
```
- url: /.*
script: main.py
```
In main.py you will need to put this code:
```
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class NotFoundPageHandler(webapp.RequestHand... | google app engine now has [Custom Error Responses](https://cloud.google.com/appengine/docs/python/config/appconfig?csw=1#Python_app_yaml_Custom_error_responses)
so you can now add an error\_handlers section to your app.yaml, as in this example:
```
error_handlers:
- file: default_error.html
- error_code: over_quota... | Google App Engine and 404 error | [
"",
"python",
"google-app-engine",
"http-status-code-404",
""
] |
I've been looking for a generic way to deal with bidirectional associations and a way to handle the inverse updates in manual written Java code.
For those who don't know what I'm talking about, here is an example. Below it are my current results of (unsatisfying) solutions.
```
public class A {
public B getB();
... | google collections (from google's internal code) -- <http://code.google.com/p/google-collections/> is Java Generics compatible(not only compatible, uses generics very well)
Class BiMap -- <http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/c... | Thanks for all suggestions. But none came close to what I was looking for, I probably formulated the question in a wrong way.
I was looking for a replacement for gemini, so for a way to handle this in an unobtrusive manner, without polluting the code with endless checks and special List implementations. This calls of ... | Generic Java Framework to Manage Bidirectional Associations and Inverse Updates | [
"",
"java",
"associations",
"bidirectional",
"inverse",
""
] |
I'm working in .Net 3.5sp1 in C# for an ASP.Net solution and I'm wondering if there's any way to turn on the Class Name and Method Name drop-downs in the text editor that VB.Net has at the top. It's one of the few things from VB that I actually miss.
Edit: Also, is there any way to get the drop downs to be populated w... | Go To:
```
Tools -> Options -> Text Editor -> C# -> General -> Navigation Bar
```
Make sure it is clicked, and that should show something at the top of your code that has all the classes and methods listed in your file. | In Visual Studio 2008 (and probably earlier versions):
Tools -> Options -> Text Editor -> C#(\*) -> General -> Navigation bar
(\*) or your preferred editor language | Visual Studio 2008: is there any way to turn on the Class Name/Method Name drop downs in C#? (like VB.Net has) | [
"",
"c#",
"vb.net",
"visual-studio-2008",
""
] |
this code always returns 0 in PHP 5.2.5 for microseconds:
```
<?php
$dt = new DateTime();
echo $dt->format("Y-m-d\TH:i:s.u") . "\n";
?>
```
Output:
```
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:26.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T2... | This seems to work, although it seems illogical that <http://us.php.net/date> documents the microsecond specifier yet doesn't really support it:
```
function getTimestamp()
{
return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);
}
``` | You can specify that your input contains microseconds when constructing a `DateTime` object, and use `microtime(true)` directly as the input.
Unfortunately, this will fail if you hit an exact second, because there will be no `.` in the microtime output; so use `sprintf` to force it to contain a `.0` in that case:
```... | PHP DateTime microseconds always returns 0 | [
"",
"php",
"datetime",
""
] |
I have an odd problem...I'm using a documentation generator which generates a lot of output like docs/foo.php.html. It's XHTML, and thus contains `<?xml...>` tags at the beginning of file. The problem is, Apache has somehow decided to run it through the PHP interpreter, even though ".php" appears in the middle of the f... | The problem seems to be in [mod\_mime](http://httpd.apache.org/docs/2.2/mod/mod_mime.html).
Quote from the Apache mod\_mime documentation page:
> If you would prefer only the last dot-separated part of the filename to be mapped to a particular piece of meta-data, then do not use the Add\* directives. For example, if ... | You could disable PHP's shorttags -- this is the recommended way to mix PHP and XML.
<http://us.php.net/ini.core>
```
short_open_tag = 0
``` | Why is Apache executing .php.html files as PHP? | [
"",
"php",
"html",
"apache",
""
] |
I have never seen a way to do this nicely, i would be interested in seeing how others do it. Currently i format it like this:
```
public Booking createVehicleBooking(Long officeId,
Long start,
Long end,
String... | A large set of parameters like this is often (but not always) an indicator that you could be using an object to represent the parameter set. This is especially true if either:
* There are several methods with similar large parameter sets, that can be replaced with a single method taking a parameter object.
* The metho... | ```
public Booking createVehicleBooking(
Long officeId,
Long start,
Long end,
String origin,
String destination,
String purpose,
String requirements,
Integer numberOfPassengers)
throws ServiceException {
/*..Code..*/
}
``` | How to format methods with large parameter lists | [
"",
"java",
"formatting",
"methods",
""
] |
I'm writing a [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) application which is supposed to play three sound files and at the end of each sound file, it's to change the source of an image.
I can get it to play the sounds using `System.Media.SoundPlayer`. However, it seems to play the sound in a differen... | Did you try [SoundPlayer.PlaySync Method](http://msdn.microsoft.com/en-us/library/system.media.soundplayer.playsync.aspx)? From the help:
> The PlaySync method uses the current
> thread to play a .wav file, preventing
> the thread from handling other
> messages until the load is complete. | Instead of using the Play method, use the [PlaySync](http://msdn.microsoft.com/en-us/library/system.media.soundplayer.playsync.aspx) method. | Play a sound, wait for it to finish and then do something? | [
"",
"c#",
"multithreading",
"audio",
"synchronization",
""
] |
I have a factory class that populates objects with data. I want to implementing saving from the object, but do not want to populate the object with db stuff - is it stupid to have my Factory that creates the class also save the data?
ie: in my .Save() method on the object i would call Factory.Save(myObject); | If you are concerned about database stuff in classes - have you considered using O/R mapper?
This would keep the database stuff entirely out of your code and your domain objects clean.
Maybe take a look at [NHibernate](http://www.hibernate.org/343.html) or [Active Record](http://www.castleproject.org/activerecord/ind... | The factory class is a creational pattern that helps with creating new objects.
There are various patterns which deal with persisting objects, one of which is data mapper
<http://martinfowler.com/eaaCatalog/dataMapper.html>
This is often used in conjection with Repository
<http://martinfowler.com/eaaCatalog/repositor... | Factory Class - Save Objects | [
"",
"c#",
"factory",
""
] |
The solution we developed uses a database (sqlserver 2005) for persistence purposes, and thus, all updated data is saved to the database, instead of sent to the program.
I have a front-end (desktop) that currently keeps polling the database for updates that may happen anytime on some critical data, and I am not really... | Since you're on SQL2005, you can use a [SqlDependency](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx) to be notified of changes. Note that you can use it pretty effortlessly with [System.Web.Caching.Cache](http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx), which, ... | First thought off the top of my head is a trigger combined with a message queue. | Keeping in sync with database | [
"",
"c#",
"sql-server",
".net-3.5",
""
] |
I have a Serializable object which is supposed to hold a java.awt.Image as its member. How should I go about serializing it?
*(Edited from a not so clear first version, sorry.)* | ImageIcon implements Serializable and it can be used to wrap an Image class
<http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/ImageIcon.html> | javax.swing.ImageIcon, as a part of Swing, does not guarantee to have compatible serialised form between versions. However, you can cheat and look at its readObject and writeObject code - find width and height, grab the pixels with PixelGrabber. I'm not entirely sure that covers the colour model correctly. The obvious ... | How to best serialize a java.awt.Image? | [
"",
"java",
"image",
"serialization",
""
] |
We're running a web app on Tomcat 6 and Apache mod\_proxy 2.2.3. Seeing a lot of 502 errors like this:
> Bad Gateway!
> The proxy server received an invalid response from an upstream server.
>
> The proxy server could not handle the request GET /the/page.do.
>
> Reason: Error reading from remote server
>
> If you thin... | So, answering my own question here. We ultimately determined that we were seeing 502 and 503 errors in the load balancer due to Tomcat threads timing out. In the short term we increased the timeout. In the longer term, we fixed the app problems that were causing the timeouts in the first place. Why Tomcat timeouts were... | Just to add some specific settings, I had a similar setup (with Apache 2.0.63 reverse proxying onto Tomcat 5.0.27).
For certain URLs the Tomcat server could take perhaps 20 minutes to return a page.
I ended up modifying the following settings in the Apache configuration file to prevent it from timing out with its pro... | Bad Gateway 502 error with Apache mod_proxy and Tomcat | [
"",
"java",
"apache",
"tomcat",
"mod-proxy",
""
] |
In JPA the Entities are nice annotated Plain Old Java Objects. But I have not found a good way to interact with them and the database.
In my current app, my basic design is always to have a sequence based id as primary key so I usually have to look up entities by other properties than PK.
And for each Entity I have a... | Try Seam. The [Query Objects](http://docs.jboss.com/seam/2.1.0.BETA1/reference/en-US/html_single/#d0e7527) do most of the work for you, and they're easily extendable. Or, you could always implement a similar pattern.
In general, Seam does a lot of useful stuff to bridge the gap between JPA and you view and business la... | You're being unnecessarily verbose. For one thing, getResultList() doesn't throw an exception when no rows are returned (at least not in Eclipse or Toplink--I can't imagine another provider being any different). getSingleResult() does, getResultList() doesn't. Also, you can use the builder pattern so:
```
@SuppressWar... | What is a good design for a query "layer" for Java JPA | [
"",
"java",
"hibernate",
"jpa",
"ejb",
""
] |
I have a `datetime` column in MySQL.
How can I convert it to the display as **mm/dd/yy H:M (AM/PM)** using PHP? | If you're looking for a way to normalize a date into MySQL format, use the following
```
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
```
The line `$phpdate = strtotime( $mysqldate )` accepts a string and performs a series of heuristics to turn that string into a unix timestamp.
... | To convert a date retrieved from MySQL into the format requested (`mm/dd/yy H:M (AM/PM)`):
```
// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM
```
Refer to the [PHP date fo... | Convert from MySQL datetime to another format with PHP | [
"",
"php",
"mysql",
"datetime",
""
] |
Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <http://gist.github.com/12978>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seco... | Don't waste time profiling. The time is always in the database operations. Do as few as possible. Just the minimum number of inserts.
Three Things.
One. Don't SELECT over and over again to conform the Date, Hostname and Person dimensions. Fetch all the data ONCE into a Python dictionary and use it in memory. Don't do... | In the for loop, you're inserting into the 'chats' table repeatedly, so you only need a single sql statement with bind variables, to be executed with different values. So you could put this before the for loop:
```
insert_statement="""
INSERT INTO chats(person_id, message_type, created_at, channel)
VALUES(:per... | How do you make Python / PostgreSQL faster? | [
"",
"python",
"postgresql",
""
] |
I have a custom class loader so that a desktop application can dynamically start loading classes from an AppServer I need to talk to. We did this since the amount of jars that are required to do this are ridiculous (if we wanted to ship them). We also have version problems if we don't load the classes dynamically at ru... | The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.
One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppS... | Yes there are ways to load classes and to "unload" them later on. The trick is to implement your own classloader which resides between high level class loader (the System class loader) and the class loaders of the app server(s), and to hope that the app server's class loaders do delegate the classloading to the upper l... | Unloading classes in java? | [
"",
"java",
"classloader",
""
] |
I have a form with many input fields.
When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array? | ```
$('#myForm').submit(function() {
// get all the inputs into an array.
var $inputs = $('#myForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).v... | Late to the party on this question, but this is even easier:
```
$('#myForm').submit(function() {
// Get all the forms elements and their values in one step
var values = $(this).serialize();
});
``` | Obtain form input fields using jQuery? | [
"",
"javascript",
"jquery",
""
] |
I love the way I can profile a Java/.Net app to find performance bottlenecks or memory problems. For example, it's very easy to find a performance bottleneck looking at [the call tree with execution times and invocation counts per method](http://www.yourkit.com/dotnet/features/cpu-tree-threads-together.gif). In SQL Ser... | Check out [SQL Nexus Tool](http://www.codeplex.com/sqlnexus/Wiki/View.aspx?title=SqlNexusReports&referringTitle=Home). This has some good reports on identifying bottlenecks.
SQL Nexus is a tool that helps you identify the root cause of SQL Server performance issues. It loads and analyzes performance data collected by S... | In addition to SQL Server Profiler, as mentioned in a comment from @Galwegian, also check out your execution plan when you run a query.
<http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx>
<http://en.wikipedia.org/wiki/Query_plan> | Is there a SQL Server profiler similar to Java/.Net profilers? | [
"",
"java",
"sql-server",
"stored-procedures",
"profiling",
""
] |
What is the [MIME](http://en.wikipedia.org/wiki/MIME) type of javascript?
More specifically, what is the right thing to put in the "type" attribute of a script tag? `application/x-javascript` and `text/javascript` seem to be the main contenders. | This is a common mistake. The MIME type for javascript wasn't standardized for years. It's now [officially](http://www.rfc-editor.org/rfc/rfc4329.txt): "**application/javascript**".
The real kicker here is that most browsers won't use that attribute anyway, at least not in the case of the script tag. They actually pee... | Far out this is the first page I've found on the topic with any sense about it.
My collective research suggests:
1. `text/javascript` as Keparo stated must be used in html4 and xhtml1 if you want it to validate. Though browsers ignore it.
2. `application/javascript` is expected to be the new official MIME type if eve... | What is the javascript MIME type for the type attribute of a script tag? | [
"",
"javascript",
"mime-types",
""
] |
Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this:
```
struct MY_STRUCT
{
int n1;
int n2;
};
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct()
{
memset(this, 0, sizeof(MY_STRUCT));
}
};
```
This trick... | ## PREAMBLE:
While my answer is still Ok, I find [litb's answer](https://stackoverflow.com/questions/112085/is-this-c-structure-initialization-trick-safe/1315024#1315024) quite superior to mine because:
1. It teaches me a trick that I did not know (litb's answers usually have this effect, but this is the first time I... | You can simply value-initialize the base, and all its members will be zero'ed out. This is guaranteed
```
struct MY_STRUCT
{
int n1;
int n2;
};
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct():MY_STRUCT() { }
};
```
For this to work, there should be no user declared constructor in the base class,... | Is this C++ structure initialization trick safe? | [
"",
"c++",
"data-structures",
""
] |
I have a Tapestry application that is serving its page as UTF-8. That is, server responses have header:
```
Content-type: text/html;charset=UTF-8
```
Now within this application there is a single page that should be served with ISO-8859-1 encoding. That is, server response should have this header:
```
Content-type: ... | Have you considered a Filter? Maybe not as elegant as something within Tapestry, but using a plain Filter, that registers the url mapping(s) of interest. One of its init parameters would be the encoding your after. Example:
```
public class EncodingFilter implements Filter {
private String encoding;
private FilterConf... | You could have done:
```
@Override
public ContentType getResponseContentType() {
return new ContentType("text/html;charset=" + someCharEncoding);
}
``` | Setting ISO-8859-1 encoding for a single Tapestry 4 page in application that is otherwise totally UTF-8 | [
"",
"java",
"encoding",
"utf-8",
"tapestry",
"iso-8859-1",
""
] |
I'm having a problem using the java.text.MessageFormat object.
I'm trying to create SQL insert statements. The problem is, when I do something like this:
```
MessageFormat messageFormat = "insert into {0} values ( '{1}', '{2}', '{3}', {4} )";
Object[] args = { str0, str1, str2, str3, str4 };
String result = messageFo... | I just tried double quotes and it worked fine for me:
```
MessageFormat messageFormat = new MessageFormat("insert into {0} values ( ''{1}'', ''{2}'', ''{3}'', {4} )");
Object[] args = {"000", "111", "222","333","444","555"};
String result = messageFormat.format(args);
```
The result is:
```
insert into 000 values ( ... | Sorry if this is off the side, but it looks like you're trying to replicate the PreparedStatement that is already in JDBC.
If you are trying to create SQL to run against a database then I suggest that you look at PreparedStatement, it already does what you're trying to do (with a slightly different syntax).
Sorry if ... | Java MessageFormat - How can I insert values between single quotes? | [
"",
"java",
""
] |
We need to optimize the text rendering for a C# [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) application displaying a large number of small strings in an irregular grid. At any time there can be well over 5000 cells visible that update 4 times per second. The font family and size is consistent across the... | A Microsoft developer has posted a [GDI vs. GDI+ Text Rendering Performance](http://blogs.msdn.com/cjacks/archive/2006/05/19/602021.aspx) article on his blog which answers the raw speed question: on his system, GDI DrawText was about 6 times faster than GDI+ DrawString.
If you need to be a real speed demon, TextOut is... | 5000+ text rendering is slow even with GDI, especially if you need scrolling. Create a separate rendering thread and notify the UI thread every 200 ms and bitblt the current results. It gives a smooth user experience. | Fastest API for rendering text in Windows Forms? | [
"",
"c#",
"windows",
"performance",
""
] |
If I have an array of a fixed size depending on how it is defined and used, I typically use one of two ways to reference it.
Array type 1: Since it is a fixed size based on a define, I just use that define in all my loops referencing it.
```
#define MAXPLAYERS 4
int playerscores[MAXPLAYERS];
for(i=0;i<MAXPLAYERS;++... | This will work for both of your cases, regardless of array element type:
```
#define ARRAY_COUNT(x) (sizeof(x)/sizeof((x)[0]))
...
struct foo arr[100];
...
for (i = 0; i < ARRAY_COUNT(arr); ++i) {
/* do stuff to arr[i] */
}
``` | In C++ just use the vector class.
If you can't for some reason then there are macro implementations of what you want.
See this answer for a set of macros from winnt.h that work in C and even more safely in C++:
[Can this macro be converted to a function?](https://stackoverflow.com/questions/95500/can-this-macro-be-co... | Best practices for handling variable size arrays in c / c++? | [
"",
"c++",
"c",
"arrays",
""
] |
In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy? | The method GetDrives() returns a DriveInfo class which has a property DriveType that corresponds to the enumeration of System.IO.DriveType:
```
public enum DriveType
{
Unknown, // The type of drive is unknown.
NoRootDirectory, // The drive does not have a root directory.
Removable, // The... | [DriveInfo.DriveType](http://msdn.microsoft.com/en-us/library/system.io.driveinfo.drivetype.aspx) should work for you.
```
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine(" File type: {0}", d.DriveType);
}
``` | How to detect if any specific drive is a hard drive? | [
"",
"c#",
"hardware",
"hard-drive",
""
] |
In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:
```
interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main... | As someone else has mentioned, C++0x is getting this built into the language. Until then, I'd recommend [Bjarne Stroustrup](http://en.wikipedia.org/wiki/Bjarne_Stroustrup)'s [suggestions for template constraints](http://www.stroustrup.com/bs_faq2.html#constraints).
Edit: [Boost](http://boost.org) also has an [alternat... | If you use C++11, you can use `static_assert` with `std::is_base_of` for this purpose.
For example,
```
#include <type_traits>
template<typename T>
class YourClass {
YourClass() {
// Compile-time check
static_assert(std::is_base_of<BaseClass, T>::value, "type parameter of this class must derive ... | Template Constraints C++ | [
"",
"c++",
"templates",
"constraints",
""
] |
When I have a regular textbox in a UpdatePanel (not an ASP.NET control) with some JavaScript events on it, after the UpdatePanel updates my events are gone. Is there a way to re-attach my events after the update? (Preferably without putting my events inline). | You can use the [endRequest](http://www.asp.net/AJAX/documentation/live/ClientReference/Sys.WebForms/PageRequestManagerClass/PageRequestManagerEndRequestEvent.aspx) event of the [PageRequestManager](http://www.asp.net/AJAX/documentation/live/ClientReference/Sys.WebForms/PageRequestManagerClass/default.aspx) class. | You can have a `setInterval()` loop on document load that would search for the element in the update panel and if it didn't have the events, it can re-attach them. | How do I perform an action after an UpdatePanel updates? | [
"",
"javascript",
"asp.net-ajax",
"updatepanel",
""
] |
Does anyone have an example of script that can work reliably well across IE/Firefox to detect if the browser is capable of displaying embedded flash content. I say reliably because I know its not possible 100% of the time. | [SWFObject](https://github.com/swfobject/swfobject) is very reliable. I have used it without trouble for quite a while. | I agree with [Max Stewart](https://stackoverflow.com/questions/159261/cross-browser-flash-detection-in-javascript/159374#159374). [SWFObject](https://github.com/swfobject/swfobject) is the way to go. I'd like to supplement his answer with a code example. This ought to to get you started:
Make sure you have included th... | Cross Browser Flash Detection in Javascript | [
"",
"javascript",
"flash",
"cross-browser",
""
] |
So I have a ListView with an upper limit of about 1000 items. I need to be able to filter these items using a textbox's TextChanged event. I have some code that works well for a smaller number of items (~400), but when I need to re-display a full list of all 1000 items, it takes about 4 seconds.
I am not creating new ... | There are two things to address this:
1. Turn off sorting while manipulating the list contents.
2. Hide the list so it doesn't try to paint.
The 1st point is the biggest performance gain in list manipulation out of these two. To achieve this, just set the ListViewItemSorter to null for the duration of the modificatio... | There is a better way, you can use the [VirtualMode](http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.virtualmode.aspx) of the list view.
That documentation should get you started. The idea is to provide information to the ListView only as it's needed. Such information is retrieved using events. A... | How to efficiently filter a large LIstViewItemCollection? | [
"",
"c#",
".net",
"winforms",
"performance",
"listview",
""
] |
Out of order execution in CPUs means that a CPU can reorder instructions to gain better performance and it means the CPU is having to do some very nifty bookkeeping and such. There are other processor approaches too, such as hyper-threading.
Some fancy compilers understand the (un)interrelatedness of instructions to a... | It sounds like you ran into the same problem chip designers face: Executing a single instruction takes a lot of effort, but it involves a bunch of different steps that can be strung together in an [execution pipeline](http://en.wikipedia.org/wiki/Pipeline_(computing)). (It is easier to execute things in parallel when y... | Given optimizing compilers and pipelined processors, I would suggest you just write clear, readable code. | Explicit code parallelism in c++ | [
"",
"c++",
"performance",
"design-patterns",
""
] |
I've always just FTPed files down from sites, edited them and put them back up when creating sites, but feel it's worth learning to do things properly.
I've just commited everything to a SVN repo, and have tried sshing into the server and checking out a tagged build, as well as updating that build using switch.
All g... | You don't necessarily need to use SVN to deploy the files to the server. Keep using FTP for that and just use SVN for revision history. | I'd recommend you keep using Subversion to track all changes, even bug fixes. When you wish to deploy to your production server, you should use SSH and call `svn update`. This process can be automated using [Capistrano](http://www.capify.org/), meaning that you can sit at your local box and call `cap deploy` -- Capistr... | What's the best way to use SVN to version control a PHP site? | [
"",
"php",
"svn",
""
] |
For example, the standard division symbol '/' rounds to zero:
```
>>> 4 / 100
0
```
However, I want it to return 0.04. What do I use? | There are three options:
```
>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04
```
which is the same behavior as the C, C++, Java etc, or
```
>>> from __future__ import division
>>> 4 / 100
0.04
```
You can also activate this behavior by passing the argument `-Qnew` to the Python interpreter:
```
$ python -Qnew
>>> 4 / 1... | Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:
```
>>> 0.4/100.
0.0040000000000000001
```
If you actually want a *decimal* value, do this:
```
>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")
```
That will gi... | How do I get a decimal value when using the division operator in Python? | [
"",
"python",
"python-2.7",
"math",
"syntax",
"operators",
""
] |
Here's what I would like to do:
I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much *looks* the same, I don't want to store the latest snapshot.
I imagine there's some way of quantifying the difference, and I... | ## General idea
Option 1: Load both images as arrays (`scipy.misc.imread`) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference.
Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather t... | **A simple solution:**
Encode the image as a **jpeg** and look for a substantial change in **filesize**.
I've implemented something similar with video thumbnails, and had a lot of success and scalability. | How can I quantify difference between two images? | [
"",
"python",
"image-processing",
"background-subtraction",
"image-comparison",
"timelapse",
""
] |
What is the best way to convert an int or null to boolean value in an SQL query, such that:
* Any non-null value is **TRUE** in the results
* Any null value is **FALSE** in the results | To my knowledge (correct me if I'm wrong), there is no concept of literal boolean values in SQL. You can have expressions evaluating to boolean values, but you cannot output them.
This said, you can use CASE WHEN to produce a value you can use in a comparison:
```
SELECT
CASE WHEN ValueColumn IS NULL THEN 'FALSE... | No need to use case... when:
```
select (column_name is not null) as result from table_name;
```
Returns 1 for all fields not NULL and 0 for all fields that are NULL, which is as close as you can get to booleans in SQL. | What is the best way to convert an int or null to boolean value in an SQL query? | [
"",
"sql",
"null",
"boolean",
"type-conversion",
""
] |
Have a n-tire web application and search often times out after 30 secs. How to detect the root cause of the problem? | Log at separation of concerns, in this case at the boundaries of each layer.
when you say search, I'd assume that this is a web app where the user is searching for some text.
Is the DB search involved ?
Is there a possibility that your garbage collector is kicking in and the search timed out ?
Try to log your garbage ... | You can add trace code to log its activities and then look at each operation to see what part times out and why. | How to detect intermittent time out problem in web applications? | [
"",
"java",
"web-services",
""
] |
I need a select from table which does not have column that tells when row was inserted, only `timestamp` column (values like: 0x0000000000530278). Some data was imported to the table yesterday and now I need to find out what exactly was imported :(
Is there a way to do it using only `timestamp` info? [Here](http://www... | The Transact-SQL timestamp data type is a binary data type with no time-related values.
So to answer your question: *Is there a way to get DateTime value from timestamp type column?*
The answer is: *No* | The timestamp datatype in SQL Server 2005 is a synonym of rowversion and is just a number that is automatically incremented with each row update.
You can cast it to bigint to see its value.
To get what you want for new or updated rows, you should propably add another datetime column (lastupdate) and a trigger to upda... | Is there a way to get DateTime value from timestamp type column? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
This code works (C# 3)
```
double d;
if(d == (double)(int)d) ...;
```
1. Is there a better way to do this?
2. For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)
*Note:* Several people pointed out the (important) point that == is often proble... | ```
d == Math.Floor(d)
```
does the same thing in other words.
NB: Hopefully you're aware that you have to be very careful when doing this kind of thing; floats/doubles will very easily accumulate miniscule errors that make exact comparisons (like this one) fail for no obvious reason. | This would work I think:
```
if (d % 1 == 0) {
//...
}
``` | Test if a floating point number is an integer | [
"",
"c#",
"floating-point",
"numerical",
""
] |
In c#, how can I check to see if a link button has been clicked in the page load method?
I need to know if it was clicked before the click event is fired. | ```
if( IsPostBack )
{
// get the target of the post-back, will be the name of the control
// that issued the post-back
string eTarget = Request.Params["__EVENTTARGET"].ToString();
}
``` | if that doesn't work.Try `UseSubmitBehavior="false"` | ASP.NET : Check for click event in page_load | [
"",
"c#",
"asp.net",
".net",
"pageload",
""
] |
Is there a fix or a workaround for the memory leak in getpwnam? | `getpwnam()` **does not** suffer of memory leak. Subsequent calls, indeed, will overwrite its static internal buffer.
Such kind of functions are instead *non-reentrant* and therefore *non-thread safe*. Paul suggested the use of `getpwnam_r()` which is the reentrant version, that is safe to be used in a multithread con... | Use getpwnam\_r. | Is there a fix or a workaround for the memory leak in getpwnam? | [
"",
"c++",
"linux",
""
] |
Ok, my actual problem was this: I was implementing an `IList<T>`. When I got to `CopyTo(Array array, int index)`, this was my solution:
```
void ICollection.CopyTo(Array array, int index)
{
// Bounds checking, etc here.
if (!(array.GetValue(0) is T))
throw new ArgumentException("Cannot cast to this typ... | The only way to be sure is with reflection, but 90% of the time you can avoid the cost of that by using `array is T[]`. Most people are going to pass a properly typed array in, so that will do. But, you should always provide the code to do the reflection check as well, just in case. Here's what my general boiler-plate ... | There is a method on Type specifically for this, try:
```
if(!typeof(T).IsAssignableFrom(array.GetElementType()))
``` | Proper nullable type checking in C#? | [
"",
"c#",
"casting",
"nullable",
""
] |
I am currently initializing a Hashtable in the following way:
```
Hashtable filter = new Hashtable();
filter.Add("building", "A-51");
filter.Add("apartment", "210");
```
I am looking for a nicer way to do this.
I tried something like
```
Hashtable filter2 = new Hashtable() {
{"building", "A-51"},
{"apartmen... | The exact code you posted:
```
Hashtable filter2 = new Hashtable()
{
{"building", "A-51"},
{"apartment", "210"}
};
```
Compiles perfectly in C# 3. Given you reported compilation problems, I'm guessing you are using C# 2? In this case you can at least do this:
```
... | In C# 3 it should compile fine like this:
```
Hashtable table = new Hashtable {{1, 1}, {2, 2}};
``` | Is there a better way to initialize a Hastable in .NET without using Add method? | [
"",
"c#",
""
] |
An idiom commonly used in OO languages like Python and Ruby is instantiating an object and chaining methods that return a reference to the object itself, such as:
```
s = User.new.login.get_db_data.get_session_data
```
In PHP, it is possible to replicate this behavior like so:
```
$u = new User();
$s = $u->login()->... | All of these proposed solutions complicate your code in order to bend PHP to accomplish some syntactic nicety. Wanting PHP to be something it's not (like good) is the path to madness.
I would just use:
```
$u = new User();
$s = $u->login()->get_db_data()->get_session_data();
```
It is clear, relatively concise and i... | ```
<?php
class User
{
function __construct()
{
}
function Login()
{
return $this;
}
function GetDbData()
{
return $this;
}
function GetSession()
{
return array("hello" => "world");
... | "Inline" Class Instantiation in PHP? (For Ease of Method Chaining) | [
"",
"php",
"oop",
"static-methods",
""
] |
Please bear with me, I'm just learning C++.
I'm trying to write my header file (for class) and I'm running into an odd error.
```
cards.h:21: error: expected unqualified-id before ')' token
cards.h:22: error: expected `)' before "str"
cards.h:23: error: expected `)' before "r"
```
What does "expected unqualified-id ... | Your issue is your `#define`. You did `#define Card`, so now everywhere `Card` is seen as a token, it will be replaced.
Usually a `#define Token` with no additional token, as in `#define Token Replace` will use the value `1`.
Remove the `#define Card`, it's making line 22 read: `1();` or `();`, which is causing the c... | (edited for updated question)
Remove the `#define` statements, they're mangling the file. Were you trying to implement an include guard? That would be something like this:
```
#ifndef CARD_H
#define CARD_H
class Card ...
...
#endif
```
---
old answer:
It means that `string` is not defined in the current line. Tr... | GCC - "expected unqualified-id before ')' token" | [
"",
"c++",
""
] |
I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what ro... | Building a DSL to be interpreted by Python.
Step 1. Build the run-time classes and objects. These classes will have all the cursor loops and SQL statements and all of that algorithmic processing tucked away in their methods. You'll make heavy use of the [Command](http://exciton.cs.rice.edu/javaresources/DesignPatterns... | I think we're going to need a bit more information here. Let me know if any of the following is based on incorrect assumptions.
First of all, as you pointed out yourself, there already exists a DSL for selecting rows from arbitrary tables-- it is called "SQL". Since you don't want to reinvent SQL, I'm assuming that yo... | Writing a Domain Specific Language for selecting rows from a table | [
"",
"python",
"database",
"algorithm",
"dsl",
""
] |
I have a form in which people will be entering dollar values.
Possible inputs:
$999,999,999.99
999,999,999.99
999999999
99,999
$99,999
The user can enter a dollar value however they wish. I want to read the inputs as doubles so I can total them.
I tried just typecasting the strings to doubles but that didn... | A regex won't convert your string into a number. I would suggest that you use a regex to validate the field (confirm that it fits one of your allowed formats), and then just loop over the string, discarding all non-digit and non-period characters. If you don't care about validation, you could skip the first step. The s... | You don't ever want to represent monetary values as floats!
For example, take the following (seemingly straight forward) code:
```
$x = 1.0;
for ($ii=0; $ii < 10; $ii++) {
$x = $x - .1;
}
var_dump($x);
```
You might assume that it would produce the value zero, but that is not the case. Since `$x` is a floating poi... | How to add currency strings (non-standardized input) together in PHP? | [
"",
"php",
""
] |
I have an object of class F. I want to output the contents of the object using Console.WriteLine for quick and dirty status updates like this:
Console.WriteLine(objectF);
This prints out only the name of the class to the console:
```
F
```
I want to overload this somehow so that I can instead print out some useful ... | Console.WriteLine(objectF)
Should work, if you overloaded `ToString`. When the framework needs to convert an object to a string representation, it invokes `ToString`.
```
public override string ToString()
{
// replace the line below with your code
return base.ToString();
}
``` | You should override ToString() though in some situations you may just find the following code useful:
```
public static class ObjectUtility
{
public static string ToDebug(this object obj)
{
if (obj == null)
return "<null>";
var type = obj.GetType();
var props = type.GetProp... | What interface or method should my class implement to print what I want in Console.WriteLine? | [
"",
"c#",
".net",
"console-application",
"console.writeline",
""
] |
How do I prevent my users from accessing directly pages meant for ajax calls only?
Passing a key during ajax call seems like a solution, whereas access without the key will not be processed. But it is also easy to fabricate the key, no? Curse of View Source...
p/s: Using Apache as webserver.
EDIT: To answer why, I h... | As others have said, Ajax request can be emulated be creating the proper headers.
If you want to have a basic check to see if the request is an Ajax request you can use:
```
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
//Request identified as ajax request
}
```
However you should never base your... | There is no way of guaranteeing that they're accessing it through AJAX. Both direct access and AJAX access come from the client, so it can easily be faked.
Why do you want to do this anyways?
If it's because the PHP code isn't very secure, make the PHP code more secure. (For example, if your AJAX passes the user id t... | Prevent direct access to a PHP page | [
"",
"php",
"ajax",
"apache",
""
] |
Assuming I have three tables :
TableA (key, value)
TableB (key, value)
TableC (key, value)
and I want to return a value for all keys. If the key exists in TableC return that value else if the key exists in B return that value else return the value from table A
The best I have come up with so far is
```
SELECT key,Va... | OK, using your concrete example as a basis, I came up with a solution different from the others posted (although I think I like your solution better). This was tested on MS SQL Server 2005 - changes may be needed for your SQL dialect.
First, some DDL to set the stage:
```
CREATE TABLE [dbo].[StandardSchedule](
[s... | Here is an alternate SQL statement:-
```
SELECT
ALL_KEYS.KEY,
NVL( TABLEC.VALUE, NVL( TABLEB.VALUE, TABLEA.VALUE)) AS VALUE
FROM
(SELECT KEY AS KEY FROM TABLEA
UNION
SELECT KEY FROM TABLEB
UNION
SELECT KEY FROM TABLEC) ALL_KEYS,
TABLEA,
TABLEB,
TABLEC
WHERE
ALL_KEYS.K... | Return values from different tables based on a priority | [
"",
"sql",
""
] |
I'm curious as to if there are any best practices relating to JQuery when constructing encapsulated code blocks.
Generally, when I construct a page I like to encapsulate the functions used within that page inside an object. This allows me some encapsulation when building applications. There's nothing I hate more than ... | Since I've been working with jQuery for a while now, I've decided on a standard pattern that works well for me.
It's a combination of the YUI module pattern with a bit of jQuery plugin pattern mixed in.. We ended up using the self executing closure pattern. This is beneficial in a few ways:
1. It keeps code to a mini... | I use YUI and jQuery when developing (YUI widgets and a few convenience functions, jQuery selectors and javascript "extensions"), and the general javascript template I use is this:
```
/*global YAHOO, $ */
// Create the public-scope accessable namespace for this page
YAHOO.namespace('Project');
YAHOO.Project.page = ... | JQuery JavaScript Design: Self Executing Function or Object Literal? | [
"",
"javascript",
"jquery",
""
] |
I have a page being loaded with jQuery. The initial load includes 100 records with 6 icons per record. Needless to say, it takes a few seconds to load and I want to give the user a "loading" prompt/animation.
Any ideas? | <http://www.ajaxload.info/> is a great resource for generating animated GIFs for this sort of thing.
Once you've got your animation, render it as part of the page; fire the jQuery load mechanism on the animation's onload() event (so you're certain the animation has loaded first), and use a callback at the end of your ... | Matt Berseth has [**a nice jQuery-based way of doing this**](http://mattberseth.com/blog/2007/10/yui_style_ajax_progress_indica.html). | Do you have any Ajax loading image ideas for use with jQuery? | [
"",
"javascript",
"jquery",
"ajax",
""
] |
Would having a nice little feature that makes it quicker to write code like Automatic Properties fit very nicely with the mantra of VB.NET?
Something like this would work perfect:
```
Public Property FirstName() As String
Get
Set
End Property
```
**UPDATE:** VB.NET 10 (coming with Visual Studio 2010 and .NET... | One reason many features get delayed in VB is that the development structure is much different than in C# and additionally, that often more thought goes into details. The same seems to be true in this case, as suggested by [Paul Vick's post](http://www.panopticoncentral.net/archive/2008/03/27/23050.aspx) on the matter.... | It also wasn't as big of a pain point in vb.net, since visual studio will automatically create 90% of the skeleton code of a property for you whereas with C# you used to have to type it all out. | Why doesn't VB.NET 9 have Automatic Properties like C# 3? | [
"",
"c#",
"vb.net",
"properties",
"language-features",
""
] |
How do I find the location of my `site-packages` directory? | There are two types of site-packages directories, *global* and *per user*.
1. **Global** site-packages ("[dist-packages](https://stackoverflow.com/questions/9387928/whats-the-difference-between-dist-packages-and-site-packages)") directories are listed in `sys.path` when you run:
```
python -m site
```
F... | ```
>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
```
(or just first item with `site.getsitepackages()[0]`) | How do I find the location of my Python site-packages directory? | [
"",
"python",
""
] |
I am looking at some code and it has this statement:
```
~ConnectionManager()
{
Dispose(false);
}
```
The class implements the `IDisposable` interface, but I do not know if that is part of that the tilde(~) is used for. | **~ is the destructor**
1. Destructors are invoked automatically, and cannot be invoked explicitly.
2. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
3. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
4. Destructors ca... | This is a [finalizer](http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx). To be honest, you should very rarely need to write a finalizer. You really only need to write one if:
* You have direct access to an unmanaged resource (e.g. through an `IntPtr`) and you can't use `SafeHandle` which makes it ea... | What does the tilde before a function name mean in C#? | [
"",
"c#",
"syntax",
"tilde",
""
] |
I want to write something that acts just like confirm() in javascript, but I want to write it myself so I can skin the dialog box. In having trouble thinking through how I would basically force the javascript thread to wait until the user responds and then return true or false. | If I were you, I would look at one of the popular javascript libraries. Most contain some sort of modal dialog.
A couple I found for JQuery are [jqModal](http://dev.iceburg.net/jquery/jqModal/) and [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/).
When you build the modal dialog, you will have to tie e... | You really want to use a framework for this, because of the number of weird cross-browser issues that you'll encounter trying to build it yourself.
I've had good results using [jqModal](http://dev.iceburg.net/jquery/jqModal/), a plugin for the jQuery framework that lets you define modal dialogs, but it's by no means t... | How do I write my own confirm dialog in javascript? | [
"",
"javascript",
"modal-dialog",
""
] |
I recall reading, on multiple occasions and in multiple locations, that when firing the typical event:
```
protected virtual OnSomethingHappened()
{
this.SomethingHappened(this, EventArgs.Empty);
}
```
e should be EventArgs.Empty if there are no interesting event args, not null.
I've followed the guidance in my ... | I believe the reasoning behind the NOT NULL is that when passed as a parameter, it is not expected for the method to need to potentially handle a null reference exception.
If you pass null, and the method tries to do something with e it will get a null reference exception, with EventArgs.Empty it will not. | `EventArgs.Empty` is an instance of the [Null object pattern](http://en.wikipedia.org/wiki/Null_Object_pattern).
Basically, having an object representing "no value" to avoid checking for null when using it. | Why use EventArgs.Empty instead of null? | [
"",
"c#",
"events",
"eventargs",
""
] |
In the [Python documentation](https://docs.python.org/2/library/threading.html#thread-objects)
it says:
> A thread can be flagged as a "daemon thread". The significance of this
> flag is that the entire Python program exits when only daemon threads
> are left. The initial value is inherited from the creating thread.
... | Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.
Without daemon threads, you'd have to keep track of them, and... | Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:
1. Connect to the mail server and ask how many unread messages you have.
2. Signal the GUI with the updated count.
3. Sleep for a little whil... | Daemon Threads Explanation | [
"",
"python",
"multithreading",
"daemon",
"python-multithreading",
""
] |
I am searching for an open source Java library to generate thumbnails for a given URL. I need to bundle this capability, rather than call out to external services, such as [Amazon](http://aws.amazon.com/ast/) or [websnapr](http://www.websnapr.com/).
<http://www.webrenderer.com/> was mentioned in this post: [Server gen... | The first thing that comes to mind is using AWT to capture a screen grab (see code below). You could look at capturing the [JEditorPane](http://java.sun.com/javase/6/docs/api/javax/swing/JEditorPane.html), the [JDIC](https://jdic.dev.java.net/) [WebBrowser](https://jdic.dev.java.net/nonav/documentation/javadoc/jdic/org... | You're essentially asking for a complete rendering engine accessible by Java. Personally, I would save myself the hassle and call out to a child process.
Otherwise, I ran into this pure Java browser: [Lobo](http://lobobrowser.org/java-browser.jsp) | Open source Java library to produce webpage thumbnails server-side | [
"",
"java",
"open-source",
"thumbnails",
""
] |
In VB.NET (or C#) how can I determine programmatically if a public variable in class helper.vb is used anywhere within a project? | From [MSDN](http://msdn.microsoft.com/en-us/library/aa300858(VS.71).aspx)
The Find object allows you to search for and replace text in places of the environment that support such operations, such as the Code editor.
It is intended primarily for macro recording purposes. The editor's macro recording mechanism uses Fin... | Find all References is your friend. | How do you check if a variable is used in a project programmatically? | [
"",
"c#",
".net",
"vb.net",
"add-in",
"envdte",
""
] |
After reading this answer:
[best way to pick a random subset from a collection?](https://stackoverflow.com/questions/136474/best-way-to-pick-a-random-subset-from-a-collection#136513)
It got me wondering, how does one pick a random seed in Java?
And don't say use System.currentTimeMillis() or System.nanoTime(). Read t... | Take a look at [Uncommons Maths](https://uncommons-maths.dev.java.net) (full disclosure: I wrote it). It should solve most of the problems you'll ever have with random numbers in Java.
Even, if you don't use it you should be able to get some ideas from the various [SeedGenerator](https://uncommons-maths.dev.java.net/n... | Um, that article says that 32-bit seeds are bad, but 64-bit seeds are good. System.currentTimeMillis() is a 64-bit seed. | What is a cross platform way to select a random seed in Java? | [
"",
"java",
"random",
"cross-platform",
"random-seed",
""
] |
What is the slickest way to initialize an array of dynamic size in C# that you know of?
This is the best I could come up with
```
private bool[] GetPageNumbersToLink(IPagedResult result)
{
if (result.TotalPages <= 9)
return new bool[result.TotalPages + 1].Select(b => true).ToArray();
...
``` | use [Enumerable.Repeat](http://msdn.microsoft.com/en-us/library/bb348899%28v=vs.110%29.aspx)
```
Enumerable.Repeat(true, result.TotalPages + 1).ToArray()
``` | If by 'slickest' you mean fastest, I'm afraid that **Enumerable.Repeat** may be 20x slower than a **for** loop.
See <http://dotnetperls.com/initialize-array>:
```
Initialize with for loop: 85 ms [much faster]
Initialize with Enumerable.Repeat: 1645 ms
```
So use Dotnetguy's SetAllValues() method. | C# Array initialization - with non-default value | [
"",
"c#",
".net",
""
] |
Is there any way in the SQL language or in MySQL (or other DBMA) to transfer a value from one cell to another? For example, say there is a table called user\_cars with the following structure:
```
|id| |user_name| |num_cars|
```
Bob has 5 cars, and John has 3 cars. Is there any way to in one query subtract 2 cars fro... | For Oracle you could do this. Don't know if there is an equivalent in mysql. Obviously this particular statement is very specific to the example you stated.
```
UPDATE user_cars
SET num_cars = num_cars +
CASE WHEN user_name='Bob' THEN -2
WHEN user_name='John' THEN +2
... | This will work, but it is not pleasant:
```
UPDATE USER_CARS UC
SET
NUM_CARS = NUM_CARS + CASE WHEN UC.USER_NAME = 'Bob'
THEN -2 --take from bob
WHEN UC.USER_NAME = 'John'
THEN 2 --give to John
ELSE ... | Any way to transfer value from one cell to another? | [
"",
"sql",
"mysql",
"database",
""
] |
What is the best way to determine available bandwidth in .NET?
We have users that access business applications from various remote access points, wired and wireless and at times the bandwidth can be very low based on where the user is. When the applications appear to be running slow, the issue could be due to low band... | Not beyond the obvious of downloading a file of a known size and timing how long it takes. the disadvantage of that is that you'd need to waste a lot of bandwidth to do it. Also, if you wanted to alert when throughput drops below a threshold, you'll have to run the test more-or-less continuously.
IMHO, I'd live with p... | There's no easy way to measure bandwidth without actually using it - which of course will starve the applications. A couple of points to bear in mind though:
1) Is it actually bandwidth that's the problem, or latency? You can measure latency in a less intrusive manner than bandwidth.
2) Are the applications all run f... | Determining available bandwidth | [
"",
"c#",
".net",
""
] |
I have a large int[] array and a much smaller int[] array. I want to fill up the large array with values from the small array, by repeat copying the small array into the large array until it is full (so that large[0] = large[13] = large[26] ... = small[0] etc.). I already have a simple method:
```
int iSource = 0;
for... | Interestingly the winning answer is the slowest with the provided source array!
The solution I was going to propose was
```
for (int i = 0; i < destArray.Length; i++)
{
destArray[i] = sourceArray[i%sourceArray.Length];
}
```
but when i tested the perf over 100000 iterations using the inputs in the answering ques... | Have your loop work using the `Array.Copy()` overload that lets you copy from one array into the a particular index in the destination array.
```
if (sourceArray.Length == 0) return; // don't get caught in infinite loop
int idx = 0;
while ((idx + sourceArray.Length) < destArray.Length) {
Array.Copy( sourceArray,... | What's the best way to copy/fill a large array with a smaller array in C#? | [
"",
"c#",
"arrays",
".net-2.0",
""
] |
Given a table structure like this:
```
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(32) NOT NULL,
`username` varchar(16) NOT NULL,
`password` char(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
);
```
Is there any use in using the LIMIT keyword... | I've always been told and read that you should include the `LIMIT` everytime you only want 1 result. This just tells the DB that it should stop so matter what. In your case, you're probably right it doesn't make a difference, but I think it's better just to always do than always deciding and leaving it out one time whe... | There is no need to use LIMIT.
However... If you have a HUGE HUGE HUGE cardinality on the table (and you're worried about speed), you might consider not using the special UNIQUE constraint in the DB and manage it from your application. Then, you can specify an INDEX on only the first few characters of your username fi... | Using LIMIT when searching by a unique field | [
"",
"sql",
"indexing",
""
] |
I have an SP that takes 10 seconds to run about 10 times (about a second every time it is ran). The platform is asp .net, and the server is SQL Server 2005. I have indexed the table (not on the PK also), and that is not the issue. Some caveats:
* usp\_SaveKeyword is not the issue. I commented out that entire SP and it... | Why are you using `top 1 @SearchID` instead of `max (SearchID)` or `where exists` in this query? `top` requires you to run the query and retrieve the first row from the result set. If the result set is large this could consume quite a lot of resources before you get out the final result set.
```
SELECT TOP 1 @SearchID... | Enable "Display Estimated Execution Plan" in SQL Management Studio - where does the execution plan show you spending the time? It'll guide you on the heuristics being used to optimize the query (or not in this case). Generally the "fatter" lines are the ones to focus on - they're ones generating large amounts of I/O.
... | Stored Procedure; Insert Slowness | [
"",
"sql",
"performance",
"stored-procedures",
""
] |
When a Java VM crashes with an EXCEPTION\_ACCESS\_VIOLATION and produces an hs\_err\_pidXXX.log file, what does that indicate? The error itself is basically a null pointer exception. Is it always caused by a bug in the JVM, or are there other causes like malfunctioning hardware or software conflicts?
Edit: there is a ... | Most of the times this is a bug in the VM.
But it can be caused by any native code (e.g. JNI calls).
The hs\_err\_pidXXX.log file should contain some information about where the problem happened.
You can also check the "Heap" section inside the file. Many of the VM bugs are caused by the garbage collection (expeciall... | Answer found!
I had the same error and noticed that others who provided the contents of the pid log file were running 64 bit Windows. Just like me. At the end log file, it included the PATH statement. There I could see C:\Windows\SysWOW64 was incorrectly listed ahead of: %SystemRoot%\system32. Once I corrected it, the... | Possible causes of Java VM EXCEPTION_ACCESS_VIOLATION? | [
"",
"java",
"null",
"jvm",
"crash",
"swt",
""
] |
Assume I have a class foo, and wish to use a std::map to store some boost::shared\_ptrs, e.g.:
```
class foo;
typedef boost::shared_ptr<foo> foo_sp;
typeded std::map<int, foo_sp> foo_sp_map;
foo_sp_map m;
```
If I add a new foo\_sp to the map but the key used already exists, will the existing entry be deleted? For ... | First off, your question title says boost::auto\_ptr, but you actually mean boost::shared\_ptr
And yes, the original pointer will be freed (if there are no further shared references to it). | It depends on what happens in your ... section
Your container class contains *copies* of instances of foo\_sp, when you execute `m[0] = p2;` the copy of `p` that was originally in that place goes out of scope. At that time it will be deleted *if there are no other foo\_sp refers to it*.
If the copy that was declared ... | boost::shared_ptr standard container | [
"",
"c++",
"smart-pointers",
"std",
"stdmap",
""
] |
I'm trying to create a c++ library for use on windows/MSVC.
My problem is that it seems that in order to link properly, I need to distribute a bunch of different versions, linked against different versions of MSVC's c++ runtimes - single and multi-threaded, debug and release, different compiler versions, various other... | You want static linking, as a general answer.
Quick note on Chris' answer (don't want to de-boost cause it's mostly good, but...):
DO NOT link to msvcrt.dll (the unversioned one); this is the OS-specific version DLL, and if you link to it, your app probably will not work on other versions of Windows. You should alway... | Link statically to C++ runtime library:
1. Open project properties.
2. Go to Configuration Properties | C/C++ | Code Generation section.
3. Set Runtime Library to Multi-threaded (/MT). | Building windows c++ libraries without a runtime? | [
"",
"c++",
"visual-c++",
"runtime",
""
] |
I need to fire an event when the mouse is above a PictureBox with the mouse button already clicked and held down.
Problems:
The MouseDown and MouseEnter event handlers do not work together very well.
For instance once a mouse button is clicked and held down, C# will fire the MouseDown event handler, but when the cur... | When the mouse is pressed down most controls will then *Control.Capture* the mouse input. This means that all *MouseMove* events are sent to the original control that captured rather than the control the mouse happens to be over. This continues until the mouse loses capture which typically happens on the mouse up.
If ... | **Mouse events**
Use the MouseDown event to just detect a down press of a mouse button and set this.Capture to true so that you then get other mouse events, even when the mouse leaves the control (i.e. you won't get a MouseLeave event because you captured the mouse). Release capture by setting this.Capture to false wh... | How can I detect a held down mouse button over a PictureBox? | [
"",
"c#",
"winforms",
"mouse",
"picturebox",
""
] |
I have an array of items that are time sensitive. After an amount of time, the last item needs to fall off and a new item is put at the beginning.
What is the best way to do this? | I would suggest using a queue, just a special instance of an array or list. When your timed event occurs, pop the last item from the queue, and then push your new item on. | Probably the easiest way to do this with an array is to use a circular index. Rather than always looking at array[n], you would reference array[cIndex] (where cIndex referrs to the item in the array being indexed (cIndex is incremented based on the arraySize (cIndex % arraySize)).
When you choose to drop the oldest it... | How to shift items in an array? | [
"",
"c#",
"data-structures",
""
] |
Is there a way to identify unused attributes/methods in Visual C++ 2008 Professional? If it's not possible by default, recommendations of 3rd-party tools are also much appreciated.
Thanks,
Florian
**Edit:** nDepend only works for .NET assemblies. I'm looking for something that can be used with native C++ applicatio... | Try [PC-Lint](http://www.gimpel.com/). It's pretty good at finding redundant code.
I haven't tried version 9 yet. Version 8 does take some time to configure.
Try the online interactive demo. | I have not personally used their productivity tools (I use their windows control suit), but it looks like DevExpress has a C++ refactor'er called [Refactor! for C++](http://www.devexpress.com/Products/Visual_Studio_Add-in/RefactorCPP/). I didn't immediately spot the features that you are looking for, but maybe they hav... | How to find unused attributes/methods in Visual C++ 2008 | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"visual-c++",
"static-analysis",
""
] |
What features of C++ should be avoided in embedded systems?
Please classify the answer by reason such as:
* memory usage
* code size
* speed
* portability
EDIT: Lets' use an ARM7TDMI with 64k ram as a target to control the scope of the answers. | **RTTI and Exception Handling:**
* Increases code-size
* Decreases performance
* Can often be replaced by cheaper mechanisms or a better software-design.
**Templates:**
* be careful with them if code-size is an issue. If your target CPU has no or only a very tiny ínstruction cache it may reduce the performance as we... | Choosing to avoid certain features should always be driven by quantitative analysis of the behavior of *your* software, on *your* hardware, with *your* chosen toolchain, under the constraints *your* domain entails. There are a lot of conventional wisdom "don'ts" in C++ development which are based on superstition and an... | C++ usage in embedded systems | [
"",
"c++",
"embedded",
""
] |
This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.
In Python, it's worth mentioning that the problem is somewhat related to [how-do-i-use-pythons-itertoolsgroupby](https://stackoverflow.com/questions/773/... | Have you tried sorting the list first? The algorithm you proposed should work, albeit with lots of database hits.
```
import itertools
cars = [
{'car': 'X2', 'mods': [1,2]},
{'car': 'Y2', 'mods': [2]},
{'car': 'W2', 'mods': [1]},
{'car': 'X1', 'mods': [1,2]},
{'car': 'W1', 'mods': [1]},
{'car'... | check [regroup](http://docs.djangoproject.com/en/dev//ref/templates/builtins/#regroup). it's only for templates, but i guess this kind of classification belongs to the presentation layer anyway. | Django/Python - Grouping objects by common set from a many-to-many relationships | [
"",
"python",
"django",
"algorithm",
"puzzle",
""
] |
Been using **PHP/MySQL** for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using `mysql_fetch_object()` vs `mysql_fetch_assoc()` / `mysql_fetch_array()`. | Performance-wise it doesn't matter what you use. The difference is that mysql\_fetch\_object returns object:
```
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
```
mysql\_fetch\_assoc() returns associative array:
```
while ($row = mysql_fetch_assoc($result)) {
ech... | `mysql_fetch_array` makes your code difficult to read = a maintenace nightmare. You can't see at a glance what data your object is dealing with. It slightly faster, but if that is important to you you are processing so much data that PHP is probably not the right way to go.
`mysql_fetch_object` has some drawbacks, esp... | Mysql results in PHP - arrays or objects? | [
"",
"php",
"mysql",
"arrays",
"object",
""
] |
Is it possible to do something like this?
```
var pattern = /some regex segment/ + /* comment here */
/another segment/;
```
Or do I have to use new `RegExp()` syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise. | Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitrary string manipulation before it becomes a regular expression object:
```
var segment_part = "some bit of the regexp";
var pattern = new RegExp("some regex segment" + /*comment here */
... | Just randomly concatenating regular expressions **objects** can have some adverse side effects. Use the [RegExp.source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source) instead:
```
var r1 = /abc/g;
var r2 = /def/;
var r3 = new RegExp(r1.source + r2.source,
... | How can I concatenate regex literals in JavaScript? | [
"",
"javascript",
"regex",
"syntax",
""
] |
I have 7-8 xml files. Each one is approximately 50 MB in size. What is the best way to merge files programmatically in C# without getting System.OutOfMemory Exception? So far I have tried reading each file in a StringBuilder and than putting it in an array of string builder but I still get system.outofmemoery exception... | Personally, when I *have* to deal with XML files (forced by threat of physical violence usually), I do this:
1. Load each file into a .NET DataSet via DataSet.ReadXML()
2. Combine the information (via DataSet queries).
3. Write out the combined DataSet to XML via DataSet.WriteXML()
Then I aggressively delete the orgi... | The thing about stringbuilder is you're still trying to keep the entire contents in memory. You want to only keep a small portion in memory at a time, and that means using filestreams. Don't read an entire file into memory, open a stream on it and keep reading from the stream.
The problem with xml is that you can't ju... | Merging big files in C# | [
"",
"c#",
""
] |
There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the `as` operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException? | Here's an implementation of as, as suggested by @Omar Kooheji:
```
public static <T> T as(Class<T> clazz, Object o){
if(clazz.isInstance(o)){
return clazz.cast(o);
}
return null;
}
as(A.class, new Object()) --> null
as(B.class, new B()) --> B
``` | I'd think you'd have to roll your own:
```
return (x instanceof Foo) ? (Foo) x : null;
```
EDIT: If you don't want your client code to deal with nulls, then you can introduce a [Null Object](http://en.wikipedia.org/wiki/Null_Object_pattern)
```
interface Foo {
public void doBar();
}
class NullFoo implements Foo ... | How to emulate C# as-operator in Java | [
"",
"java",
"casting",
""
] |
In terms of quick dynamically typed languages, I'm really starting to like Javascript, as I use it a lot for web projects, especially because it uses the same syntax as Actionscript (flash).
It would be an ideal language for shell scripting, making it easier to move code from the front and back end of a site, and less... | Of course, in Windows, the JavaScript interpreter is shipped with the OS.
Just run `cscript` or `wscript` against any .js file. | I personally use SpiderMonkey, but here's an extensive list of [ECMAScript shells](http://www.discerning.com/burstproject.org/build/doc/shells.html)
Example spidermonkey install and use on Ubuntu:
```
$ sudo apt-get install spidermonkey
$ js myfile.js
output
$ js
js> var f = function(){};
js> f();
``` | Javascript interpreter to replace Python | [
"",
"javascript",
"shell",
"scripting",
""
] |
For example, imagine a simple mutator that takes a single boolean parameter:
```
void SetValue(const bool b) { my_val_ = b; }
```
Does that `const` actually have any impact? Personally I opt to use it extensively, including parameters, but in this case I wonder if it makes any difference.
I was also surprised to lea... | The reason is that `const` for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though.
I personally tend to not use `const` except for reference and pointer paramete... | > *`const` is pointless when the argument is passed by value since you will
> not be modifying the caller's object.*
Wrong.
It's about self-documenting your code and your assumptions.
If your code has many people working on it and your functions are non-trivial then you should mark `const` any and everything that yo... | Does using const on function parameters have any effect? Why does it not affect the function signature? | [
"",
"c++",
"parameters",
"constants",
"function-declaration",
"const-correctness",
""
] |
Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own? | You could use a decorator function such as:
```
class cache(object):
def __init__(self, fun):
self.fun = fun
self.cache = {}
def __call__(self, *args, **kwargs):
key = str(args) + str(kwargs)
try:
return self.cache[key]
except KeyError:
self.cac... | If you don't mind working at a slightly lower level, httplib2 (<https://github.com/httplib2/httplib2>) is an excellent HTTP library that includes caching functionality. | Caching in urllib2? | [
"",
"python",
"caching",
"urllib2",
""
] |
Let's say I have to implement a piece of T-SQL code that must return a table as result. I can implement a table-valued function or else a stored procedure that returns a set of rows. What should I use?
In short, what I want to know is:
**Which are the main differences between functions and stored procedures?** What c... | If you're likely to want to combine the result of this piece of code with other tables, then obviously a table-valued function will allow you to compose the results in a single SELECT statement.
Generally, there's a hierarchy (View < TV Function < Stored Proc). You can do more in each one, but the ability to compose t... | Functions must be deterministic, and cannot be used to make changes to the database, whereas stored procedures allow you to do inserts and updates, etc.
You should limit your use of functions, since they pose a huge scalability problem for big, complex queries. They become sort of a "black box" for the query optimizer... | Functions vs Stored Procedures | [
"",
"sql",
"sql-server",
"database",
"function",
"stored-procedures",
""
] |
This
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%';
```
is slower than this
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value';
```
but what about this?
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value';
```
My testing indicates the second and third examples are exactly... | There is a clear difference when you use bind variables, which you should be using in Oracle for anything other than data warehousing or other bulk data operations.
Take the case of:
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE :b1
```
Oracle cannot know that the value of :b1 is '%some\_value%', or 'some\_valu... | Check out the [EXPLAIN PLAN](http://www.adp-gmbh.ch/ora/explainplan.html) for both. They generate the same execution plan, so to the database, they're the same thing.
You would use = to test for equality, not similarity. If you're controlling the comparison value as well, then it doesn't make much of a difference. If ... | Any performance impact in Oracle for using LIKE 'string' vs = 'string'? | [
"",
"sql",
"performance",
"oracle",
""
] |
This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern ... | The rematcher function seems to do what you want:
```
def rematcher(re_str, iterable):
matcher= re.compile(re_str)
in_match= 0
for item in iterable:
if matcher.match(item):
if in_match == 0:
yield item
in_match+= 1
else:
if in_match > 1:
... | Updated your code to be a bit more effective
```
#!/usr/bin/env python
#
import re
import types
def remove_repeats (l_string, l_regex):
"""Take a string, remove similar lines and replace with a summary message.
l_regex accepts strings/patterns or tuples of strings/patterns.
"""
# Convert string/pattern... | What is best way to remove duplicate lines matching regex from string using Python? | [
"",
"python",
"regex",
""
] |
I have an application - more like a utility - that sits in a corner and updates two different databases periodically.
It is a little standalone app that has been built with a Spring Application Context. The context has two Hibernate Session Factories configured in it, in turn using Commons DBCP data sources configured... | The best way to distribute transactions over more than one database is: Don't.
Some people will point you to XA but XA (or Two Phase Commit) is a lie (or marketese).
Imagine: After the first phase have told the XA manager that it can send the final commit, the network connection to one of the databases fails. Now wha... | Setup a transaction manager in your context. Spring docs have examples, and it is very simple. Then when you want to execute a transaction:
```
try {
TransactionTemplate tt = new TransactionTemplate(txManager);
tt.execute(new TransactionCallbackWithoutResult(){
protected void doInTransactionWithoutResult... | What is the 'best' way to do distributed transactions across multiple databases using Spring and Hibernate | [
"",
"java",
"hibernate",
"spring",
"transactions",
"xa",
""
] |
Java supplies standard User Interface guidelines for applications built using Java Swing. The basic guidelines are good, but I really feel the look and feel is really boring and outdated.
Is anyone aware of a publicly available Java User Interface Guide that has better look & feel guidelines than the Sun provided guid... | Along the line of Chii's answer, I would recommend taking a look at the [Windows Vista User Experience Guidelines](http://msdn.microsoft.com/en-us/library/aa511258.aspx "Windows Vista User Experience Guidelines") for general tips on making user interfaces.
Although the name ("Windows Vista User Experience Guidelines")... | the apple developer guide has a human computer interface guide - <http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGIntro/chapter_1_section_1.html#//apple_ref/doc/uid/TP30000894-TP6> .
Even though its targeted at the mac platform, you could learn something from it - its the reaso... | Java User Interface Specification | [
"",
"java",
"swing",
"user-interface",
""
] |
Is it possible to sign only part of an applet? Ie, have an applet that pops up no security warnings about being signed, but if some particular function is used (that requires privileges) then use the signed jar?
From what I can tell, some (perhaps most) browsers will pop up the warning for a signed applet even if you ... | Try splitting your code into an unsigned jar and a signed jar. | In theory you can (signed + unsigned jar), but in practice it will result that your code will be handled as unsigned. The access decision should be made from the thread, not the immediate caller. If the thread contains in the stack a call made from an object from unsigned code, the whole call should be treated as unsig... | Java Applet - Partially Signed? | [
"",
"java",
"security",
"applet",
"signed-applet",
""
] |
I learned to use "exists" instead of "in".
BAD
```
select * from table where nameid in (
select nameid from othertable where otherdesc = 'SomeDesc' )
```
GOOD
```
select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
```
1. The expl... | It's specific to each DBMS and depends on the query optimizer. Some optimizers detect IN clause and translate it.
In all DBMSes I tested, alias is only valid inside the ( )
BTW, you can rewrite the query as:
```
select t.*
from table t
join othertable o on t.nameid = o.nameid
and o.otherdesc in ('SomeDesc','S... | You are treading into complicated territory, known as 'correlated sub-queries'. Since we don't have detailed information about your tables and the key structures, some of the answers can only be 'maybe'.
In your initial IN query, the notation would be valid whether or not OtherTable contains a column NameID (and, inde... | SQL - table alias scope | [
"",
"sql",
"scope",
"table-alias",
""
] |
Why am I getting a textbox that returns undefined list of variables?
When I run this code:
```
var query = (from tisa in db.TA_Info_Step_Archives
where tisa.ta_Serial.ToString().StartsWith(prefixText)
select tisa.TA_Serial.ToString()).Distinct().Take(Convert.ToInt32(count));
return ... | updated my ajax kit to version 1.0.10920 then changed my code to the following:
```
foreach (DataRow dr in dt.Rows)
{
items.SetValue("\"" + dr["somenumber"].ToString() + "\"", i);
i++;
}
```
Late friday nights with .net is not fun. I have no life. :-P | I tried the code below and it worked for me:
```
items.SetValue("'"+dr["somenumber"]+"'", i);
``` | Why is my ASP.NET AutoCompleteExtender returning undefined? | [
"",
"c#",
"linq",
"web-services",
"autocomplete",
""
] |
I'd like my .exe to have access to a resource string with my svn version. I can type this in by hand, but I'd prefer an automated way to embed this at compile time. Is there any such capability in Visual Studio 2008? | I wanted a similar availability and found $Rev$ to be insufficient because it was only updated for a file if that file's revision was changed (which meant it would have to be edited and committed very time: not something I wanted to do.) Instead, I wanted something that was based on the repository's revision number.
F... | How about using [SubWCRev](http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-subwcrev.html) the command line tool that ships with [TortoiseSVN](http://tortoisesvn.net/). You create a template file with tokens in it like $WCREV$ $WCDATE$ etc. Then have a pre-build step that run SubWCRev on your template file to cr... | Embedding SVN Revision number at compile time in a Windows app | [
"",
"c++",
"windows",
"visual-studio",
"svn",
""
] |
I was writing a (seemingly) straight-forward SQL snippet that drops a column after it makes sure the column exists.
The problem: if the column does NOT exist, the code *inside* the IF clause complains that it can't find the column! Well, *doh*, that's why it's inside the IF clause!
So my question is, why does a pie... | ```
IF exists (select * from syscolumns
WHERE id=object_id('Table_MD') and name='timeout')
BEGIN
DECLARE @SQL nvarchar(1000)
SET @SQL = N'ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout'
EXEC sp_executesql @SQL
END
GO
```
Reason:
When Sql server compiles the code, they check it for used objects ( if t... | By the way, there is a similar issue in Oracle, and a similar workaround using the "execute immediate" clause. | Why does a T-SQL block give an error even if it shouldn't even be executed? | [
"",
"sql",
"t-sql",
""
] |
IIS is literally sending `<?php ... ?>` code to the browser rather then executing it.
But, only for the root `http://domain.com/index.php` file.
All other .php files in that folder and index.php files in subfolders execute as expected.
How can I get my root index.php code to execute?
---
Update: "index.php" is a D... | * [IIS 5.1 does not run PHP properly under root directory, but fine in all other folders](http://forums.devshed.com/iis-97/iis-5-1-does-not-run-php-properly-under-root-163070.html)
* [Running a WordPress blog in site root using IIS](http://www.simmonsconsulting.com/2008/04/21/running-a-wordpress-blog-in-site-root-using... | It seems you have properly configured your handlers.
If you're using `<? ... ?>` make sure you have
`short_open_tag = On`
in your php.ini. | Why isn't IIS executing the PHP code of my site root index.php file? | [
"",
"php",
"iis",
""
] |
I'm trying to write a resolution selection dialog that pops up when a program first starts up. To prevent boring the user, I want to implement the fairly standard feature that you can turn off that dialog with a checkbox, but get it back by holding down the alt key at startup.
Unfortunately, there is no obvious way to... | ```
public class LockingKeyDemo {
static Toolkit kit = Toolkit.getDefaultToolkit();
public static void main(String[] args) {
System.out.println("caps lock2 = "
+ kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
}
}
``` | ```
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class LockingKeyDemo {
static Toolkit kit = Toolkit.getDefaultToolkit();
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.addWindowListener(new WindowAdapter() {
public voi... | How to check for key being held down on startup in Java | [
"",
"java",
"swing",
"keyboard",
"key",
"awt",
""
] |
So C# now allows you to use `default(Foo)` to get a recognized "not filled in yet"/empty instance of a class -- I'm not sure if it is exactly the same as `new Foo()` or not. Many library classes also implement a `Foo.Empty` property, which returns a similar instance. And of course any reference type can point to `null`... | `default(Foo)` will return null when `Foo` is a class type, zero where `Foo` is a value type (such as int), and an instance of `Foo` with all fields initialized to *their* respective `default()` values where `Foo` is a struct. It was added to the language so that generics could support both value and reference types - ... | `default(Foo)` works for both value types and reference types. `New Foo(), null` and `Foo.Empty()` do not. This makes it a good choice for use with generic types, for example, when you may not know which you're dealing with. But in most reference-type cases, `null` is probably good enough. | Should I use default(Foo), Foo.Empty, or null? | [
"",
"c#",
"constructor",
"conventions",
""
] |
Is there a library or acceptable method for sanitizing the input to an html page?
In this case I have a form with just a name, phone number, and email address.
Code must be C#.
For example:
`"<script src='bobs.js'>John Doe</script>"` should become `"John Doe"` | We are using the [HtmlSanitizer](https://github.com/mganss/HtmlSanitizer) .Net library, which:
* Is open-source (MIT) - [GitHub link](https://github.com/mganss/HtmlSanitizer)
* Is fully customizable, e.g. configure which elements should be removed. [see wiki](https://github.com/mganss/HtmlSanitizer/wiki)
* [Is activel... | Based on the comment you made to this answer, you might find some useful info in this question:
<https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site>
Here's a parameterized query example. Instead of this:
```
string sql = "UPDATE UserRecord SET FirstName='" + txt... | How to use C# to sanitize input on an html page? | [
"",
"c#",
"html-sanitizing",
"antixsslibrary",
""
] |
Alright. So I have a very large amount of binary data (let's say, 10GB) distributed over a bunch of files (let's say, 5000) of varying lengths.
I am writing a Java application to process this data, and I wish to institute a good design for the data access. Typically what will happen is such:
* One way or another, all... | Use Java NIO and MappedByteBuffers, and treat your files as a list of byte arrays. Then, let the OS worry about the details of caching, read, flushing etc. | @Will
Pretty good results. Reading a large binary file quick comparison:
* Test 1 - Basic sequential read with RandomAccessFile.
**2656 ms**
* Test 2 - Basic sequential read with buffering.
**47 ms**
* Test 3 - Basic sequential read with MappedByteBuffers and further frame buffering optimization.
**16 ms** | Java: Advice on handling large data volumes. (Part Deux) | [
"",
"java",
"performance",
"data-access",
""
] |
When creating a class library in C++, you can choose between dynamic (`.dll`, `.so`) and static (`.lib`, `.a`) libraries. What is the difference between them and when is it appropriate to use which? | Static libraries increase the size of the code in your binary. They're always loaded and whatever version of the code you compiled with is the version of the code that will run.
Dynamic libraries are stored and versioned separately. It's possible for a version of the dynamic library to be loaded that wasn't the origin... | Others have adequately explained what a static library is, but I'd like to point out some of the caveats of using static libraries, at least on Windows:
* **Singletons:** If something needs to be global/static and unique, be very careful about putting it in a static library. If multiple DLLs are linked against that st... | When to use dynamic vs. static libraries | [
"",
"c++",
"dll",
"shared-libraries",
"static-linking",
"dynamic-linking",
""
] |
Is there a built-in mechanism in .NET to match patterns other than [regular expressions](https://en.wikipedia.org/wiki/Regular_expression) (regex)? I'd like to match using Unix-style ([glob](https://en.wikipedia.org/wiki/Glob_(programming))) wildcards (\* = any number of any character).
I'd like to use this for a end-... | I found the actual code for you:
```
Regex.Escape( wildcardExpression ).Replace( @"\*", ".*" ).Replace( @"\?", "." );
``` | I like my code a little more semantic, so I wrote this extension method:
```
using System.Text.RegularExpressions;
namespace Whatever
{
public static class StringExtensions
{
/// <summary>
/// Compares the string against a given pattern.
/// </summary>
/// <param name="str">The... | Glob pattern matching in .NET | [
"",
"c#",
".net",
"glob",
""
] |
My .NET application fails when run from a network drive even when the very same executable runs perfectly fine from a local hard drive?
I tried checking for "Full trust" like so:
```
try
{
// Demand full trust permissions
PermissionSet fullTrust = new PermissionSet( PermissionState.Unrestricted );
fullTru... | It indeed has to do with the fact the apps on a network location are less trusted then on your local hdd (due to the default policy of the .NET framework).
If I'm not mistaken Microsoft finally corrected this annoyance in .NET 3.5 SP1 (after a lot of developers complaining).
I google'd it: [.NET Framework 3.5 SP1 All... | Did you try Using [CasPol to Fully Trust a Share](http://blogs.msdn.com/shawnfa/archive/2004/12/30/344554.aspx)? | Why does my .NET application crash when run from a network drive? | [
"",
"c#",
".net",
"networking",
"securityexception",
"permissionset",
""
] |
I often use the `execv()` function in C++, but if some of the arguments are in C++ strings, it annoys me that I cannot do this:
```
const char *args[4];
args[0] = "/usr/bin/whatever";
args[1] = filename.c_str();
args[2] = someparameter.c_str();
args[3] = 0;
execv(args[0], args);
```
This doesn't compile because `ex... | The Open Group Base Specifications explains why this is: for compatibility with existing C code. Neither the pointers nor the string contents themselves are intended to be changed, though. Thus, in this case, you can get away with `const_cast`-ing the result of `c_str()`.
[Quote:](http://pubs.opengroup.org/onlinepubs/... | const is a C++ thing - execv has taken char \* arguments since before C++ existed.
You can use const\_cast instead of copying, because execv doesn't actually modify its arguments. You might consider writing a wrapper to save yourself the typing.
Actually, a bigger problem with your code is that you declared an array ... | execv() and const-ness | [
"",
"c++",
"unix",
""
] |
What I have now (which successfully loads the plug-in) is this:
```
Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
```
This only works for a class that has a constructor with no arguments. How do I pass in an argument to a constructor? | You cannot. Instead use [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx) as shown in the example below (note that the Client namespace is in one DLL and the Host in another. Both must be found in the same directory for code to work.)
However, if you want to create a truly pluggable int... | call
```
public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
```
instead.
[MSDN Docs](http://msdn.microsoft.com/en-us/library/ck6xe688.aspx)
EDIT: If you are going to vote this down, please give ins... | How can I pass an argument to a C# plug-in being loaded through Assembly.CreateInstance? | [
"",
"c#",
"assemblies",
"arguments",
"createinstance",
""
] |
I need to do a lot of searches of certain patterns in source files while the user is changing them, so I need to do regexp matching that is efficient in time and memory. The pattern repeats itself so should be compiled once, but I need to be able to retrieve subparts (rather than just confirm a match)
I'm considering ... | I am not sure there is a huge performance gap in term of the different regexp java engines.
But there sure is a performance issue when constructing a regexp (and that is, if the data is large enough, as [noted by Jeff Atwood](http://blog.codinghorror.com/regex-performance/))
The only thing you should avoid is [catast... | As VonC says, you need to know your regexps. It doesn't hurt to compile the Regexes beforehand OTHERWISE, the cost of compiling regex each time can hurt the performance badly.
For some categories, there are alternate libraries : <http://jint.sourceforge.net/jint.html> which might have better performance. Then again, i... | Is java.util.regexp efficient enough? | [
"",
"java",
"regex",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.