Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a data acquisition program written in C++ (Visual Studio 6.0). Some clients would like to control the software from their own custom software or LabView. I would like to come up with a simple API with a dll I can distribute to them and would like some tips on how to get started. This is going to be VERY basic, m... | You are on the right track with a DLL. The real trick, it sounds like, will be deciding what sort of inter-process communication (IPC) you want to use. Options are: sockets, pipes, shared memory, synchronization objects (events, etc.), files, registry, etc.
Once you decide that, then implement a listener within your e... | Things that start simple like this have a habit of growing over time, so you may be better off doing a little more work up front and using a technique that will grow with you.
Implementing a COM interface to your program would give the clients are lot of freedom in how the interface with it, and you wouldn't have to w... | How to add a simple API to my C++ application for access by LabView? | [
"",
"c++",
"windows",
"api",
"labview",
""
] |
Is it possible to have a post-mortem ( or post-exception ) debugging session in Java ? What would the workarounds be ( if there isn't a solution for this already ) ? | You can attach the debugger to a java process and set a breakpoint when a specific
exception is received. Is this what you need?
From
<http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/jdb.html>
> When an exception occurs for which
> there isn't a catch statement anywhere
> up a Java program's stack, the Java
> ru... | As far as I know, you'd have to wait for Java 7 for an official API - see <http://tech.puredanger.com/java7#jsr326>.
In the meantime, you could substitute Exception (replace base class, inject code via instrumentation, etc) to keep your data. Please note though the ClassLoader throws and catches ClassNotFoundException... | Java post-mortem debugging? | [
"",
"java",
"debugging",
"exception",
""
] |
I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any information about a (feature) comparison.
I think the most interesting frameworks are CppUnit, Boost and the new Google t... | [See this question](https://stackoverflow.com/questions/91683/how-do-you-implement-unit-testing-in-large-scale-c-projects) for some discussion.
They recommend the articles:
[Exploring the C++ Unit Testing Framework Jungle](http://gamesfromwithin.com/?p=29), By Noel Llopis.
And the more recent: [C++ Test Unit Framework... | A new player is [Google Test](http://code.google.com/p/googletest/) (also known as *Google C++ Testing Framework*) which is pretty nice though.
```
#include <gtest/gtest.h>
TEST(MyTestSuitName, MyTestCaseName) {
int actual = 1;
EXPECT_GT(actual, 0);
EXPECT_EQ(1, actual) << "Should be equal to one";
}
```
... | Comparison of C++ unit test frameworks | [
"",
"c++",
"unit-testing",
"cppunit",
"googletest",
"boost-test",
""
] |
We use a base entity with properties such as version (datetime needed for NHibernate) and guid (as key).
It also has an Id (int) field with two functions. Firstly to relate to legacy application key if there is one. Secondly as a shorthand code: for instance files are sometimes created based on these which would look ... | Well, int64 uses 8 byte of memory storage, while int uses 4 byte... however, you pointed out most of the disadvantages already. Of course calculations performed will also be slower on many systems (a 64 bit system running in 64 bit mode can perform operations on 64 bit as fast as on 32 bit, but a 32 bit system needs to... | If your app is running on a 64 bit CPU then probably not much difference at all.
On a 32 bit CPU, a 64 bit integer will be more processor intensive to perfom calculations with.
There is also the obvious memory use. | Downsides to using Int64 universally instead of int (C#) | [
"",
"c#",
".net-2.0",
""
] |
I have two STL containers that I want to merge, removing any elements that appear more than once. For example:
```
typedef std::list<int> container;
container c1;
container c2;
c1.push_back(1);
c1.push_back(2);
c1.push_back(3);
c2.push_back(2);
c2.push_back(3);
c2.push_back(4);
container c3 = unique_merge(c1, c2);
... | For an unordered lists, your set trick is probably one of the best. It each insert should be O(log n), with N inserts required, and traversing will be O(n), giving you O(N\*log n).
The other option is to run std::sort on each list individually and then walk through them in parallel using [std::set\_union](http://msdn.m... | You are going to need to either sort (either explicitly, or implicitly via a sorted container like set).
There is a common idiom using std::sort/std::unique/std::erase to get unique elements in a container.
So create a container with the contents of c1, append the contents of c2, then sort, move unique elements to th... | Best way to merge multiple STL containers, removing duplicate elements? | [
"",
"c++",
"stl",
""
] |
I'm working on an app which scrapes data from a website and I was wondering how I should go about getting the data. Specifically I need data contained in a number of div tags which use a specific CSS class - Currently (for testing purposes) I'm just checking for
```
div class = "classname"
```
in each line of HTML - ... | Several years ago I used JTidy for the same purpose:
<http://jtidy.sourceforge.net/>
"JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML. In addition, JTidy provides a DOM interface to the documen... | Another library that might be useful for HTML processing is jsoup.
Jsoup tries to clean malformed HTML and allows html parsing in Java using jQuery like tag selector syntax.
<http://jsoup.org/> | Java HTML Parsing | [
"",
"java",
"html",
"parsing",
"web-scraping",
""
] |
I have two forms, form A and form B. These forms must differ in appearance, but they share a lot of logic. The problem is that this logic is tied to the appearance (validation on button click, events being fired, etc.). For example, I have a name field, and when the save button is pressed, I need to fire an event which... | You could create an object with data that is represented in both forms, and put validation logic in that object. The presentation layer should populate that object with the entered data, ask the object to validate itself, and then handle validation errors in a form-specific way. | If the common logic is UI related you need to create your own custom form class (that inherit from Form class) with the desired logic. then all you need to do is inherit that class in your forms.
If the common logic is less UI related create an internal class that encapsulates the common logic and call it from both fo... | How to avoid duplicating logic on two similar WinForms? | [
"",
"c#",
".net",
"coding-style",
""
] |
I've been looking around for a good MVC framework for Python using PyGTK. I've looked at [Kiwi](http://www.async.com.br/projects/kiwi/) but found it a bit lacking, especially with using the Gazpacho Glade-replacement.
Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a w... | In defense of Kiwi:
* Kiwi works fine with Glade3 instead of Gazpacho. (who forced you to use Gazpacho?)
* Kiwi is my first dependency for *any* PyGTK application commercial or open source.
* Kiwi is very actively maintained.
I have generally got to a stage where I think its irresponsible to not use Kiwi in a PyGTK a... | There's [Dabo](https://stackoverflow.com/questions/310856/python-gtk-mvc), made by some guys moving from FoxPro. It might work for you if you're writing a data driven business app.
Beyond that, I haven't found anything that you haven't.
> GUI stuff is *supposed* to be hard. It builds character.
([Attributed](http://... | Python GTK MVC: Kiwi? | [
"",
"python",
"model-view-controller",
"gtk",
""
] |
I cannot figure out a way to disable a container AND its children in Swing. Is Swing really missing this basic feature?
If I do setEnabled(false) on a container, its children are still enabled.
My GUI structure is pretty complex, and doing a traversion of all elements below the container is not an option. Neither is ... | To add to [mmyers's answer](https://stackoverflow.com/questions/305527#305551), disabling children is not an easy task (see this [thread](http://forums.java.net/jive/thread.jspa?threadID=13758))
> The problem is near-to unsolvable in the general case. That's why it is not part of core Swing.
>
> Technically, the disab... | [JXLayer](https://jxlayer.dev.java.net/) might be what you're looking for, according to [this post](http://weblogs.java.net/blog/alexfromsun/archive/2007/06/_enablingdisabl_1.html):
> Wrap your container with the JXLayer and call `JXLayer.setLocked(true)` after that - all components inside will be disabled
[alt text ... | How to disable a container and its children in Swing | [
"",
"java",
"swing",
""
] |
```
// A Mutex allows threads mutually exclusive access to a resource.
//-----------------------------------------------------------------------
class Mutex
{
private:
CRITICAL_SECTION m_mutex;
public:
Mutex() { InitializeCriticalSection(&m_mutex); }
~Mutex() { DeleteCriticalSection(&m_mutex); }
... | I'll bet you can fake out the snitch with ::memset ( & m\_mutex, 0, sizeof ( m\_mutex ) ); before the call to init it. | CodeSnitch is apparently not smart enough to know that InitializeCriticalSection() *expects* to be working on a structure containing an uninitialized pointer.
Think of it from CodeSnitch's point of view. What's the difference between what you're doing, and this:
```
struct Customer {
char * name;
};
extern void ... | What is wrong with this tiny piece of mutex code? | [
"",
"c++",
"mutex",
"critical-section",
""
] |
I am taking my first foray into PHP programming and need to configure the environment for the first time. Can I use PHP with the built in VS web server or do I need to (and I hope not) use IIS locally?
In addition, any pointers on pitfalls to be avoided would be great.
Many thanks.
**Update:** I should have made the... | For what you're doing, you really shouldn't be using the PHP scripts from that example.
Instead, you should be pulling data from the Form variables posted to the server on your own self-made pages. I don't know the "proper" way to do this using the MVC framework. With the ASP Forms framework, you'd do something like t... | PHP on IIS is a bit of a pitfall in itself, you can find some reference here: [What do I need to run PHP applications on IIS?](https://stackoverflow.com/questions/10515/php-on-iis)
I would sugest using WAMP from here: <http://www.apachefriends.org/en/xampp-windows.html> | What's the best way to develop local using PHP and Visual Studio? | [
"",
"php",
"asp.net-mvc",
"visual-studio",
""
] |
Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'?
Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part. | jQuery only accepts a string as an argument for the `val` parameter of the `html()` method. If you pass a number like you are it will call the `html()` method override that sets the contents of the element but the value of the argument will end up being null or an empty string.
Try this:
```
$("p").html((0).toString(... | Try using `text()` instead `html()`. | Weird Behaviour in jQuery's html method | [
"",
"javascript",
"jquery",
""
] |
What's the better way to insert cell comments in excel 2007 files programmatically using c# and .net 3.5? | I just did exactly that but with MS Word (using Microsoft.Office.Interop.Word
range.Comments.Add ( range, ref \_categoryMessage );
So, I would suggest using Microsoft.Office.Interop.Excel and the similar method.
Consider this from MSDN:
<https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.ran... | The accepted answer points in the right direction, but the correct syntax is:
```
Excel.Range cell;
cell.AddComment("My comment");
``` | Insert cell comments in excel programmatically | [
"",
"c#",
"excel",
".net-3.5",
"openxml",
""
] |
I have some code like this:
```
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save([Bind(Prefix="")]Person person)
{
String s = person.property;
/* ... */
}
```
But it throws the error: "Cannot use local variable 'person' before it is declared".
What simple thing am I missing? | Okay, this is just some really bizarre error - if the variable is named a particular name it does not work, for any other name it does work... | It is most likely that you are receiving this error because the same variable is being declared later in the same code block.
According to compiler rules, a variable reference will refer to default by a matching declaration withing the same block EVEN IF THE SAME DECLARATION EXISTS OUTSIDE OF THE BLOCK IN IN LOGICAL S... | Cannot use local variable before it is declared ASP.NET | [
"",
"c#",
"asp.net-mvc",
""
] |
I am looking to write a function like
```
ref String TestIt( int index )
{
return this.TestArray[index];
};
```
so that I could write code like:
```
MyClass.TestIt(0) = "Hello World";
```
My goal is to mimic this c++ declaration
```
CString& MyClass::Data( UINT index);
```
By Reference I am referring to the c++ t... | To do this you need to write a setter property. Unfortunately, setters can’t take further arguments in C# so you won't be able to write this code 1:1 in C#. The closest you can get is a nested class with a default property:
```
class YourClass {
public class Nested {
public Nested(YourClass outer) { m_RefT... | The short answer is that you cannot return a reference to a string *variable*, i.e. a reference to the string reference).
The simple solution is to avoid this kind of API and require the user to set the string in another way:
```
myobj.SetString(0, "Hello, world!");
```
If you *really* need to represent (as a first-... | How to return a reference to a string in c#? | [
"",
"c#",
""
] |
I'm fairly new to WPF and I've come across a problem that seems a bit tricky to solve. Basically I want a 4x4 grid thats scalable but keeps a square (or any other arbitrary) aspect ratio. This actually seems quite tricky to do, which surprises me because I would imagine its a reasonably common requirement.
I start wit... | You need to put the content (the grid) inside a [Viewbox](http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.aspx) and set the [Viewbox.Stretch Property](http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.stretch.aspx) to [Stretch.Uniform](http://msdn.microsoft.com/en-us/librar... | In this instance, your best bet is a [UniformGrid](http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.uniformgrid.aspx). This is only useful if you want NxN grids. | How do I keep aspect ratio on scalable, scrollable content in WPF? | [
"",
"c#",
".net",
"wpf",
"xaml",
""
] |
We've been trying to hunt down some heap corruption issues in our multi-threaded C++ apps. As one technique, we tried add -lmcheck to the libraries line of the application. This is causing the app to crash out with apparent heap corruption in relatively short order.
Our app does use both malloc/free and new/delete (as... | No, mcheck is not thread-safe and should not be used with multi-threaded applications. Doing so can introduce additional problems since there is no synchronization between the threads. Here is the response from Ulrich Drepper (glibc maintainer) on the subject a few months ago:
> mcheck does not work for multi-threaded... | I should have checked that before we spent time fooling with it. Ahh well.
Here's the link to where that quote comes from (I believe):
<http://sourceware.org/bugzilla/show_bug.cgi?id=6547>
glibc documentation defect:
<http://sourceware.org/bugzilla/show_bug.cgi?id=12751>
has been opened to help avoid others from h... | glibc's '-lmcheck' option and multithreading | [
"",
"c++",
"multithreading",
"glibc",
""
] |
How do I do the above? I've started using MVC and I'm having issues passing data around.
My specific problem is to do with a list of objects I have in my Model which I need to access in a View and iterate through.
Thanks in advance. | Let's say your controller action looks something like
```
public ActionResult List()
{
List<string> myList = database.GetListOfStrings();
(...)
}
```
Now you want to pass your list to the view, say "List.aspx". You do this by having the action return a ViewResult (ViewResult is a subclass of ActionResult). Yo... | The quick and dirty way is to pass it via ViewData
```
public ActionResult List()
{
ViewData["MyList"] = new List<string> () {"test1", "test2"};
return View ();
}
```
then you can access it in your view
```
<ul>
<% foreach (string item in (List<string>)ViewData["MyList"]) { %>
<li><%= item %></li>
<% }%... | ASP.NET MVC: How do I pass a list (from a class in Model) to a repeater in a View? | [
"",
"c#",
"asp.net-mvc",
"model-view-controller",
""
] |
Assume I have a function like this:
```
MyClass &MyFunction(void)
{
static MyClass *ptr = 0;
if (ptr == 0)
ptr = new MyClass;
return MyClass;
}
```
The question is at program exit time, will the ptr variable ever become invalid (i.e. the contents of that ptr are cleaned up by the exiting process)? I realize... | To answer your question:
```
'imagine that the ptr points to some memory address which I want to check in the destructor of some other static class'
```
The answer is yes.
You can see the value of the pointer (the address).
You can look at the content if you have not called delete on the pointer.
Static function... | When you process exits the all memory pages allocated to it will be freed by the OS (modulo shared memory pages that someone else may be using).
However, as others point out the destructor for MyClass is never called. Nor is the value pointed to by ptr ever changed. If you have a static int with the value 123 then its... | C++: Do static primitives become invalid at program exit? | [
"",
"c++",
"memory-management",
"static",
""
] |
Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the `$n` values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.
Python does it like so:
```
>>> import re
>>> regex = re.compile(r'(?P<count>\d+)')
>>> mat... | Perl uses `(?<NAME>pattern)` to specify names captures. You have to use the `%+` hash to retrieve them.
```
$variable =~ /(?<count>\d+)/;
print "Count is $+{count}";
```
This is only supported on Perl 5.10 and higher though. | As of Perl 5.10, Perl regexes support [some Python features](http://perldoc.perl.org/perlre.html#PCRE%2fPython-Support), making them *Python* compatible regexes, I guess. The Python versions have the "P" in them, but all of these work in Perl 5.10. See the [perlre](http://perldoc.perl.org/perlre.html) documentation for... | Can I use named groups in a Perl regex to get the results in a hash? | [
"",
"python",
"regex",
"perl",
""
] |
How can I fetch more than 1000 record from data store and put all in one single list to pass to django? | Starting with Version 1.3.6 (released Aug-17-2010) you **CAN**
[From the changelog:](http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes#Version_1.3.6_-_August_17,_2010)
> Results of datastore count() queries **and offsets for all datastore queries are no longer capped at 1000**. | Just for the record - fetch limit of 1000 entries is now gone:
<http://googleappengine.blogspot.com/2010/02/app-engine-sdk-131-including-major.html>
Quotation:
> No more 1000 result limit - That's
> right: with addition of Cursors and
> the culmination of many smaller
> Datastore stability and performance
> improvem... | How to fetch more than 1000? | [
"",
"python",
"google-app-engine",
"google-cloud-datastore",
""
] |
Is there a way to find out when in a LAN anyone plugs in a pendrive to the USB port?
Programatically (in C# preferably) or through some tool. Basically I'd imagine a client application sits on each terminal and monitors the USB ports and sends the information to the server.
a.) Can I get the details of the file(s) bei... | [Assuming Windows, given the C# remark. Please tag accordingly]
Yes, this is possible. And it is possible to get the details of the file. It will require programming, though. Watch for [WM\_DEVICECHANGE](http://msdn.microsoft.com/en-us/library/aa363480(VS.85).aspx) and re-enumerate drives afterwards. It will get you U... | Also check out the registry where all information is stored about the usb devices.
HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Enum\USB
You can hook into changes of that key in the registry and act upon that.
This free utility are a big help when pooking around: <http://www.nirsoft.net/utils/usb_devices_view.html>
... | How to detect using c# if a pendrive is plugged into a USB port? | [
"",
"c#",
"windows",
"usb",
"monitoring",
"usb-flash-drive",
""
] |
This question follows on from [this vim search question](https://stackoverflow.com/questions/299114/can-i-search-for-php-class-members-and-methods-with-vim-star-search)
I have a setting in my .vimrc which excludes $ as a valid part of a word:
```
set iskeyword-=$
```
This works fine for most files but isn't working ... | I would probably just add `set isk-=$` to my syntax highlighting auto command in `$VIMRUNTIME\filetype.vim`. Don't know if it is the nicest way to do it, though.
Thinking about it... I think it would be enough to have an appropriate autocommand in your `vimrc`.
```
au FileType php set isk-=$
```
This executes a... | Add a {rtp}/after/ftplugin/php.vim that contains the `:setlocal isk-=$`
Otherwise, you will have to track where it has been changed last with `:verbose set isk`, or by playing with `:scriptnames` | Can I stop settings in vimrc from being overwritten by plugins? | [
"",
"php",
"plugins",
"vim",
""
] |
We are developing large ASP.NET applications with lot of dynmically created pages containing ASCX controls. We use a lot of jQuery everywhere.
I have been reading that it would make sense to move the inline JavaScript code to the bottom of the page as it could delay the loading of the page when it's included "too earl... | You could model the different ways of ordering the JavaScript in [Cuzillion](http://stevesouders.com/cuzillion/) to see how it affects page loading.
See the [examples](http://stevesouders.com/cuzillion/help.php#examples) and [this blog post](http://www.stevesouders.com/blog/2008/04/25/cuzillion/) for examples of how o... | Placing scripts late in the HTML is recommended because loading and executing scripts happens sequentially (one script at a time) and completely blocks the loading and parsing of images and CSS files meanwhile.
Large/lagged/slow-running scripts near the top of the page can cause unnecessary delay to the loading and re... | jQuery: Move JavaScript to the bottom of the page? | [
"",
"javascript",
"asp.net",
"jquery",
""
] |
I have a somewhat complex WPF application which seems to be 'hanging' or getting stuck in a Wait call when trying to use the dispatcher to invoke a call on the UI thread.
The general process is:
1. Handle the click event on a button
2. Create a new thread (STA) which: creates a new instance of the presenter and UI, t... | You say you are creating a new STA thread, is the dispatcher on this new thread running?
I'm getting from "this.Dispatcher.Thread != Thread.CurrentThread" that you expect it to be a different dispatcher. Make sure that its running otherwise it wont process its queue. | Invoke is synchronous - you want Dispatcher.BeginInvoke. Also, I believe your code sample should move the "SetValue" inside an "else" statement. | WPF Dispatcher.Invoke 'hanging' | [
"",
"c#",
".net",
"wpf",
"invoke",
"dispatcher",
""
] |
I have a SQL challenge that is wracking my brain. I am trying to reconcile two reports for licenses of an application.
The first report is an access database table. It has been created and maintained by hand by my predecessors. Whenever they installed or uninstalled the application they would manually update the table... | Taking Kaboing's answer and the edited question, the solution seems to be:
```
SELECT *
FROM report_1 r1
FULL OUTER JOIN report_2 r2
ON r1.SAMAccountName = r2.SAMAccountName
OR r1.NetbiosName = r2.NetbiosName
OR r1.DisplayName = r2.DisplayName
WHERE r2.NetbiosName IS NULL OR r1.NetbiosName IS NULL
```
N... | You need to look at the [EXCEPT](http://msdn.microsoft.com/en-us/library/ms188055.aspx) clause. It's new to SQL SERVER 2005 and does the same thing that Oracle's MINUS does.
SQL1
EXCEPT
SQL2
will give you all the rows in SQL1 not found in SQL2
IF
SQL1 = A, B, C, D
SQL2 = B, C, E
the result is A, D | SQL join to find inconsistencies between two data sources | [
"",
"sql",
"sql-server",
""
] |
I have an annoying problem which I might be able to somehow circumvent, but on the other hand would much rather be on top of it and understand what exactly is going on, since it looks like this stuff is really here to stay.
Here's the story: I have a simple OpenGL app which works fine: never a major problem in compili... | Boost.Thread has quite a few possible build combinations in order to try and cater for all the differences in linking scenarios possible with MSVC. Firstly, you can either link statically to Boost.Thread, or link to Boost.Thread in a separate DLL. You can then link to the DLL version of the MSVC runtime, or the static ... | This is a classic link error. It looks like you're [linking to a Boost DLL](http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#library-naming) that itself links to the wrong C++ runtime (there's also [this page](http://www.boost.org/development/separate_compilation.html), do a text search for "threa... | Adding Boost makes Debug build depend on "non-D" MSVC runtime DLLs | [
"",
"c++",
"visual-studio-2008",
"dll",
"boost",
"sxs",
""
] |
What is the simplest way to get: `http://www.[Domain].com` in asp.net?
There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone? | You can do it like this:
```
string.Format("{0}://{1}:{2}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port)
```
And you'll get the [generic URI syntax](http://www.faqs.org/rfcs/rfc2396.html) <protocol>://<host>:<port> | We can use Uri and his baseUri constructor :
* `new Uri(this.Request.Url, "/")` for the root of the website
* `new Uri(this.Request.Url, this.Request.ResolveUrl("~/"))` for the root of the website | What is the quickest way to get the absolute uri for the root of the app in asp.net? | [
"",
"c#",
"asp.net",
""
] |
What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")?
```
$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = ???($row['my_timestamp']);
e... | You could use MySQL to do this for you,
```
$result = mysql_query("SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = $row['my_timestamp'];
echo $formatted_date;
```
Or use PHP,
```
$result = mysql_query("SELECT m... | I tend to do the date formatting in SQL, like [Aron](https://stackoverflow.com/users/11568/aron)'s [answer](https://stackoverflow.com/questions/238071/what-is-the-simplest-way-to-format-a-timestamp-from-sql-in-php#238077). Although for PHP dates, I prefer using the [DateTime](http://www.php.net/manual/en/function.date-... | What is the simplest way to format a timestamp from SQL in PHP? | [
"",
"php",
"mysql",
"formatting",
"timestamp",
""
] |
When measuring network latency (time ack received - time msg sent) in any protocol over TCP, what timer would you recommend to use and why? What resolution does it have? What are other advantages/disadvantages?
Optional: how does it work?
Optional: what timer would you NOT use and why?
I'm looking mostly for Windows... | This is a copy of my answer from: [C++ Timer function to provide time in nano seconds](https://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds#275231)
For Linux (and BSD) you want to use [clock\_gettime()](http://opengroup.org/onlinepubs/007908799/xsh/clock_gettime.html).
```
#incl... | You mentioned that you use GetTickCount(), so I'm going to recommend that you take a look at QueryPerformanceCounter(). | Timers to measure latency | [
"",
"c++",
"winapi",
"timer",
"latency",
""
] |
I know in the MVC Framework, you have the Html Class to create URLs:
```
Html.ActionLink("About us", "about", "home");
```
But what if you want to generate Urls in Webforms?
I haven't found a really good resource on the details on generating URLs with Webforms.
For example, if I'm generating routes like so:
```
Ro... | As you say, ASP.NET MVC offers you a set of helper methods to "reverse lookup" the RouteTable and generate a URL for you. I've not played with this much yet but as far as I can see you need to call the GetVirtualPath method on a RouteCollection (most likely RouteTable.Routes). So something like:
```
Dim routedurl = Ro... | Thanks for the answers. TO add to this, here is what I've done:
## In Global.asax
```
RouteValueDictionary rvdSiteDefaults
= new RouteValueDictionary { { "country", "ca" }, { "lang", "en" } };
Route oneArticle
= new Route("{country}/{lang}/articles/a{id}/{title}",
rvdSiteDefaults,
rvdConstr... | Generate a URL with URL Routing in Webforms | [
"",
"c#",
"url",
"routes",
"url-routing",
""
] |
I've got Postscript code/data (?) in memory (in a Java Tomcat webapp) that I'd like to send directly to a networked PS printer. Is there an easy way (i.e. just popping open a port and sending the text) to print this, bypassing all of the O/S-specific drivers and stuff (and hopefully not even requiring extra jars)? A li... | open a TCP socket to the LPR port on the target printer.
send your data; as long as the printer comprehends it, you're cool.
don't forget a Line feed when you're done.
(then close the port.) | You can send it directly to a network printer on port 9100. I wrote a blog post about this here:
<http://frank.zinepal.com/printing-directly-to-a-network-printer>
The problem is that most laser printers do not support PostScript. You usually have to get a printer add-on for it. | Java printing directly to a Postscript network printer | [
"",
"java",
"networking",
"printing",
"postscript",
""
] |
I know it makes little difference to a project but, assuming you use #defined header guards for your C++ code, what format do you use? e.g. assuming a header called `foo.hpp`:
```
#ifndef __FOO_HPP__
...
#ifndef INCLUDED_FOO_HPP
...
#ifndef SOME_OTHER_FORMAT
```
I'm sold on the idea of upper-case #defines but canno... | I always included the namespace or relative path in the include guard, because only the header name alone has proven to be dangerous.
For example, you have some large project with the two files somewhere in your code
```
/myproject/module1/misc.h
/myproject/module2/misc.h
```
So if you use a consistent naming schema... | To truly avoid name collisions, I use GUIDs:
```
#ifndef GUARD_8D419A5B_4AC2_4C34_B16E_2E5199F262ED
``` | #include header guard format? | [
"",
"c++",
"header",
"c-preprocessor",
""
] |
The situation is somewhat like-
```
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
```
The problem is that the value of `someVar` is not visible inside the listener function of the `addEventListener`, where it is probably being treated as a ne... | There is absolutely nothing wrong with the code you've written. Both `some_function` and `someVar` should be accessible, in case they were available in the context where anonymous
```
function() { some_function(someVar); }
```
was created.
Check if the alert gives you the value you've been looking for, be sure it wi... | Why not just get the arguments from the target attribute of the event?
Example:
```
const someInput = document.querySelector('button');
someInput.addEventListener('click', myFunc, false);
someInput.myParam = 'This is my parameter';
function myFunc(evt)
{
window.alert(evt.currentTarget.myParam);
}
```
```
<bu... | How to pass arguments to addEventListener listener function? | [
"",
"javascript",
"dom",
"addeventlistener",
""
] |
Which is the best method to make the browser use cached versions of js files (from the serverside)? | Have a look at Yahoo! tips: <https://developer.yahoo.com/performance/rules.html#expires>.
There are also tips by Google: <https://developers.google.com/speed/docs/insights/LeverageBrowserCaching> | or in the .htaccess file
```
AddOutputFilter DEFLATE css js
ExpiresActive On
ExpiresByType application/x-javascript A2592000
``` | caching JavaScript files | [
"",
"javascript",
"http",
"caching",
""
] |
What would be the most efficient data type to store a UUID/GUID in databases that do not have a native UUID/GUID data type? 2 BIGINTs?
And what would be the most efficient code (C# preferred) to convert to and from a GUID to that type?
Thanks. | It's hard to say what would be the most efficient without knowing the database you are using.
My first inclination would be to use a `binary(16)` column.
As for using that value in C#, the `System.Guid` type has a constructor that accepts a `byte[]` array, and a method `ToByteArray()` that returns a byte array. | In my experience, the UUID broken up into two integers will still be more efficient than using a char field. Different DBs react in different ways though. Collation could make a difference there too. That being said, there are usually much bigger performance "sins" all over applications, and I don't think that this wou... | Most efficient data type for UUID in database besides a native UUID | [
"",
"c#",
"database",
"database-design",
"guid",
"uuid",
""
] |
I am trying to use `set.insert (key)` as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like:
```
if (set.insert( key )) {
// some kind of code
}
```
Is this allowed? Because... | The version of insert that takes a single key value should return a `std::pair<iterator,bool>`, where the bool indicates whether an insertion was made. A value of true indicates that the value was inserted, and false indicates that the value was already present. So your conditional would look like this:
```
if( set.in... | set::insert returns a pair, try this:
```
if( set.insert( key ).second ) {
// some kind of code
}
``` | Using set.insert( key ) as a conditional? | [
"",
"c++",
"insert",
"conditional-statements",
"set",
""
] |
For a system I need to convert a pointer to a long then the long back to the pointer type. As you can guess this is very unsafe. What I wanted to do is use dynamic\_cast to do the conversion so if I mixed them I'll get a null pointer. This page says <http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?top... | I've had to do similar things when loading C++ DLLs in apps written in languages that only support a C interface. Here is a solution that will give you an immediate error if an unexpected object type was passed in. This can make things much easier to diagnose when something goes wrong.
The trick is that every class th... | `dynamic_cast` can be used only between classes related through inheritance. For converting a pointer to long or vice-versa, you can use `reinterpret_cast`. To check whether the pointer is null, you can `assert(ptr != 0)`. However, it is usually not advisable to use `reinterpret_cast`. Why do you need to convert a poin... | Safely checking the type of a variable | [
"",
"c++",
"dynamic-cast",
""
] |
I've got a ant `build.xml` that uses the `<copy>` task to copy a variety of xml files. It uses filtering to merge in properties from a `build.properties` file. Each environment (dev, stage, prod) has a different `build.properties` that stores configuration for that environment.
Sometimes we add new properties to the S... | You can do it in ant 1.7, using a combination of the `LoadFile` task and the `match` condition.
```
<loadfile property="all-build-properties" srcFile="build.properties"/>
<condition property="missing-properties">
<matches pattern="@[^@]*@" string="${all-build-properties}"/>
</condition>
<fail message="Some propert... | If you are looking for a specific property, you can just use the fail task with the unless attribute, e.g.:
```
<fail unless="my.property">Computer says no. You forgot to set 'my.property'!</fail>
```
Refer to [the documentation for Ant's fail task](https://ant.apache.org/manual/Tasks/fail.html "Ant fail documentatio... | ant filtering - fail if property not set | [
"",
"java",
"ant",
""
] |
I'm building a JSF+Facelets web app, one piece of which is a method that scans a directory every so often and indexes any changes. This method is part of a bean which is in application scope. I have built a subclass of TimerTask to call the method every X milliseconds. My problem is getting the bean initialized. I can ... | If your code calls [FacesContext](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/FacesContext.html), it will not work outside a thread associated with a JSF request lifecycle. A FacesContext object is created for every request and disposed at the end of the request. The reason you can fe... | Using listeners or load-on-startup, try this: <http://www.thoughtsabout.net/blog/archives/000033.html> | JSF initialize application-scope bean when context initialized | [
"",
"java",
"jsf",
""
] |
I'm designing a system which is receiving data from a number of partners in the form of CSV files. The files may differ in the number and ordering of columns. For the most part, I will want to choose a subset of the columns, maybe reorder them, and hand them off to a parser. I would obviously prefer to be able to trans... | XSLT provides new features that make it easier to parse non-XML files.
Andrew Welch posted an [XSLT 2.0 example that converts CSV into XML](http://ajwelch.blogspot.com/2007/02/csv-to-xml-converter-in-xslt-20.html) | I think you need something like this (sorry, not supported by .NET but code is very simple)
<http://csv2xml.sourceforge.net> | Transforming flat file to XML using XSLT-like technology | [
"",
"c#",
".net",
"xml",
"xslt",
"flat-file",
""
] |
What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in javascript)?
An example (psuedo code):
```
function mouseClick()
{
moveDiv("div_0001", mouseX, mouseY);
}
function moveDiv(objID, destX, destY)
{
//some code that moves the div closer to destination... | when you call settimeout, it returns you a variable "handle" (a number, I think)
if you call settimeout a second time, you should first
```
clearTimeout( handle )
```
then:
```
handle = setTimeout( ... )
```
to help automate this, you might use a wrapper that associates timeout calls with a string (i.e. the div's ... | I would do it this way:
```
// declare an array for all the timeOuts
var timeOuts = new Array();
// then instead of a normal timeOut call do this
timeOuts["uniqueId"] = setTimeout('whateverYouDo("fooValue")', 1000);
// to clear them all, just call this
function clearTimeouts() {
for (key in timeOuts) {
... | How do you handle multiple instances of setTimeout()? | [
"",
"javascript",
""
] |
In regular Java, you can get the text of a stack trace by passing a PrintWriter to printStackTrace. I have a feeling I know the answer to this (i.e. "No") but,
Is there any way to obtain the text of a stack trace in JavaME as a String?
**Update:**
I should mention that I'm restricted to CLDC 1.0 | AFAIK there is no way to get the stack trace as a string value, unless a specific platform provides a means to override the default System.err stream. On the BlackBerry platform, it throws out the stack trace on `catch(Exception)` in order to save memory, however it doesn't do this on `catch(Throwable)` and gives acces... | two solutions:
* reproduce the exception on emulator. the wireless toolkit and Netbeans will print stack traces on your computer.
* use a Symbian device.
Prior to the Feature Pack 2 of Series 60 3rd edition, Symbian handsets use the Sun Hotspot java virtual machine. It was adapted to Symbian OS by linking it to a par... | How to get the text of an exception stack trace in Java ME? | [
"",
"java",
"java-me",
""
] |
I have extensively used Prototype before and it helped us add considerable interactivity to our web applications. However we are looking at making the move to use jQuery in order to standardize on something better supported in Visual Studio.
I understand that we can use the jQuery.noConflict to run it alongside Protot... | I can't really help you too much with your question, other than to say that I haven't heard of any such tool, and that I'd be really surprised if one actually existed.
While I think jQuery is a great library, and that you're right to be wanting to only use one library, just remember that the cost of you changing over ... | Falkayn,
There is no automated process available for conversion of JavaScipt code written against one JS library to another one. Moreover there cannot be one. Different libraries implement different proramming models as well as they arrange their APIs in different manner.
So, before you have found a solution to your ... | Is there a resource to help convert Prototype JavaScript to jQuery? | [
"",
"javascript",
"jquery",
"asp.net",
"visual-studio",
"prototypejs",
""
] |
My C++ framework has Buttons. A Button derives from Control. So a function accepting a Control can take a Button as its argument. So far so good.
I also have List`<`T>. However, List`<`Button> doesn't derive from List`<`Control>, which means a function accepting a list of Controls can't take a list of Buttons as its a... | I hate to tell you but if you're using a list of instances to Control instead of pointers to Control, your buttons will be garbage anyway (Google "object slicing"). If they're lists of pointers, then either make the `list<button*>` into `list<control*>` as others have suggested, or do a copy to a new `list<control*>` f... | Stroustrup has an item on this in his FAQ:
[Why can't I assign a `vector<Apple*>` to a `vector<Fruit*>`](http://www.research.att.com/~bs/bs_faq2.html#conversion)
You can solve it in two ways:
* Make the List contain pointers to `Control` . Then accept `List<Control*>`
* Make your function a template. You can still u... | C++ templates and inheritance | [
"",
"c++",
"inheritance",
"templates",
""
] |
So, when playing with the development I can just set `settings.DEBUG` to `True` and if an error occures I can see it nicely formatted, with good stack trace and request information.
But on kind of production site I'd rather use `DEBUG=False` and show visitors some standard error 500 page with information that I'm work... | Well, when `DEBUG = False`, Django will automatically mail a full traceback of any error to each person listed in the `ADMINS` setting, which gets you notifications pretty much for free. If you'd like more fine-grained control, you can write and add to your settings a middleware class which defines a method named `proc... | Django Sentry is a good way to go, as already mentioned, but there is a bit of work involved in setting it up properly (as a separate website). If you just want to log everything to a simple text file here's the logging configuration to put in your `settings.py`
```
LOGGING = {
'version': 1,
'disable_existing_... | How do you log server errors on django sites | [
"",
"python",
"django",
"error-logging",
""
] |
I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:
```
fun (head : rest) = ...
```
So when I pass in a list, `head` will be the first element, and `rest` will be the trailing elements.
Likewise, in Python, I can automatically unpack tuples:
```
(va... | So far as I know there's no way to make it a one-liner in current Python without introducing another function, e.g.:
```
split_list = lambda lst: (lst[0], lst[1:])
head, rest = split_list(my_func())
```
However, in Python 3.0 the specialized syntax used for variadic argument signatures and argument unpacking will bec... | First of all, please note that the "pattern matching" of functional languages and the assignment to tuples you mention are not really that similar. In functional languages the patterns are used to give partial definitions of a function. So `f (x : s) = e` does not mean take the head and tail of the argument of `f` and ... | Pattern matching of lists in Python | [
"",
"python",
"functional-programming",
"pattern-matching",
""
] |
I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great.
When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature
```
System.Collections.Generic.List<<>f__AnonymousType0<System.DateTime,System.Linq.IGrouping<Sys... | select new { Date = s.Key, Games = s.ToList() };
Edit: thats wrong! I think this will do.
```
public List<IGrouping<DateTime, Game>> getGamesList(int leagueID)
{
var sortedGameList =
from g in Games
group g by g.Date;
return sortedGameList.ToList();
}
```
And no, you do not need the select! | You shouldn't return anonymous instances.
You can't return anonymous types.
Make a type (named) and return that:
```
public class GameGroup
{
public DateTime TheDate {get;set;}
public List<Game> TheGames {get;set;}
}
```
//
```
public List<GameGroup> getGamesGroups(int leagueID)
{
List<GameGroup> sortedGameL... | Anonymous Types in a signature | [
"",
"c#",
"asp.net-mvc",
"linq",
"anonymous-types",
""
] |
Is it ever acceptable to have a [memory leak](http://en.wikipedia.org/wiki/Memory_leak) in your C or C++ application?
What if you allocate some memory and use it until the very last line of code in your application (for example, a global object's destructor)? As long as the memory consumption doesn't grow over time, i... | No.
As professionals, the question we should not be asking ourselves is, "Is it ever OK to do this?" but rather "Is there ever a *good* reason to do this?" And "hunting down that memory leak is a pain" isn't a good reason.
I like to keep things simple. And the simple rule is that my program should have no memory leak... | I don't consider it to be a memory leak unless the amount of memory being "used" keeps growing. Having some unreleased memory, while not ideal, is not a big problem unless the amount of memory required keeps growing. | Are memory leaks ever OK? | [
"",
"c++",
"c",
"memory-leaks",
""
] |
Please tell me if it is possible to do the following:
* create an instance of a specific class in Java
* pass it to JRuby to do something with it
* continue using the "modified" version in Java
May you provide a small working example?
EDIT: It turns out that embedding was the simplest way to achieve this. More infor... | This was the solution I used : [Direct JRuby embedding](https://github.com/jruby/jruby/wiki/RedBridge) | Yes it's possible. [This page](https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby) on the JRuby wiki should get you started. | JRuby and Java objects | [
"",
"java",
"scripting",
"jruby",
"jruby-java-interop",
""
] |
I'm trying to find the best solution for nonblocking IO via stdin/stdout with the following characteristics:
* As long as there is enough data, read in *n*-sized chunks.
* If there's not enough data, read in a partial chunk.
* If there is no data available, block until there is some (even though it may be smaller than... | Maybe [boost::asio](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html) can be of use for you? | I used the threads and platform specific code. See [my answer to another question](https://stackoverflow.com/questions/717572/c-nonblocking-io-on-linux/1280659#1280659). I was able to put the OS-specific stuff in inputAvailable() (Linux uses select, Windows just returns true). I could then use WaitForSingleObject() wit... | Cross-platform (linux/Win32) nonblocking C++ IO on stdin/stdout/stderr | [
"",
"c++",
"pipe",
"stdin",
"iostream",
"nonblocking",
""
] |
How can you convert a byte array to a hexadecimal string and vice versa? | You can use [`Convert.ToHexString`](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring) starting with .NET 5.
There's also a method for the reverse operation: [`Convert.FromHexString`](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring).
---
For older versions of .NET yo... | ## Performance Analysis
*Note: new leader as of 2015-08-20.*
I ran each of the various conversion methods through some crude `Stopwatch` performance testing, a run with a random sentence (n=61, 1000 iterations) and a run with a Project Gutenburg text (n=1,238,957, 150 iterations). Here are the results, roughly from f... | How do you convert a byte array to a hexadecimal string, and vice versa? | [
"",
"c#",
"arrays",
"hex",
""
] |
When using the [pImpl idiom](http://en.wikipedia.org/wiki/Pimpl_idiom) is it preferable to use a `boost:shared_ptr` instead of a `std::auto_ptr`? I'm sure I once read that the boost version is more exception friendly?
```
class Foo
{
public:
Foo();
private:
struct impl;
std::auto_ptr<impl> impl_;
};
class... | You shouldn't really use std::auto\_ptr for this. The destructor won't be visible at the point you declare the std::auto\_ptr, so it might not be called properly. This is assuming that you are forward declaring your pImpl class, and creating the instance inside the constructor in another file.
If you use [boost::scope... | I tend to use `auto_ptr`. Be sure to make your class noncopyable (declare private copy ctor & operator=, or else inherit `boost::noncopyable`). If you use `auto_ptr`, one wrinkle is that you need to define a non-inline destructor, even if the body is empty. (This is because if you let the compiler generate the default ... | std::auto_ptr or boost::shared_ptr for pImpl idiom? | [
"",
"c++",
"boost",
"stl",
"shared-ptr",
"auto-ptr",
""
] |
Does anybody know what's going on here:
I run hibernate 3.2.6 against a PostgreSQL 8.3 (installed via fink) database on my Mac OS X. The setup works fine when I use Java 6 and the JDBC 4 driver (postgresql-8.3-603.jdbc4). However, I need this stuff to work with Java 5 and (hence) JDBC 3 (postgresql-8.3-603.jdbc3). Whe... | I don't see you specifying the driver class in your Hibernate configuration. Try adding the following:
```
<hibernate-configuration>
<session-factory>
.
.
<property name="connection.driver_class">org.postgresql.Driver</property>
.
</session-factory>
</hibernate-configuration>
``... | did you notice that the connection url is incomplete
```
<property name="connection.url">jdbc:postgresql:test</property>
```
as opposed to
```
<property name="connection.url">jdbc:postgresql://localhost/test</property>
``` | "No suitable driver" problem with Hibernate3, PostgreSQL 8.3 and Java 5 | [
"",
"java",
"hibernate",
"postgresql",
""
] |
I'm not sure what the best api for simple 2d graphics with Java is. I know `java.awt.Graphics2D` was the standard but has it been replaced? Swing is the new API for Java GUI apps but it seems a bit heavy for what I want. What I really want is something like the C [SDL library](http://libsdl.org/). | [Java 2D](http://docs.oracle.com/javase/tutorial/2d/) (`Graphics2D` and friends) is indeed the best choice that I know of. Swing is actually implemented on top of Java 2D, so yes, if you want non-GUI-type graphics, Java 2D is the way to go. | If you want to have the least work possible if you're building a game (or even if not) use <http://slick.cokeandcode.com/>
UPDATE: The link has since changed to <http://slick.ninjacave.com/> | Best API for simple 2D graphics with Java | [
"",
"java",
"graphics",
"java-2d",
""
] |
I'm writing a GreaseMonkey script where I'm iterating through a bunch of elements. For each element, I need a string ID that I can use to reference that element later. The element itself doesn't have an `id` attribute, and I can't modify the original document to give it one (although I can make DOM changes in my script... | **UPDATE:** Closures are indeed the answer. So after fiddling with it some more, I figured out why closures were initially problematic and how to fix it. The tricky thing with a closure is you have to be careful when iterating through the elements not to end up with all of your closures referencing the same element. Fo... | Closure is the way to go. This way you'll have exact reference to the element that even will survive some shuffling of DOM.
Example for those who don't know closures:
```
var saved_element = findThatDOMNode();
document.body.onclick = function()
{
alert(saved_element); // it's still there!
}
```
*If* you had to ... | Unique element ID, even if element doesn't have one | [
"",
"javascript",
"firefox",
"dom",
"greasemonkey",
""
] |
I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a `dict` which will page parts of itself ou... | Hash-on-disk is generally addressed with Berkeley DB or something similar - several options are listed in the [Python Data Persistence documentation](http://docs.python.org/library/persistence.html). You can front it with an in-memory cache, but I'd test against native performance first; with operating system caching i... | The 3rd party [shove](http://pypi.python.org/pypi/shove) module is also worth taking a look at. It's very similar to shelve in that it is a simple dict-like object, however it can store to various backends (such as file, SVN, and S3), provides optional compression, and is even threadsafe. It's a very handy module
```
... | Python Disk-Based Dictionary | [
"",
"python",
"database",
"dictionary",
"disk-based",
""
] |
I need to share SSO information between two different domains with a cookie, can this be done in PHP and how? | On both domains, place an image or other web element that is pulled from the other domain. Use the URL to notify the other domain that user X is on domain A, and let domain B associate that user ID with that user on their system.
It's a little complex to carry out correctly, but if you think it through it'll work out ... | You don't, cookies are bound to a domain. There are restrictions on this and it's referred to as cross site scripting.
Now, for some help to your problem.
What you can do is create a script that helps bridge them.
You can globally rewrite all links to your second site are going to need cookie information from the fir... | How do I use cookies across two different domains? | [
"",
"php",
"cookies",
""
] |
I am attempting to insert a copy of a row from one table into another table with the same schema, with the addition of one column (a timestamp) to provide a "history" of the first table in MS Sql Server 2005.
So, my query, without the additional column would be:
```
"SELECT INTO [WebsiteHistory] FROM [Website]"
```
... | Be warned. This works, but it is neither *nice* nor recommendable:
```
INSERT
WebsiteHistory
SELECT
*,
GETDATE()
FROM
Website
WHERE
Id = @WebsiteId
```
This assumes `WebsiteHistory` has the same structure as `Website` (you said it has), plus there is one additional `DATETIME` field.
Better is this, because... | Can't you set a default constraint on the column that would automatically populate the timestamp column when a row is inserted to the table? | SELECT INTO with an additional column | [
"",
".net",
"sql",
"sql-server-2005",
"t-sql",
""
] |
I want to build two-dimentional array of strings where length of one dimention is 2. Similar to this
```
string[,] array = new string[,]
{
{"a", "b"},
{"c", "d"},
{"e", "f"},
{"g", "h"}
}
```
Doing
```
List<string[]> list = new List<string[]>();
list.Add(new string[2] {"a", "b"});
list.Add(new strin... | Well, you could reasonably easily write an extension method to do it. Something like this (only tested very slightly):
```
public static T[,] ToRectangularArray<T>(this IEnumerable<T[]> source)
{
if (!source.Any())
{
return new T[0,0];
}
int width = source.First().Length;
if (source.Any(ar... | You can do this.
```
List<KeyValuePair<string, string>>
```
The idea being that the Key Value Pair would mimic the array of strings you replicated. | Is there a way to define a List<> of two elements string array? | [
"",
"c#",
"arrays",
"generics",
"data-structures",
""
] |
I'm fairly new to c# so that's why I'm asking this here.
I am consuming a web service that returns a long string of XML values. Because this is a string all the attributes have escaped double quotes
```
string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>"
```
Here is my problem. I want to do a s... | the following statement in C#
```
string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>"
```
will actually store the value
```
<root><item att1="value" att2="value2" /></root>
```
whereas
```
string xmlSample = @"<root><item att1=\""value\"" att2=\""value2\"" /></root>";
```
have the value of
... | There's no reason to use a Regular expression at all... that's a lot heavier than what you need.
```
string xmlSample = "blah blah blah";
xmlSample = xmlSample.Replace("\\\", "\"");
``` | C# String.Replace double quotes and Literals | [
"",
"c#",
"xml",
""
] |
I'm wondering if I'm missing something about Java Beans. I like my objects to do as much initialization in the constructor as possible and have a minimum number of mutators. Beans seem to go directly against this and generally feel clunky. What capabilities am I missing out on by not building my objects as Beans? | It sounds like you are on the right track. It's not you who's missing the point of Java Beans, it is other programmers that are misusing them.
The Java Beans specification was designed to be used with visual tools. The idea was that an application designer would be able to configure an instance of an object interactiv... | > I like my objects to do as much
> initialization in the constructor as
> possible and have a minimum number of
> mutators.
Favouring immutable objects is a wise choice. However the benefit of beans is that frameworks/tools/libraries can determine at runtime the properties of a class, without requiring you to impleme... | Java Beans: What am I missing? | [
"",
"java",
"javabeans",
""
] |
Is there anything to use, to determine if a type is actually a anonymous type? For example an interface, etc?
The goal is to create something like the following...
```
//defined like...
public static T Get<T>(this IAnonymous obj, string prop) {
return (T)obj.GetType().GetProperty(prop).GetValue(obj, null);
}
//..... | EDIT: The list below applies to C# anonymous types. VB.NET has different rules - in particular, it can generate mutable anonymous types (and does by default). Jared has pointed out in the comment that the naming style is different, too. Basically this is all pretty fragile...
You can't identify it in a generic constra... | As I recall, there is a [`[CompilerGenerated]`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.compilergeneratedattribute.aspx) marker... 2 secs
Plus the name will be freaky, and it will be a generic type ;-p
Actually, for a "get" etc I would probably just use a static (non-extension) method.... | Anonymous Types - Are there any distingushing characteristics? | [
"",
"c#",
".net",
"generics",
"extension-methods",
"anonymous-types",
""
] |
Is it possible?
By debug I mean setting breakpoints, inspect values and advance step by step. | You can do remote debugging of python web apps over TCP/IP with [winpdb](http://winpdb.org/).
(Link appears down as of June 2019. Try [PyPI winpdb](https://pypi.org/project/winpdb/)) | I haven't used web2py, but if it runs in a terminal window, you can use standard pdb stuff. Add this line somewhere in your code:
```
import pdb; pdb.set_trace()
```
This will invoke the debugger and break. Then you can use [PDB](http://docs.python.org/lib/module-pdb.html) commands: n to step to the next line, l to l... | How to debug Web2py applications? | [
"",
"python",
"debugging",
"web2py",
""
] |
I am migrating an application from .NET 1.1 to .NET 2.0. Should I remove all uses of CollectionBase? If so, what is the best strategy for migration? | Yes, the best classes to look at are in System.Collections.Generic.
I usually use List.
There are two approaches you can use either:
**A**
```
public class MyClass
{
public List<MyItem> Items;
}
```
**B**
```
public class MyItemCollection : List<MyItem>
{
}
public class MyClass
{
public MyItemCollection Ite... | Generally, `List<T>` does most of what you normally want. If you want to customize behaviour, you should inherit from `Collection<T>` - this has `virtual` methods so you can tweak behaviour when adding/removing/updating etc. You can't do this with `List<T>` since there are no (uesful) `virtual` methods. | CollectionBase vs generics | [
"",
"c#",
".net",
"generics",
""
] |
I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate).
[Pybloom](http://www.imperialviolet.org/pybloom.html) is one option but it seems to be showing its age as it throws DeprecationWarning errors on Pyth... | Eventually I found [pybloomfiltermap](http://github.com/axiak/pybloomfiltermmap). I haven't used it, but it looks like it'd fit the bill. | I recently went down this path as well; though it sounds like my application was slightly different. I was interested in approximating set operations on a large number of strings.
You do make the key observation that a **fast** bit vector is required. Depending on what you want to put in your bloom filter, you may als... | Modern, high performance bloom filter in Python? | [
"",
"python",
"jython",
"bloom-filter",
""
] |
i'm generating controls dynamically on my asp.net page by xslt transformation from an xml file. i will need to reference these controls from code behind later. i would like to add these references to the list/hashtable/whatever during creation (in xslt file i suppose) so that i could reach them later and i have no idea... | Once you have transformed your XML using XSLT, you could pass the output to the ASP.Net [ParseControl](http://msdn.microsoft.com/en-us/library/kz3ffe28.aspx) method and it will return your controls ready to use. For example this code will place two buttons on the page:
```
protected void Page_Load(object sender, Event... | Can you give a better idea of what you are trying to do?
XML > XSLT > produces aspx page
Sounds close to reinventing the windows presentation framework or XUL
Or is it
ASPX reads xml > uses XSLT to add DOM elements to page...
Sounds like AJAX
You want to write out a unique ID using the attribute transform
<http://w... | ASP.NET - controls generated by xslt transformation | [
"",
"c#",
"asp.net",
"xml",
"xslt",
""
] |
I am new to mysqli, and trying to confirm that if I so something like the below, the errno will be set to the last error, if any, and not the error of the last query.
Is this a decent practice or should I be checking for the error in between every query?
Thanks!
```
$mysqli->autocommit(FALSE);
$mysqli->query("INSER... | mysqli\_errno — Returns the error code for **the most recent function call**. | No -- it reports the error code of the last mysqli function call. Zero means no error occurred on the last function call. So if one in the middle fails, you won't know about it by checking only at the end.
In other words, yes, you need to check the error code after each function call. Note that an error is indicated b... | mysqli->error: Is it for the last query only, or for the last error from the query group? | [
"",
"php",
"mysql",
"mysqli",
"transactions",
""
] |
How can I compare strings in a case insensitive way in Python?
I would like to encapsulate comparison of a regular strings to a repository string, using simple and Pythonic code. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. | Assuming ASCII strings:
```
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print("The strings are the same (case insensitive)")
else:
print("The strings are NOT the same (case insensitive)")
```
As of Python 3.3, [casefold()](https://docs.python.org/3/library/stdtypes.html#str.cas... | Comparing strings in a case insensitive way seems trivial, but it's not. I will be using Python 3, since Python 2 is underdeveloped here.
The first thing to note is that case-removing conversions in Unicode aren't trivial. There is text for which `text.lower() != text.upper().lower()`, such as `"ß"`:
```
>>> "ß".lowe... | How do I do a case-insensitive string comparison? | [
"",
"python",
"comparison",
"case-insensitive",
""
] |
In php I need to get the contents of a url (source) search for a string "maybe baby love you" and if it does not contain this then do x. | Just read the contents of the page as you would read a file. PHP does the connection stuff for you. Then just look for the string via regex or simple string comparison.
```
$url = 'http://my.url.com/';
$data = file_get_contents( $url );
if ( strpos( 'maybe baby love you', $data ) === false )
{
// do something
}... | ```
//The Answer No 3 Is good But a small Mistake in the function strpos() I have correction the code bellow.
$url = 'http://my.url.com/';
$data = file_get_contents( $url );
if ( strpos($data,'maybe baby love you' ) === false )
{
// do something
}
``` | PHP Get URL Contents And Search For String | [
"",
"php",
""
] |
I am trying to determine the best directory structure of my application
i have:
UI
Data
Interfaces
but i dont know where to put delegates..
should there be a seperate Delegates folder or should i store the delegates in the same classes where they are being used . . | If you have an common use for your delegates, you should store them on a common place, but if you only use it in your class then put it in the same class. | You don't have a Classes, Structs, and Enums folder. Why have a Delegates folder?
Also, if you're using C# 3.0, you generally should be using Generic Delegates - System.Action and System.Func - instead of named delegates. | Where to put your delegates . . | [
"",
"c#",
"delegates",
"directory-structure",
""
] |
I'm able to get cells to format as Dates, but I've been unable to get cells to format as currency... Anyone have an example of how to create a style to get this to work? My code below show the styles I'm creating... the styleDateFormat works like a champ while styleCurrencyFormat has no affect on the cell.
```
private... | After digging through the documentation a bit more, I found the answer:
<http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDataFormat.html>
Just need to find an appropriate pre-set format and supply the code.
```
styleCurrencyFormat.setDataFormat((short)8); //8 = "($#,##0.00_);[Red]($#,##0.00)"
```... | For at least Excel 2010:
Go into Excel. Format a cell they way you want it.

Then go back into the format dialogue. Select custom.

Copy paste the text it has on the top row under ... | Basic Excel currency format with Apache POI | [
"",
"java",
"apache-poi",
""
] |
I'm new to PHP and I'm trying to do something that may be bad practise and may well be impossible. I'm basically just hacking something together to test my knowledge and see what PHP can do.
I have one webpage with a form that collects data. That is submited to a PHP script that does a bunch of processing - but doesn'... | Is it really necessary to call another page after the processing is done? I'd probably do the following:
```
<form method="post" action="display.php">
...
</form>
```
display.php:
```
if ($_POST) {
require_once(process.php);
process($_POST);
display_results;
}
```
with process.php containing the code ne... | You could store that data in the session e.g. in the first file that handles the post
```
session_start();
$_SESSION['formdata'] = $_POST; //or whatever
```
then you can read it on the next page like
```
session_start();
print_r($_SESSION['formdata']);
```
or you could pass it through GET: (but as per comments this... | PHP open another webpage with POST data | [
"",
"php",
"post",
"redirect",
"header",
""
] |
My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.
What is ... | Have a look here: <http://en.wikipedia.org/wiki/Environment_variable#User_management_variables>. Anything that's under the users directory is good. If its for all users, then it should be: %ALLUSERSPROFILE%. If its for a specific user, make sure the permissions are right.
Check out MSDN for more info about other Windo... | The standard location for Windows application to store their (permanent) application data is referenced by the `%APPDATA%` (current user) or `%ALLUSERSPROFILE%` (all users) environment variables. You can access them using, e.g. (only rudimentary and not very elegant error checking!):
```
import os
app_path = os.getenv... | Appropriate location for my application's cache on Windows | [
"",
"python",
"windows",
""
] |
I've seen this syntax a couple times now, and it's beginning to worry me,
For example:
```
iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();
``` | It's a Generic Method, Create is declared with type parameters, and check this links for more information:
* [An Introduction to C# Generics](http://msdn.microsoft.com/en-us/library/ms379564(vs.80).aspx)
* [Generics (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/)
* ... | It's calling a generic method - so in your case, the method may be declared like this:
```
public T Create<T>()
```
You can specify the type argument in the angle brackets, just as you would for creating an instance of a generic type:
```
List<Event> list = new List<Event>();
```
Does that help?
One difference bet... | What does Method<ClassName> mean? | [
"",
"c#",
"class",
"oop",
"generics",
"syntax",
""
] |
I have a couple of questions about generic wildcards in Java:
1. What is the difference between `List<? extends T>` and `List<? super T>`?
2. What is a bounded wildcard and what is an unbounded wildcard? | In your first question, `<? extends T>` and `<? super T>` are examples of bounded wildcards. An unbounded wildcard looks like `<?>`, and basically means `<? extends Object>`. It loosely means the generic can be any type. A bounded wildcard (`<? extends T>` or `<? super T>`) places a restriction on the type by saying th... | If you have a class hierarchy `A`, `B` is a subclass of `A`, and `C` and `D` are both subclasses of `B` like below
```
class A {}
class B extends A {}
class C extends B {}
class D extends B {}
```
Then
```
List<? extends A> la;
la = new ArrayList<B>();
la = new ArrayList<C>();
la = new ArrayList<D>();
List<? super ... | Java Generics (Wildcards) | [
"",
"java",
"generics",
"bounded-wildcard",
""
] |
I have an already large table that my clients are asking for me to extend the length of the notes field. The notes field is already an NVARCHAR(1000) and I am being asked to expand it to 3000. The long term solution is to move notes out of the table and create a notes table that uses an NVARCHAR(max) field that is only... | text and ntext are deprecated in favor of varchar(max) and nvarchar(max). So nvarchar(3000) should be fine. | You probably already know this, but just make sure that the increased length doesn't drive your total record length over 8000. I pretty sure that still applies for 2005/2008. | What problems can an NVARCHAR(3000) cause | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I am looking to use quartz to schedule emails, but I'm not sure which approach to take:
1. Create a new job and trigger whenever an email is scheduled OR
2. Create a single job, and create a new trigger each time an email is scheduled
I need to pass the message/recipient etc either way, and I'm not sure whether creat... | Quartz is intended to handle tens of thousands of triggers. The main limit to scalability here is the space available in your JobStore. A JDBCJobStore backed with a reasonable database should be able to handle hundreds of thousands of triggers.
If a single job can be parameterized through the trigger's job data map, c... | Are the triggers to be based on a time schedule? You can use a [CronTrigger](http://www.opensymphony.com/quartz/wikidocs/CronTriggers%20Tutorial.html) to set up a more complex time based schedule rather than individual triggers. | Should I create a new quartz job and trigger or one job and many triggers? | [
"",
"java",
"scheduling",
"quartz-scheduler",
""
] |
I have a static class that I would like to raise an event as part of a try catch block within a static method of that class.
For example in this method I would like to raise a custom event in the catch.
```
public static void saveMyMessage(String message)
{
try
{
//Do Database stuff
}
catch (E... | Important: be very careful about subscribing to a static event from instances. Static-to-static is fine, but a subscription from a static event to an instance handler is a great (read: very dangerous) way to keep that instance alive forever. GC will see the link, and will not collect the instance unless you unsubscribe... | Your event would also need to be static:
```
public class ErrorEventArgs : EventArgs
{
private Exception error;
private string message;
public ErrorEventArgs(Exception ex, string msg)
{
error = ex;
message = msg;
}
public Exception Error
{
get { return error; }
... | How to raise custom event from a Static Class | [
"",
"c#",
"asp.net",
""
] |
Are there any libraries out there for Java that will accept two strings, and return a string with formatted output as per the \*nix diff command?
e.g. feed in
```
test 1,2,3,4
test 5,6,7,8
test 9,10,11,12
test 13,14,15,16
```
and
```
test 1,2,3,4
test 5,6,7,8
test 9,10,11,12,13
test 13,14,15,16
```
as input, and i... | I ended up rolling my own. Not sure if it's the best implementation, and it's ugly as hell, but it passes against test input.
It uses [java-diff](http://www.incava.org/projects/java/java-diff/) to do the heavy diff lifting (any apache commons StrBuilder and StringUtils instead of stock Java StringBuilder)
```
public ... | # [java-diff-utils](http://code.google.com/p/java-diff-utils/)
> The DiffUtils library for computing
> diffs, applying patches, generationg
> side-by-side view in Java
>
> Diff Utils library is an OpenSource
> library for performing the comparison
> operations between texts: computing
> diffs, applying patches, genera... | Generate formatted diff output in Java | [
"",
"java",
"diff",
""
] |
What are the hidden features of Maven2? | You can use the settings.xml to force ALL maven builds running on your local machine to also use a locally installed maven proxy. Saving yourself and the network time.
```
<settings xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ma... | Take a look at dependency:analyze as well. | What are the hidden features of Maven2? | [
"",
"java",
"apache",
"maven-2",
"dependency-management",
""
] |
I am working on a tool where I need to convert string values to their proper object types. E.g. convert a string like `"2008-11-20T16:33:21Z"` to a `DateTime` value. Numeric values like `"42"` and `"42.42"` must be converted to an `Int32` value and a `Double` value respectively.
What is the best and most efficient app... | In terms of efficiency, yes, TryParse is generally the preferred route.
If you can know (for example, by reflection) the target type in advance - but don't want to have to use a big `switch` block, you might be interested in using `TypeConverter` - for example:
```
DateTime foo = new DateTime(2008, 11, 20);
... | `Int.TryParse` and `Double.TryParse` have the benefit of actually returning the number.
Something like `Regex.IsMatch("^\d+$")` has the drawback that you still have to parse the string again to get the value out. | How to determine if a string is a number in C# | [
"",
"c#",
".net",
"string",
"value-type",
""
] |
I am trying to come up with a best practices on project directory structure.
my latest thought is that there should be no classes in the root directory of a project. All classes must go under one of the following directories
* UI
* BusinessObjects
* BusinessLogic
* DataAccess
i would like to hear other people though... | If you're talking about C# then I would separate your DAL, BLL, GUI to different projects instead of one project. And have one solution. This will force each code file to be inside of one of the projects.
I've added an example:
* Solution: ProjectName
+ Project: DAL (Namespace: ProjectName.DAL)
- Folder: Reposi... | This [blog](http://www.hanselman.com/blog/howdoyouorganizeyourcode.aspx) should provide you with some interesting reading, despite being three years old. It might give you ideas besides those of just directory structure. | Is it OK to have code in the root of a project? | [
"",
"c#",
"directory",
"structure",
""
] |
Similar to [List<> OrderBy Alphabetical Order](https://stackoverflow.com/questions/188141/c-list-orderby-alphabetical-order), we want to sort by one element, then another. we want to achieve the functional equivalent of
```
SELECT * from Table ORDER BY x, y
```
We have a class that contains a number of sorting functi... | Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this:
```
public void SortList() {
MyList.Sort(delegate(MyClass a, MyClass b)
{
int xdiff = a.x.CompareTo(b.x);
if (xdiff != 0) return xdiff;
else return a.y... | For versions of .Net where you can use LINQ `OrderBy` and [`ThenBy`](http://msdn.microsoft.com/en-us/library/vstudio/bb534743(v=vs.100).aspx) (or `ThenByDescending` if needed):
```
using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();
```
---
Note: for .Net 2... | C# List<> Sort by x then y | [
"",
"c#",
".net",
"sorting",
""
] |
There are many editions of Eclipse for Java development. I am trying out MyEclipse and am pretty impressed with the out-of-box experience. Before I get too comfortable with it, I would like to find out if it is the best edition available. Feel free to list free or commercial packages, but for the sake of other readers,... | all of the above except the color stuff works great with **vanilla Eclipse 3.4 + Subclipse**. if you find an easy way to customize colors in Eclipse, please let us know.
Until then you're stuck with having to manually change each color. | I'm always just downloading **classic** edition and just add plugins I need. That way I keep Eclipse as lean as possible. | Best Eclipse version for Java development | [
"",
"java",
"eclipse",
"ide",
""
] |
If have a set of classes that all implement an interface.
```
interface IMyinterface<T>
{
int foo(T Bar);
}
```
I want to shove them all in a list and enumerate through them.
```
List<IMyinterface> list
foreach(IMyinterface in list)
// etc...
```
but the compiler wants to know what T is. Can I do this? How c... | There is no IMyinterface type there is only a IMyinterface`1 type which will require a type argument. You could create an IMyinterface type:-
```
interface IMyinterface { ... }
```
then inherit from it
```
interface IMyinterface<T> : IMyinterface { ... }
```
You would need to move any members you would like to use ... | If you plan to invoke a method with T in the signature, the answer is that you cannot. Otherwise you can do as anthonywjones suggests | generics and interfaces enumeration | [
"",
"c#",
".net",
"generics",
"interface",
"ienumerable",
""
] |
In Java, is there a way to have a window that is "Always on top" regardless if the user switches focus to another application? I've searched the web, and all of the solutions lean to some sort of JNI interface with native bindings. Truly this can't be the only way to do it?.. or is it? | Try this method of the `Window` class:
[Window.setAlwaysOnTop(boolean)](http://java.sun.com/javase/6/docs/api/java/awt/Window.html#setAlwaysOnTop%28boolean%29)
It works the same way as the default in the Windows TaskManager: switch to another app but it shows always on top.
This was added in Java 1.5
Sample code:
... | From my observation I found that AlwaysOnTop privilege is given to the latest process which requested to be always on top.
So, if you have an application which `setAlwaysOnTop(true)` and later another application uses this option, the privilege is given to the second application. In order to work around this I have se... | "Always on Top" Windows with Java | [
"",
"java",
"user-interface",
"swing",
"awt",
""
] |
I need a fast container with only two operations. Inserting keys on from a very sparse domain (all 32bit integers, and approx. 100 are set at a given time), and iterating over the inserted keys. It should deal with *a lot of* insertions which hit the same entries (like, 500k, but only 100 different ones).
Currently, I... | Depending on the distribution of the input, you might be able to get some improvement without changing the structure.
If you tend to get a lot of runs of a single value, then you can probably speed up insertions by keeping a record of the last value you inserted, and don't bother doing the insertion if it matches. It ... | I'm not sure I understand "a lot of insertions which hit the same entries". Do you mean that there are only 100 values which are ever members, but 500k mostly-duplicate operations which insert one of those 100 values?
If so, then I'd guess that the fastest container would be to generate a collision-free hash over thos... | Fast container for setting bits in a sparse domain, and iterating (C++)? | [
"",
"c++",
"containers",
""
] |
Which GUI framework/library would you choose if you were to start your new project **now** or in the near future?
It has to be free for commercial use and cross platform.
I have been a happy swing user, but Sun seems like pushing **swing** to deprecation, while pushing **Javafx**, which is not yet ready for prime tim... | I think that despite Sun's mismanagement, Swing is still an excellent framework. You can do a *lot* with it, especially if that "lot" involves custom rendered UI controls. If your application needs a branded LAF, or even just a few complex custom controls here and there, Swing is exactly what you want.
On the other si... | Right now, I'm either using SWT or Qt (Jambi).
Swing didn't evolve in the last, say, 10 years, bugs aren't fixed, the development has stopped in favor of JavaFX, so you won't ever see any new features, too. JavaFX will probably look great but is still vaporware and it's made by the people who let Swing starve to death... | Which Java GUI framework to choose now? | [
"",
"java",
"user-interface",
"cross-platform",
"gui-toolkit",
""
] |
Here are two chunks of code that accomplish (what I think is) the same thing.
I basically am trying to learn how to use Java 1.5's concurrency to get away from Thread.sleep(long). The first example uses ReentrantLock, and the second example uses CountDownLatch. The jist of what I am trying to do is put one thread to s... | Either approach is roughly equivalent, except that a [CountDownLatch](http://java.sun.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html) can only be released once. After that all [await()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html#await()) calls return instantly. So a [... | The lock/condition variable approach is better for this task in my opinion. There is a similar example to yours here: <http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/Condition.html>
In response to protecting a boolean. You could use volatile(<http://www.ibm.com/developerworks/java/library/j-jtp0619... | Put one thread to sleep until a condition is resolved in another thread | [
"",
"java",
"concurrency",
"locking",
"conditional-statements",
"countdownlatch",
""
] |
I have started using Linq to SQL in a (bit DDD like) system which looks (overly simplified) like this:
```
public class SomeEntity // Imagine this is a fully mapped linq2sql class.
{
public Guid SomeEntityId { get; set; }
public AnotherEntity Relation { get; set; }
}
public class AnotherEntity // Imagine this... | Rick Strahl has a nice article about DataContext lifecycle management here: <http://www.west-wind.com/weblog/posts/246222.aspx>.
Basically, the atomic action approach is nice in theory but you're going to need to keep your DataContext around to be able to track changes (and fetch children) in your data objects.
See a... | You have to either:
1) Leave the context open because you haven't fully decided what data will be used yet (aka, Lazy Loading).
or 2) Pull more data on the initial load if you know you will need that other property.
Explaination of the latter: [here](http://www.singingeels.com/Blogs/Nullable/2008/10/27/EntityFramewo... | Problem using LINQ to SQL with one DataContext per atomic action | [
"",
"c#",
"linq-to-sql",
"persistence",
"ddd-repositories",
""
] |
We're creating a web system using Java and Servlet technology (actually Wicket for the presentation layer) and we need our system to be available nearly always as our customers will be quite dependent on it.
This has lead us to look for a good book focusing on the subject or another resource which explains how to set ... | Regarding GlassFish, centralized administration through the admin GUI is a big help for environments with more than one appserver instance to manage. "Always available" is overloaded. It can be service availability with no session retention on failure, or it can mean data availability with session information backed up... | The Liferay wiki has a [high availability guide](https://www.liferay.com/web/guest/community/wiki/-/wiki/Main/High+Availability+Guide) entry outlining an architecture that could serve as a starting point. | Book/Resource about setting up load balancing and fail over for Servlet based Java web application | [
"",
"java",
"web-applications",
"load-balancing",
"redundancy",
"failovercluster",
""
] |
I need to match (case insensitive) "abcd" and an optional trademark symbol
Regex: `/abcd(™)?/gi`
See example:
```
preg_match("/abcd(™)?/gi","AbCd™ U9+",$matches);
print_r($matches);
```
When I run this, `$matches` isn't populated with anything... Not even created as an empty array. Any ideas? | How is your file encoded? PHP has got issues when it comes to unicode. In your case, try using the escape sequence `\x99` instead of directly embedding the TM symbol. | **Note:** I'm not a PHP guru. However, this seems to be an issue about character encodings. For example, your PHP file could be encoded as win-1252 (where ™ is encoded as `\x99`), and the data you are trying to match could be encoded as UTF-8 (where ™ is encoded as `\xe2\x84\xa2`), or vice versa (i.e. your file is UTF-... | Why doesn't this regular expression work in PHP? | [
"",
"php",
"regex",
""
] |
I've got the a SQL Server stored procedure with the following T-SQL code contained within:
```
insert into #results ([ID], [Action], [Success], [StartTime], [EndTime], [Process])
select
'ID' = aa.[ActionID],
'Action' = cast(aa.[Action] as int),
'Success' = aa.[Success],
'StartTime' = aa.[StartTime],
... | The following article explains how to find out if your stored procedure is recompiling:
<http://it.toolbox.com/blogs/programming-life/sql-performance-abnormal-stored-procedure-recompiles-8105>
Here's a quote from the appropriate section:
> start SQL Profiler and start a new
> trace, connect to our server and give
> a... | Just offhand, you can simplify these:
```
2 = case
when (@startDate is null) then 2
when (@startDate is not null and aa.[StartTime] >= @startDate) then 2
end
```
to this:
```
(@startDate is null OR aa.[StartTime] >= @startDate)
```
As far as the recompile ... | How can I determine whether or not a stored procedure is recompiling every time? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a couple of array's:
```
const string a_strs[] = {"cr=1", "ag=2", "gnd=U", "prl=12", "av=123", "sz=345", "rc=6", "pc=12345"};
const string b_strs[] = {"cr=2", "sz=345", "ag=10", "gnd=M", "prl=11", "rc=6", "cp=34", "cv=54", "av=654", "ct=77", "pc=12345"};
```
which i then need to parse out for '=' and then put ... | This shouldn't be too hard. Your first problem is that you don't have a fixed sized array, so you'd have to pass the size of the array, or what I'd prefer you make the arrays NULL-terminated, e.g.
`const string a_strs[] = {"cr=1", "ag=2", "gnd=U", NULL};`
Then I would write a (private) helper function that parse the ... | Probably I didn't get it correctly, but obvious solutions is to split each array element into `key` and `value` and then write lo-o-ong `if-else-if-else ...` sequence like
```
if (!strcmp(key, "cr"))
my_struct.cr = value;
else if (!strcmp(key, "ag"))
my_struct.ag = value;
...
```
You can automate the creation o... | Initializing struct, using an array | [
"",
"c++",
"c",
"parsing",
""
] |
I'm looking to generate a random number and issue it to a table in a database for a particular user\_id. The catch is, the same number can't be used twice. There's a million ways to do this, but I'm hoping someone very keen on algorithms has a clever way of solving the problem in an elegant solution in that the followi... | No your algorithm is not scalable. What I've done before is to issue numbers serially (+1 each time) and then pass them through an XOR operation to jumble the bits thus giving me a seemingly random numbers. Of course they aren't really random, but they look so to users eyes.
---
**[Edit]** Additional information
Thi... | Why don't you just use a GUID? Most languages should have a built-in way to do this. It's guaranteed to be unique (with very reasonable bounds). | Algorithm for generating a random number | [
"",
"php",
"mysql",
"algorithm",
"random",
"pseudocode",
""
] |
For example, I hate typing things like:
```
$x = mysql_escape_string(stripslashes($_GET['x']));
```
Is there a way to alias those two functions in init.php or something without writing a separate function that takes one argument and returns that argument with those functions applied to it?
My C/C++ is not very good,... | This should do the trick :
```
// Macros
$mes = "mysql_escape_string";
$ss = "stripslashes";
// Using your macros
$x = $mes($ss($_GET['x']));
```
Though I don't recommend coding like this at all.
I'm just answering the question since you said you didn't want to create any new function and get a "#define"-like funct... | I hope your example is not representative of your project.
1. `stripslashes()` shouldn't be necessary - if you find it is, turn off `magic_quotes_gpc` in your php.ini.
2. You should be using `mysql_real_escape_string()` (or a `prepare`/`execute` pair) instead of `mysql_escape_string()` and it should be where your SQL ... | Is it possible to "symlink" a function in PHP easily - or alias the name to something else? | [
"",
"php",
""
] |
We have a dotnet web service that a java using customer wants to connect to. What is the best technology for them to use? Axis or Metro, or something else? | Theoretically you could do this with any standards compliant framework. In practice, the generated code (with the default settings) by some tools may not work for you. You may need for example to modify a namespace or add a SOAP header. You can do this for example with Axis2 and CXF, but some extra configuration is nee... | WSDL is a standard language following the protocol in a correct way the technology shouldn't mind.
only if this implementation requires to meet the time to market of your client. in that case use the one that can be implement more quickly. | What is the best way to connect to a DotNet web service from java? | [
"",
"java",
".net",
"web-services",
"wsdl",
""
] |
How can I open a web-page and receive its cookies using PHP?
**The motivation**: I am trying to use [feed43](http://www.feed43.com) to create an RSS feed from the non-RSS-enabled HighLearn website (remote learning website). I found the web-page that contains the feed contents I need to parse, however, it requires to l... | For a server-side HTTP client you should use the [cURL](https://www.php.net/curl) module. It will allow you to persist cookies across multiple requests. It also does some other neat things like bundling requests (curl\_multi) and transparently handling redirects.
When it comes to returning a session to your user, I do... | I've used the [Scriptable Browser](http://simpletest.sourceforge.net/en/browser_documentation.html) component from Simpletest for this kind of screen scraping before. It does a pretty good job of simulating a browser.
You don't need to pass the session on to the real client (Even though it *may* be possible, depending... | Simulating a cookie-enabled browser in PHP | [
"",
"php",
"curl",
"curl-multi",
"redirectwithcookies",
""
] |
I'm working on an app that takes data from our DB and outputs an xml file using the FOR XML AUTO, ELEMENTS on the end of the generated query, followed by an XSLT to transform it the way we want. However in a particular case where we are generating some data using an sql scalar function, it always puts that element into... | Doing some further reserach, as of now it appears running a db in 2000 compat mode while on a 2005 sql server this problem is created, will not pin this until confirmed. | I would try to get rid of the sub query parts "(SELECT..." and do regular joins, like:
```
SELECT table1.column1, table1.column2, ..., envelope.column21, ...
FROM table1 LEFT JOIN envelope on table1.column1 = envelope.column1 ...
WHERE envelope.column21 = 8
FOR XML AUTO, ELEMENTS
```
To be clearer I ommitted most ... | SQL Server and generatd xml with xml auto, elements | [
"",
"sql",
"sql-server",
"xml",
"t-sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.