Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am facing strange issue on Windows CE:
Running 3 EXEs
1)First exe doing some work every 8 minutes unless exit event is signaled.
2)Second exe doing some work every 5 minutes unless exit event signaled.
3)Third exe while loop is running and in while loop it do some work at random times.
This while loop continues unt... | Put the while loop in the third EXE to Sleep each time through the loop and see what happens. Even if it doesn't fix this particular probem, it isn't ever good practice to poll with a while loop, and even using Sleep inside a loop is a poor substitute for a proper timer. | (From Memory) Processes in Windows CE run until completion if there are no higher priority processes running, or they run for their time slice (100ms) if there are other processes of equal priority running. I'm not sure if Windows CE gives the process with the active/foreground window a small priority boost (just like ... | Strange issue running infinite while loop in EXE | [
"",
"c++",
"windows-mobile",
""
] |
I know about code-behind files, but what is the best real-world way of Designers that are using DreamWeaver or other Design Tools to work with Visual Studio programmers?
For example, say you have a basic website with user interface forms hitting the database... the database work is definitely done by the developer but... | Use another approach like [MVC](http://en.wikipedia.org/wiki/Model-view-controller), separate your design from your logic. Like this every member (designer / developer) of the team can focus on what they do best.
MVC implementations: [link](http://www.asp.net/mvc/) / [link](http://www.castleproject.org/monorail/index.... | The best way is to make sure that your designers have some knowledge of what kind of HTML they will be working with.
Every ASP.NET developer is aware of MS-HTML, that lovely nesting of HTML tables, but designers aren't. Designers have their own requirements to meet and they'll do them in the best manner possible. Sadl... | What's the best way to integrate Designers using Dreamweaver with Visual Studio C# developers? | [
"",
"c#",
"dreamweaver",
""
] |
I'm making a Java application with an application-logic-thread and a database-access-thread.
Both of them persist for the entire lifetime of the application and both need to be running at the same time (one talks to the server, one talks to the user; when the app is fully started, I need *both* of them to work).
Howev... | I would really recommend that you go through a tutorial like [Sun's Java Concurrency](http://java.sun.com/docs/books/tutorial/essential/concurrency/) before you commence in the magical world of multithreading.
There are also a number of good books out (google for "Concurrent Programming in Java", "Java Concurrency in ... | Use a [CountDownLatch](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html) with a counter of 1.
```
CountDownLatch latch = new CountDownLatch(1);
```
Now in the app thread do-
```
latch.await();
```
In the db thread, after you are done, do -
```
latch.countDown();
``` | How to make a Java thread wait for another thread's output? | [
"",
"java",
"multithreading",
""
] |
I have a quite big XML output from an application. I need to process it with my program and then feed it back to the original program. There are pieces in this XML which needs to be filled out our replaced. The interesting part looks like this:
```
<sys:customtag sys:sid="1" sys:type="Processtart" />
<sys:tag>valu... | i believe the option to use is `RegexOptions.Singleline` instead of `RegexOptions.Multiline` ([src](http://www.regular-expressions.info/dot.html)). allowing (.) to match newlines should work in your case.
> ...the mode where the dot also matches newlines is called "single-line mode". This is a bit unfortunate, because... | The regex char "." never matches a newline, even with `MultiLine` option is set.
instead, you should use `[\s\S]` or other combination with matches anything.
The `MultiLine` option only modifies the behaviour of ^ (begin-of-line instead fo begin-of-string) and $ (end-of-line instead of end-of-string)
BTW: Indeed, reg... | Cannot get regular expression work correctly with multiline | [
"",
"c#",
"regex",
"multiline",
""
] |
Not wanting to re-invent the wheel or anything, I was wondering if there's a plugin out there a field or form validation plugin that works with Prototype that you can recommend from your own experience and why? | I like Ben Keen's Really Simple Validation component.
Features I like:
All the validation rules can be kept within javascript so you're not adding class="required" to your HTML code.
You can display error messages in a javascript alert box or with HTML text.
Adding your own extensions is easy.
<http://www.benjamin... | I like [wforms](http://www.formassembly.com/wForms/). Example:
```
<input type="text" name="myDate" class="validate-date"/>
``` | What is the best field validation plugin for Prototype? | [
"",
"javascript",
"forms",
"validation",
"prototypejs",
""
] |
If I have the string `.....ZZ..ZZ.....` or `.Z.1.Z.23Z.4.Z55`,
Is there an easy way of shifting all `Z`characters in the string one space right of the current position?
Some additional test strings are:
* `.Z`
* `Z.`
* `ZZ.`
* `.ZZ`
* `Z`
* `ZZ`
* `ZZZ`
I think a few of the higher voted answers to this question (in... | Just iterate through the text and swap characters:
```
int main ()
{
char text[] = "...Z.Z.Z...", temp;
int text_len = strlen (text), i;
for (i = text_len - 1; i >= 0; i--)
{
if (text[i] == 'Z')
{
temp = text[i+1];
text[i+1] = text[i];
tex... | Building on previously posted code here. Function gets str and strlen, overwrites str. Works also with subsequent Z. Going forward for speed improvement with subsequent Z.
```
void move_z_right (char* str, int strlen) {
for (unsigned int i = 0; i < strlen - 1; ++i)
{
if (str[i] == 'Z')
{
... | Easy way to shift specific characters in a string in C++? | [
"",
"c++",
"string",
"character",
""
] |
I can't figure out how to define the default constructor (when it exists overloads) for a type in StructureMap (version 2.5) by code.
I want to get an instance of a service and the container has to inject a Linq2Sql data context instance into it.
I wrote this in my 'bootstrapper' method :
```
ForRequestedType<MyData... | You can specify a constructor with the ConstructedBy(). Please try this:
```
ForRequestedType<MyDataContext>().TheDefault.
Is.ConstructedBy(() => new MyDataContext());
```
This worked for me. | I'm assuming you'd also need to set the object lifetime (InstanceScope) if you are using Linq2Sql. I'd suggest using this code because it give you a little more flexibility.
```
ForRequestedType< MyDataContext >()
.CacheBy( InstanceScope.PerRequest )
.TheDefault.Is.OfConcreteType< MyDataContext... | How to define a default constructor by code using StructureMap? | [
"",
"c#",
"inversion-of-control",
"structuremap",
""
] |
I may be going about this backwards...
I have a class which is like a document and another class which is like a template. They both inherit from the same base class and I have a method to create a new document from a template (or from another document, the method it is in the base class).
So, if I want to create a new... | If you want to be able to do anything other than create a new object just from the code in the constructor, don't use a constructor in the first place.
Do you really need an Instance constructor taking an int? Why not turn it into a static factory method:
```
public static Instance CreateInstance(int id)
{
MyTemp... | You cannot recreate 'this' from either the constructor or any other method. You can create another object and copy contents, but I would instead make the factory public. Define a factory class that has three createDocument() methods, one for a blank document, one for a document from the DB and a third one from a templa... | Call a factory from Constructor to get a new version of "this" | [
"",
"c#",
"constructor",
""
] |
Let's say I have a **Base** class and several **Derived** classes. Is there any way to cast an object to one of the derived classes without the need to write something like this :
```
string typename = typeid(*object).name();
if(typename == "Derived1") {
Derived1 *d1 = static_cast< Derived1*>(object);
}
else if(typ... | Don't.
Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented.
Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses.
You left out the most important part of your example. The useful,... | You can use `dynamic_cast` and test for NULL, but I'd **strongly** consider refactoring the code instead.
If you need subclass-specific handling, [Template Method](http://en.wikipedia.org/wiki/Template_method_pattern) might be helpful, but without knowing what you're trying to achive, it's only a vague guess. | C++ casting programmatically : can it be done? | [
"",
"c++",
"casting",
""
] |
I'm trying to setup the Entity Framework with SQL Server 2008. I'm using Guids for the keys on my tables. Is there a way to set it up so the keys are automatically generated by the database? I tried setting "RowGuid" to true and also set the column's default value to be "(newid())". Either way the mapped class still ne... | [Not yet](http://blogs.msdn.com/dsimmons/pages/ef-faq-entity-services.aspx#Section_17):
> **17.4.Can I use a server-generated guid as my entity key?**
>
> Unfortunately, in v1 of the EF this is not supported. While it is possible with SQL Server to have a column of type “uniqueidentifier” and to set it’s default value... | Personally, I think that anyone who is using EF would be willing to give up compatibility with SQL Server 2000 to get the features they need. It seems like every halfway non-trivial thing that I need to do in EF is unsupported due to the fact that they have to keep compatibility with SQL Server 2000.
When will it ever... | Entity Framework Guid | [
"",
"c#",
"asp.net",
"entity-framework",
""
] |
I am building a PHP application in CodeIgniter. CodeIgniter sends all requests to the main controller: `index.php`. However, I don't like to see `index.php` in the URI. For example, `http://www.example.com/faq/whatever` will route to `http://www.example.com/index.php/faq/whatever`. I need a reliable way for a script to... | The [PHP documentation](http://ca.php.net/manual/en/reserved.variables.server.php) can tell you the difference:
> *'PHP\_SELF'*
> > The filename of the currently executing script, relative to the document root. For instance, *$\_SERVER['PHP\_SELF']* in a script at the address *http://example.com/test.php/foo.bar* wou... | Some practical examples of the differences between these variables:
Example 1.
PHP\_SELF is different from SCRIPT\_NAME *only* when requested url is in form:
<http://example.com/test.php/foo/bar>
```
[PHP_SELF] => /test.php/foo/bar
[SCRIPT_NAME] => /test.php
```
(this seems to be the only case when PATH\_INFO con... | PHP_SELF vs PATH_INFO vs SCRIPT_NAME vs REQUEST_URI | [
"",
"http",
"php",
"codeigniter",
""
] |
What is the best way to build a loopback URL for an AJAX call? Say I have a page at
```
http://www.mydomain.com/some/subdir/file.php
```
that I want to load with an AJAX call. In Firefox, using jQuery this works fine:
```
$.post('/some/subdir/file.php', ...);
```
Safari/WebKit tries to interpret this as a location ... | Wow, that's pretty poor of Safari/WebKit, IMO.
You could observe document.href, count the slashes, and add that many "../" to the beginning of your URL. | You could have the server insert its own URL as a javascript variable when it serves up the page, then use that variable as part of your Ajax calls. It would then be both secure and automatic. | Loopback jQuery AJAX Request | [
"",
"javascript",
"jquery",
"ajax",
""
] |
since JTree & TreeModel don't provide tooltips straight out-of-the-box, what do you think, what would be the best way to have item-specific tooltips for JTree?
Edit: (Answering my own question afterwards.)
@Zarkonnen: Thanks for the getTooltipText idea.
I found out another (maybe still a bit nicer) way with overridi... | See [getTooltipText](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTree.html#getToolTipText(java.awt.event.MouseEvent)) on JTree. This should allow you to show tooltips depending on what in the tree is being hovered over. (Do read the docs though, you need to register the JTree with the ToolTipManager.) | Yeah, you can use `onMouseMoved` and then use a method (I don't remember the name) that tells you in which node you are over. If you get null, obviously then you are not over a node. | Best way to implement tooltips for JTree? | [
"",
"java",
"swing",
"tooltip",
"jtree",
""
] |
Need a function like:
```
function isGoogleURL(url) { ... }
```
that returns true iff URL belongs to Google. No false positives; no false negatives.
Luckily there's [this](http://www.google.com/supported_domains) as a reference:
> .google.com .google.ad .google.ae .google.com.af .google.com.ag .google.com.ai .googl... | Here is an updated version of Prestaul's answer which solves the two problems I mentioned in the comment there.
```
var GOOGLE_DOMAINS = ([
'.google.com',
'.google.ad',
'.google.ae',
'.google.com.af',
'.google.com.ag',
'.google.com.ai',
'.google.am',
'.google.it.ao',
'.google.com.ar... | All the domains end in either "google.xx", "google.co.xx", or "google.com.xx" except "google.it.ao" and "google.com", so if you just look at the domain, this regular expression should work for most cases (it's not perfect, but it accepts all the listed domains, and rejects most other valid domains that happen to includ... | JavaScript function to match only Google URLs | [
"",
"javascript",
"greasemonkey",
""
] |
I'm still trying to get my head around using Java's generics. I have no problems at all with using typed collections, but much of the rest of it just seems to escape me.
Right now I'm trying to use the JUnit "PrivateAccessor", which requires a Class[] argument with a list of all the argument types for the private meth... | The first problem you have is that you should be using
```
Class<?>[] args = new Class[]
```
instead of
```
Class<? extends Object>[] args = new Class<? extends Object>[]
```
[This](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104) explains why.
Your second problem is that you s... | This is the correct syntax:
```
Class<?>[] paramTypes = new Class[]{ Collection.class, ArrayList.class };
``` | Convert Class[] to generics? | [
"",
"java",
"generics",
""
] |
Our team is using a SecureRandom to generate a list of key pairs (the SecureRandom is passed to a KeyPairGenerator). We cannot agree on which of the following two options to use:
1. Create a new instance every time we need to generate a key pair
2. Initialize a static instance and use it for all key pairs
Which appro... | Unlike the `java.util.Random` class, the `java.security.SecureRandom` class must produce non-deterministic output on each call.
What that means is, in case of `java.util.Random`, if you were to recreate an instance with the same seed each time you needed a new random number, you would essentially get the *same* result... | For [SecureRandom](http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/security/SecureRandom.html) you would want to consider occasionally reseeding ([using system entropy in most cases](https://bugs.java.com/bugdatabase/view_bug?bug_id=6202721)) via a call like so:
```
mySecureRandom.setSeed(mySecureR... | SecureRandom: init once or every time it is needed? | [
"",
"java",
"security",
"random",
"cryptography",
""
] |
I'm writing an application which has to be configurable to connect to Oracle, SQL Server and MySQL depending on client whim.
Up till now I'd been planning on using the JDBC-ODBC bridge and just connecting to the databases using different connection strings.
**I'm told this is not very efficient.**
1. Is there a patt... | I would suggest that you make it configurable and include the three drivers. You can use a pattern like this: Create a super class (lets call it DAO) that provides the functionality of connecting to the database. This could be abstract.
Create a concrete sub class for each type of database that you wish to connect to.... | If you're careful (and you test), you can do this with straight JDBC and just vary the driver class and connection information. You definitely want to stay away from the JDBC-ODBC bridge as it's generally slow and unreliable. The bridge is more likely to behave differently across dbs than JDBC is.
I think the DAO path... | Pattern for connecting to different databases using JDBC | [
"",
"java",
"jdbc",
""
] |
As I use the web, I regularly get runtime errors (usually javascript) being reported via popups. This can make for a really unsatisfying user experience on many otherwise excellent websites and also makes me wonder what functionality I am not getting access to.
Why is this such a common issue? Is this down to a lack o... | Its a number of issues.
1. Many web page creators copy and paste JavaScript code from the web. They are not programmers and may not appreciate the nuances of the language.
2. Lack of good testing frameworks (At least I don't know any). For Java we have JUNIT and .NET NUNIT etc. Its difficult to automate JavaScript tes... | I put it down to a lack of testing. | Web page runtime errors | [
"",
"javascript",
"internet-explorer-7",
"user-experience",
"runtime-error",
""
] |
How can I make a variable (object) available for the whole lifetime of the webservice?
Static variable seem to work but is there an other way to do it? | Static variables exist for the lifetime of the App Domain that contains them. In the case of a web service, this is usually the ASP.Net Worker Process. What that means is that when IIS decides to cycle the worker process, your static variable will be gone. This may be what you want, in which case it is probably a good ... | A singleton utilizing HttpApplicationState should work a treat | Web service variable shared for the lifetime of the webservice? | [
"",
"c#",
"web-services",
".net-2.0",
"c#-2.0",
""
] |
I'm attempting to register an anonymous function when a user clicks a cell in an HTML table. Here's some of the raw, unadulterated code:
```
document.getElementById(
"course"+displayed_year_index+occurrences_indices[displayed_year_index]).onclick =
eval("function() {PrintReceipt("+result.years[result_year_... | IMHO closures should not be used in this case and there is no need to create a new function for each onlick (uses much more memory than necessary) and eval is the wrong answer.
You know that the element you are getting with getElementById is an object and that you can assign values to it?
```
for ( /* your definition... | Have you tried something like this?
```
document.getElementById('course' + displayed_year_index + occurences_indices[displayed_year_index]) =
function (nr)
{
return function () { PrintReceipt(nr) }
} (result.years[result_year_index].rul_code);
```
Can you please post the loop to help us find the p... | Firefox Javascript Events Anonymous Function | [
"",
"javascript",
"firefox",
"event-handling",
"closures",
"anonymous-function",
""
] |
We have a simple project where we read data from a socket and we want to populate a table with the coming data, but we can't find a way to add rows to a yet created `JTable` object, we can only find how to add rows at creation time of the table.
Is it possible to add rows dynamically to a `JTable`, or there is a bette... | You should create a custom [`TableModel`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/table/TableModel.html). A `JTable` doesn't actually store the rows, it always delegates that to a `TableModel`. To help you implementing it, you should make use of [`AbstractTableModel`](http://java.sun.com/j2se/1.5.0/docs/api... | If you use the default table model for a JTable then you can add rows with following code
```
if ( dest+1 < table.getRowCount()-1 )
( (DefaultTableModel) table.getModel() ).insertRow(dest+1, getValuesForNewRow());
else
( (DefaultTableModel) table.getModel() ).addRow(getValuesForNewRow());
``` | Adding rows to a JTable | [
"",
"java",
"swing",
""
] |
This is one is for any of you Doctrine users out there. I have a PHP CLI daemon process that checks a table every n seconds to find entries that haven't been processed. It's basically a FIFO. Anyways, I always exceed the memory allocated to PHP becuase Doctrine does not free it's resources. To combat this problem it pr... | The problem is, that `free()` does not remove the Doctrine objects from memory but just eliminates the circular references on those objects, making it possible for the garbage collector to cleanup those objects. Please see [23.6 Free Objects](http://www.doctrine-project.org/documentation/manual/1_0?chapter=improving-pe... | Doctrine\_Query also has a free() method, at the moment you are just calling free() on your Doctrine\_Collection, eg, try:
```
$query = Doctrine_Query::create()
->from('SubmissionQueue s')
->where('s.time_acted_on IS NULL')
->orderby('s.time_queued')
->limit(1);
$r... | Why is PHP Doctine's free() not working? | [
"",
"php",
"memory",
"orm",
"doctrine",
""
] |
I am using JQuery to post with AJAX to another ASP page. Do I need this ASP page to return a full html page. Or can I just have it send back a value ( I just need a status ) . Here is my function.
```
$.ajax({
url: "X.asp",
cache: false,
type: "POST",
data: queryString,
success: fun... | If it's just a simple value you need, I'd simple use Json (JQuery has a dedicated method for that : [$.getJSON()](http://docs.jquery.com/Ajax/jQuery.getJSON)).
So no, you don't need your ASP page to return a full html page, just the value in simple JSON notation. | You can return anything you want (even single character), but remember to change content type of your page X.asp to ContentType="text/plain" if you don't want to return HTML. | AJAX - Do I need to return a full HTML document on the server side? | [
"",
"javascript",
"jquery",
"ajax",
"asp-classic",
""
] |
In C#, the questions of what types to create, what members they should have, and what namespaces should hold them, are questions of OO design. They are not the questions I'm interested in here.
Instead, I want to ask how you store these in disk artifacts. Here are some example rules:
* Put all of an assembly's types ... | Whatever you do, just PLEASE do it consistently. I don't believe there is any one single answer (though there are a few wrong ones). But just make sure you stay true to your form as this will be the key for your successor(s) to find things easily. | Currently I do:
* One assembly for production code + unit tests
* directory structure mimics namespaces
* one type per file
* nested types get their own file, using `partial` types. That is:
```
// ------ C.cs
public partial class C : IFoo
{
// ...
}
// ------ C.Nested.cs
partial class C
{
public class Nest... | How do you organize C# code in to files? | [
"",
"c#",
"code-organization",
""
] |
I'm looking for Java code that can be used to generate sound at runtime - NOT playback of existing sound files.
For example, what's the best code for generating a sawtooth waveform at 440 Hz for a duration of 2 milliseconds? **Source code appreciated!**
I remember my Commodore 128 had a simple Sound command that took... | You can easily generate sampled sound data in Java and play it back without using native code. If you're talking MIDI things may get tricky, but I've not dabbled in that area.
To generate sampled sound data, you have to thing of the process backwards. We're going to act like the A-to-D and sample a continuous sound fu... | Here is a sample that might help. This generates sin waves:
```
package notegenerator;
import java.io.IOException;
/**
* Tone generator and player.
*
* @author Cesar Vezga vcesar@yahoo.com
*/
public class Main {
public static void main(String[] args) throws IOException {
Player player = new Player();
... | How to generate sound effects in Java? | [
"",
"java",
"audio",
""
] |
I'd like to serialize some LINQ generated objects and store them in a table as a binary field (Never you mind why). I'd like to be able to write some code that looks something like this:
```
SerialTestDataContext db = new SerialTestDataContext();
relation_table row = db.relation_tables.First();
MemoryStream memStrea... | With linq-to-sql (from tags), then yes: you can mark the dmbl as serializable, which uses the [DataContract]/[DataMember] approach. You do this by setting the "Serialization Mode" to "Unidirectional" in the designer, or you can do it in the dbml itself:
```
<Database ... Serialization="Unidirectional">...
```
You can... | Following Marc Gravell's advice I wrote the following two blocks of code which worked beautifully:
```
relation_table row = db.relation_tables.First();
MemoryStream memStream = new MemoryStream();
NetDataContractSerializer ndcs = new NetDataContractSerializer();
ndcs.Serialize(memStream, row);
byte[] stuff = memStre... | Is it possible to Serialize a LINQ object? | [
"",
"c#",
"linq",
"linq-to-sql",
"serialization",
""
] |
My function is pretty much a standard search function... I've included it below.
In the function I have 1 line of code responsible for weeding out Repart NTFS points.
```
if (attributes.ToString().IndexOf("ReparsePoint") == -1)
```
The problem is now I am getting an error
`Access to the path 'c:\System Volume Inform... | Nobody has permission to access System Volume Information except the SYSTEM account. So either change the permissions on the directory. Or much, much better catch the exception and go on. | I'm not sure what the answer to the question is, but *please* change your attribute check to use proper bitwise operations!
```
if (attributes.ToString().IndexOf("ReparsePoint") == -1)
```
... is much more correctly written as ...
```
if ((attributes & FileAttributes.ReparsePoint) == 0)
``` | What is the best way to check for reparse point in .net (c#)? | [
"",
"c#",
".net",
"ntfs",
"reparsepoint",
""
] |
I have a unit test where I have statically defined a quite large byte array (over 8000 bytes) as the byte data of a file I don't want to read every time I run my unit test.
```
private static final byte[] FILE_DATA = new byte[] {
12,-2,123,................
}
```
This compiles fine within Eclipse, but when compiling v... | Methods in Java are restricted to 64k in the byte code. Static initializations are done in a single method (see [link](http://www.mail-archive.com/help-bison@gnu.org/msg01990.html))
You may try to load the array data from a file. | You can load the byte array from a file in you `@BeforeClass` static method. This will make sure it's loaded only once for all your unit tests. | javac error "code too large"? | [
"",
"java",
"compiler-construction",
"ant",
""
] |
Is there a **JavaScript** equivalent of **Java**'s `class.getName()`? | > Is there a JavaScript equivalent of Java's `class.getName()`?
***No***.
**ES2015 Update**: [the name of `class Foo {}` is `Foo.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Function_names_in_classes). The name of `thing`'s class, regardless of `thing`'s type, ... | Jason Bunting's answer gave me enough of a clue to find what I needed:
```
<<Object instance>>.constructor.name
```
So, for example, in the following piece of code:
```
function MyObject() {}
var myInstance = new MyObject();
```
`myInstance.constructor.name` would return `"MyObject"`. | Get the name of an object's type | [
"",
"javascript",
""
] |
Lets say you need to attach some JavaScript functionality to an ASP.NET User Control of which there might be multiple instances on any given page. Because JavaScript has shared global state, what techniques can you use to keep the client state and behavior for each instance of a control separate? | Well, the main thing you can do is make sure your JavaScript functions are abstract enough that they are not coupled to specific instances of HTML controls - have them accept parameters that allow you to pass various instances of objects in.
The JavaScript that does whatever magic you need to be done should only exist... | ```
function <%=this.ClientID %>_myButton_onclick()
{
DoSomething();
}
```
and
```
<button id="myButton" onclick="<%=this.ClientID %>_myButton_onclick()">
```
Notice in this case the control is a regular HTML control. | How do you handle attaching JavaScript to UserControls in ASP.NET and keep multiple instance isolated? | [
"",
"asp.net",
"javascript",
""
] |
Is there a way to execute a query(containing built in DB function) using PreparedStatement?
Example:
insert into foo (location) values (pointfromtext('12.56666 13.67777',4130))
Here pointfromtext is a built in function. | By what I've seen, the first parameter on pointfromtext function is a string, and the second a number. So, try the following:
```
PreparedStatement preparedStatement = getConnection().prepareStatement("insert into map_address (location) values(pointfromtext('POINT(' || ? || ' ' || ? || ')',4130))");
preparedStatement.... | Sure, that should work.
If not, what is your database system, and can you run the exact same command from the SQL command line? | JDBC built in functions and prepared statements | [
"",
"java",
"jdbc",
""
] |
I have 2 tables event + event\_artist
## event
```
eventId | eventName
-------------------
1 , gig1
2, gig2
```
## event\_artist
```
eventId, artistName
-------------------
1, Led Zip
1, The Beatles
```
ie Led Zep and the Beatles are both playing @ Gig1
I need to create the SQl to bind to a gridview ( you... | Saw this in SQL Server Magazine- not great, and the total list will have an upper length limit, but:
```
drop table event
go
drop table event_artist
go
create table event (eventid int, eventname varchar(255))
go
create table event_artist (eventid int, artistname varchar(255))
go
insert into event values (1, 'gig1'... | SQL Server doesn't have anything built in to concatenate values in one statement like that. You could build the strings, but it has to be done one at a time.
However, you can get around this by building your own [custom aggregate function](https://stackoverflow.com/questions/43940/custom-aggregate-functions-in-ms-sql-... | Inner select on one to many | [
"",
".net",
"sql",
"sql-server",
"t-sql",
""
] |
I've got a section of code on a b2evo PHP site that does the following:
```
$content = preg_replace_callback(
'/[\x80-\xff]/',
create_function( '$j', 'return "&#".ord($j[0]).";";' ),
$content);
```
What does this section of code do? My guess is that it strips out ascii characters between 128 and 256, but ... | Not really stripping, it replaces high-Ascii characters by their entities.
See [preg\_replace\_callback](http://fr.php.net/manual/en/function.preg-replace-callback.php "PHP: preg_replace_callback - Manual").
create\_function is used to make an anonymous function, but you can use a plain function instead:
```
$conte... | It's `create_function` that's leaking your memory - just use a normal function instead and you'll be fine.
The function itself is replacing the characters with numeric HTML entities (`&#xxx;`) | what does this preg_replace_callback do in PHP? and how do I stop it leaking memory? | [
"",
"php",
"preg-replace-callback",
"create-function",
""
] |
Is their a way to use a non-member non-friend function on an object using the same "dot" notation as member functions?
Can I pull a (any) member out of a class, and have users use it in the same way they always have?
Longer Explanation:
[Scott Meyers](http://www.ddj.com/cpp/184401197), Herb Sutter, et all, argue tha... | You *can* use a single syntax, but perhaps not the one you like. Instead of placing one insert() inside your class scope, you make it a friend of your class. Now you can write
```
mystring s;
insert(s, "hello");
insert(s, other_s.begin(), other_s.end());
insert(s, 10, '.');
```
For any non-virtual, public method, it'... | Yes, it means that part of the interface of an object is composed of non member functions.
And you're right about the fact it involves the use of the following notation, for an object of class T:
```
void T::doSomething(int value) ; // method
void doSomething(T & t, int value) ; // non-member non-friend function
... | non-member non-friend function syntax | [
"",
"c++",
"class-design",
""
] |
There's this program, pdftotext, that can convert a pdf file to a text file. To use it directly on the linux console:
```
pdftotext file.pdf
```
That will generate a file.txt on the same directory as the pdf file. I was looking for a way to do it from inside a php program, and after some googling I ended with two com... | It's probably a permissions issue, but try this instead:
```
<?php
system('pdftotext file.pdf 2>&1');
?>
```
The `2>&1` redirects stderr to stdout, so any error messages will be printed. It should be pretty easy to fix from then on. | install this. it solved the problem for me.
<http://www.ssforge.com/ssforge-standard/onlinehelp/help/faq/libstdc.html>
now, pdftotext works great. | Converting pdf files to txt files with php | [
"",
"php",
"pdf",
"text-files",
""
] |
I'm passing a reference of a form to a class. Within this class I believed I could use `formRef->Controls["controlName"]` to access properties on the control.
This works for a few labels, but on a button I receive a "Object reference not set to an instance of an object." when I try to change the Text property.
Help o... | I did this, and it's working. Could possibly be safer as I can check if the control actually exists...
```
array<Control^>^ id = myForm->Controls->Find("myButton", true);
id[0]->Text = "new text";
```
I think the reason it breaks is that the button is on another panel. I didn't think of that when I posted. The new so... | That suggests that the control with the given name wasn't found.
Don't forget that the name of the control isn't necessarily the same as its ID in the designer. Check the actual name against the one you're using to look it up with. | Modifying controls with Form.Controls | [
"",
".net",
"c++",
"winforms",
""
] |
This is my code:
```
internal enum WindowsMessagesFlags {
WM_EXITSIZEMOVE = 0x00000232,
WM_DISPLAYCHANGE = 0x0000007e,
WM_MOVING = 0x00000216,
}
protected override void WndProc(ref Message m) {
switch(m.Msg) {
case (int)WindowsMessagesFlags.WM_DISPLAYCHANGE:
Fix... | Sort of - cast m.Msg instead:
```
protected override void WndProc(ref Message m) {
switch((WindowsMessagesFlags) m.Msg) {
case WindowsMessagesFlags.WM_DISPLAYCHANGE:
FixWindowSnapping();
break;
case WindowsMessagesFlags.WM_EXITSIZEMOVE:
SaveWindowProp... | What is Message.Msg defined as?
I'm betting it is Int32.
I'm also betting WindowsMessagesFlags is your type, but Message is from the framework.
Which means you're using your own enum with a framework-built object, and of course they are going to have some incompatibilities regarding types.
An enum is a strong type,... | Why do I have to cast enums to int in C#? | [
"",
"c#",
"enums",
"casting",
"int",
""
] |
I'm writing a function that fishes out the src from the first image tag it finds in an html file. Following the instructions in [this thread](https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php) on here, I got something that seemed to be working:
```
preg_match_all('#<im... | These two lines of PHP code should give you a list of all the values of the src attribute in all img tags in an HTML file:
```
preg_match_all('/<img\s+[^<>]*src=["\']?([^"\'<>\s]+)["\']?/i', $content, $result, PREG_PATTERN_ORDER);
$result = $result[1];
```
To keep the regex simple, I'm not allowing file names to have... | Most likely because the "XML" being picked up by the regex isn't proper XML for whatever reason. I would probably go for a more complicated regex that would pull out the src attribute, instead of using SimpleXML to get the src. This REGEX might be close to what you need.
```
<img[^>]*src\s*=\s*['|"]?([^>]*?)['|"]?[^>]... | Why is this regex returning errors when I use it to fish img src's from HTML? | [
"",
"php",
"html",
"xml",
"regex",
"simplexml",
""
] |
I can understand wanting to avoid having to use a cursor due to the overhead and inconvenience, but it looks like there's some serious cursor-phobia-mania going on where people are going to great lengths to avoid having to use one.
For example, one question asked how to do something obviously trivial with a cursor and... | The "overhead" with cursors is merely part of the API. Cursors are how parts of the RDBMS work under the hood. Often `CREATE TABLE` and `INSERT` have `SELECT` statements, and the implementation is the obvious internal cursor implementation.
Using higher-level "set-based operators" bundles the cursor results into a sin... | Cursors make people overly apply a procedural mindset to a set-based environment.
And they are **SLOW**!!!
From [SQLTeam](http://www.sqlteam.com/article/cursors-an-overview):
> Please note that cursors are the
> SLOWEST way to access data inside SQL
> Server. The should only be used when
> you truly need to access o... | Why do people hate SQL cursors so much? | [
"",
"sql",
"database-cursor",
""
] |
## Setup
I have a website that draws RSS feeds and displays them on the page. Currently, I use percentages on the divs that contain each feed, so that multiples can appear next to each other.
However, I only have two next to each other, and if the window resizes, there can be some ugly empty space on the screen.
## ... | You probably cannot get what you want with just CSS/HTML, but you can get somewhat close.
A trick I used for a photo album is this:
1. Make sure each feed has a fixed width, I would recommend something like '20em';
2. Make sure each feed has the same height.
3. Float everything left.
Because each div has the same di... | you might be able to do this with lists; i've never tried it, so i'm not sure.
if you make list items display:inline, the list becomes horizontal instead of vertical. from there, if you stuff the list into a containing element and fiddle with the padding and margins, you may be able to get the list to line-warp, like ... | Dynamic resizing / repositioning of divs for multi-column viewing | [
"",
"php",
"html",
"css",
"styling",
"dynamic-css",
""
] |
I need to spawn a process in Java (under Linux exclusively) that will continue to run after the JVM has exited. How can I do this?
Basically the Java app should spawn an updater which stops the Java app, updates files and then starts it again.
I'm interested in a hack & slash method to just get it working as well as ... | If you're spawning the process using [`java.lang.Process`](http://java.sun.com/javase/6/docs/api/java/lang/Process.html) it should "just work" - I don't believe the spawned process will die when the JVM exits. You might find that the Ant libraries make it easier for you to control the spawning though. | It does actually "just work", unless you're trying to be clever.
My wrapped java.lang.Process was trying to capture the script's output, so when the JVM died, the script didn't have anywhere to send output so it just dies. If I don't try to capture the output, or the script doesn't generate any or redirects everything... | Spawn a process in Java that survives a JVM shutdown | [
"",
"java",
"process",
""
] |
When @RadioServiceGroup is set to NULL, I want to return all the records from the sbi\_l\_radioservicecodes table which has about 120 records. However, when I execute the following procedure and set the @RadioServiceGroup to NULL, it returns no records. Here is the stored proc:
```
CREATE PROCEDURE [dbo].[GetRadioServ... | Try "IS NULL" instead of "= NULL" | > Curious, is it just a syntax thing on why = does not work on nvarchar for NULL
Some people are saying that NULL = NULL evaluates to false. This is wrong. NULL = NULL evaluates to NULL.
The result (NULL) is not true, so the ELSE condition is run.
See also : [ThreeValuedLogic on Wikipedia](http://en.wikipedia.org/wi... | Why doesn't setting a nvarchar variable to null return nothing in this stored proc? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Is it better to initialize class member variables on declaration
```
private List<Thing> _things = new List<Thing>();
private int _arb = 99;
```
or in the default constructor?
```
private List<Thing> _things;
private int _arb;
public TheClass()
{
_things = new List<Thing>();
_arb = 99;
}
```
Is it simply a mat... | In terms of performance, there is no real difference; field initializers are implemented as constructor logic. The only difference is that field initializers happen before any "base"/"this" constructor.
The constructor approach can be used with auto-implemented properties (field initializers cannot) - i.e.
```
[Defau... | Actually, field initializers as you demonstrate is a convenient shorthand. The compiler actually copies the initialization code into the beginning of each instance constructor that you define for your type.
This has two implications: first, any field initialization code is duplicated in each constructor and, second, a... | C# member variable initialization; best practice? | [
"",
"c#",
"constructor",
"declaration",
""
] |
Is there a single algorithm that removes elements from a container as happens in the following code?
```
vec_it = std::remove_if( vec.begin(), vec.end(), pred );
vec.erase( vec_it, vec.end() );
``` | The idiomatic way to do it is like jalf has said. You can build your own function to do that more easily:
```
template<typename T, typename Pred> void erase_if(T &vec, Pred pred)
{
vec.erase(std::remove_if(vec.begin(), vec.end(), pred), vec.end());
}
```
So you can use
```
std::vector<int> myVec;
// (...) fill t... | You mean like this?
```
vec.erase( std::remove_if( vec.begin(), vec.end(), pred ), vec.end() );
```
That's the idiomatic way to do it. | Single statement method to remove elements from container | [
"",
"c++",
"stl",
"erase-remove-idiom",
""
] |
How can I programmatically change my browser's default home page with C#? | Set it in this registry setting:
```
HKCU\Software\Microsoft\Internet Explorer\Main\Start Page
``` | See this, which is not in C#, but you should be able to work out the registry stuff in C# pretty easily.
<http://www.microsoft.com/technet/scriptcenter/resources/qanda/nov04/hey1108.mspx>
Please don't arrange for this code to run on my machine! | How to set the default browser home page (IE) with C#? | [
"",
"c#",
"browser",
""
] |
I would like to know how to get the name of the property that a method parameter value came from. The code snippet below shows what I want to do:
```
Person peep = new Person();
Dictionary<object, string> mapping = new Dictionary<object, string>();
mapping[peep.FirstName] = "Name";
Dictionary<string, string> propertyT... | I think ultimately you will need to store either the PropertyInfo object associated with the property, or the string representation of the property name in you mapping object. The syntax you have:
```
mapping[peep.FirstName] = "Name";
```
Would create an entry in the dictionary with a key value equal to the value of ... | You are not able to do so in this way, since the way it works is that C# evaluates the value of FirstName property by calling its get accessor and passes the value of that to the indexer of the dictionary. Therefore, the way you found out FirstName value is completely lost. Just like the way you evaluate 2 + 2.
If you ... | Getting the property name that a value came from | [
"",
"c#",
".net",
"reflection",
""
] |
How can I display something over all other application. I want to to display something over all form of my program and all other programs open on my desktop (not mine).
**\*Top Most doesn't work I have tested and my browser can go OVER my application :S**
Here is an image of when I use TopMost to TRUE. You can see my... | You can use the form instance and set the property **TopMost** to True.
---
If you want to be over all Windows, there are another way with **Win32 Api** calls.
Here is what you could do:
In your form class add :
```
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWin... | The Form.TopMost property will set your form the top form above all other running windows applications (not just your forms.)
```
myForm.TopMost = true; // This will do the job
``` | Form top most? | [
"",
"c#",
".net",
""
] |
I have a block of JSP code that needs to be used in several places (basically a widget that several pages use). What's a good way to modularize this? I'd rather not put it in an object since string manipulation of HTML gets ugly. Using `<%@ include file="foo.jsp"%>` is problematic because we wind up having implicit glo... | You can create a simple *tag* and use it anywhere you want your widget. A tag is a reusable object that you can use in any of your JSP's.
Please see <http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags.html>. | 1. Separate the JSP out into its own file and include it (JSP Includes, Tiles Includes, etc)
2. Can you create a Tag Lib incorporating the functionality? | Best way to modularize a block of JSP code | [
"",
"java",
"jsp",
""
] |
We have very strange problem, one of our applications is continually querying server by using .net remoting, and every 100 seconds the application stops querying for a short duration and then resumes the operation. The problem is on a client and not on the server because applications actually queries several servers in... | I've never seen that behavior before and unfortunately it's a vague enough scenario I think you're going to have a hard time finding someone on this board who's encountered the problem. It's likely specific to your application.
I think there are a few investigations you can do to help you narrow down the problem.
1. ... | 100 Seconds is a give away number as it's the default timeout for a webrequest in .Net.
I've seen in the past that the PSI (Project Server Interface within Microsoft Project) didn't override the timeout and so the default of 100 seconds was applied and would terminate anything talking to it for longer than that time.
... | .net remoting stops every 100 seconds | [
"",
"c#",
".net",
"remoting",
""
] |
I have a \*.MDB database file, and I am wondering if it is possible or recommended to work against it using LINQ in C#. I am also wondering what some simple examples would look like.
I don't know a lot about LINQ, but my requirements for this task are pretty simple (I believe). The user will be passing me a file path ... | What you want is a LINQ to ODBC provider, or a LINQ to JET/OLEDB provider.
Out of the box, MS doesn't make one. There may be a 3rd party who does. | Actually I recently (today) discovered that you can access an Access database with LinqToSql. It must be in the 2002 or newer format, you will not be able to drag and drop the tables to your datacontext so either manually create the objects in your dbml or you can use SQL Server Migration for Access to move it to a sql... | Query Microsoft Access MDB Database using LINQ and C# | [
"",
"c#",
"linq",
"ms-access",
""
] |
When you use the PHP [copy](https://www.php.net/manual/en/function.copy.php) function, the operation blindly copies over the destination file, even if it already exists. How do you copy a file safely, only performing the copy if there is no existing file? | The obvious solution would be to call [file\_exists](https://www.php.net/manual/en/function.file-exists.php) to check to see if the file exists, but doing that could cause a race condition. There is always the possibility that the other file will be created in between when you call [file\_exists](https://www.php.net/ma... | I think you answered your own question - check to make sure the destination file exists before performing the copy. If the file exists, skip the copy.
Update: I see you really did answer your own question. You mention race conditions, but if you do find that the file already exists, how do you know that:
* the file t... | How do you copy a file in PHP without overwriting an existing file? | [
"",
"php",
"file",
"file-io",
""
] |
**Background**
We have a web application in which several developers have written several .js files that manipulate the DOM and the problem of duplicate function names has crept into our application.
**Question**
Can anyone recommend a tool that will warn us when we accidentally write a web page with two javascript ... | Well, using a parser may not always be ideal as it requires an extra step of copying and pasting your code, and everyone else's, into the parser and even then I'm not sure it would catch what you want. The time tested solution to collaborative Javascript development is to namespace your code.
```
var myNamespace = fun... | I have often used [JSLINT](http://jslint.com/)
In short it is a "compiler" for JavaScript using JavaScript. I have learned a lot by watching Douglas Crockford’s training videos.
It not only checks for duplicate functions, but global variables, and a whole bunch of other things. Like Douglas said in one of his videos ... | Tool that detects duplicate javascript function names in a web page? | [
"",
"javascript",
""
] |
Could someone explain why this works in C#.NET 2.0:
```
Nullable<DateTime> foo;
if (true)
foo = null;
else
foo = new DateTime(0);
```
...but this doesn't:
```
Nullable<DateTime> foo;
foo = true ? null : new DateTime(0);
```
The latter form gives me an compile error "Type of condi... | The compiler is telling you that it doesn't know how convert `null` into a `DateTime`.
The solution is simple:
```
DateTime? foo;
foo = true ? (DateTime?)null : new DateTime(0);
```
Note that `Nullable<DateTime>` can be written `DateTime?` which will save you a bunch of typing. | FYI (Offtopic, but nifty and related to nullable types) we have a handy operator just for nullable types called the null coalescing operator
```
??
```
Used like this:
```
// Left hand is the nullable type, righthand is default if the type is null.
Nullable<DateTime> foo;
DateTime value = foo ?? new DateTime(0);
``` | Nullable type issue with ?: Conditional Operator | [
"",
"c#",
"generics",
"nullable",
"conditional-operator",
""
] |
In Perl
```
print "a" x 3; # aaa
```
In C#
```
Console.WriteLine( ??? )
``` | It depends what you need... there is `new string('a',3)` for example.
For working with strings; you could just loop... not very interesting, but it'll work.
With 3.5, you could use `Enumerable.Repeat("a",3)`, but this gives you a sequence of strings, not a compound string.
If you are going to use this a lot, you cou... | If you only need to repeat a single character (as in your example) then this will work:
```
Console.WriteLine(new string('a', 3))
``` | What is the C# equivalent of Perl's repetition operator? | [
"",
"c#",
"perl",
"string",
""
] |
I have following string
```
String str = "replace :) :) with some other string";
```
And I want to replace first occurance of `:)` with some other string
And I used `str.replaceFirst(":)","hi");`
it gives following exception
> "Unmatched closing ')'"
I tried using `replace` function but it replaced all occurance ... | [Apache Jakarta Commons](http://commons.apache.org/) are often the solution for this class of problems. In this case, I would have a look at [commons-lang](http://commons.apache.org/lang/), espacially [StringUtils.replaceOnce()](http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html#replaceOnce... | The `replaceFirst` method takes a regular expression as its first parameter. Since `)` is a special character in regular expressions, you must quote it. Try:
```
str.replaceFirst(":\\)", "hi");
```
The double backslashes are needed because the double-quoted string also uses backslash as a quote character. | String replace function | [
"",
"java",
"string",
""
] |
I have an object that implements [ArrayAccess](http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html), [Iterator](http://www.php.net/~helly/php/ext/spl/interfaceIterator.html) and [Countable](http://www.php.net/~helly/php/ext/spl/interfaceCountable.html). That produces a nigh-perfect array masking. I can acce... | Recent changes in PHP prevent ArrayIterators form being manipulated using the standard array functions (reset, next, etc).
This should be restored soon:
<http://news.php.net/php.internals/42015> | One way to get this to work is to define your own iterator in a separate class, and then tell your main class to use that new iterator instead of the default one.
```
class MyIterator implements Iterator {
public function key() {
//
}
public function rewind() {
//
}
// etc.
}
class MyMainClass im... | PHP objects as faux-arrays | [
"",
"php",
"arrays",
"spl",
""
] |
I have an ActiveX plugin that we need (if possible) to run in Firefox. Is there a plugin (or other way) for Firefox that will allow this? | I seem to have found a solution:
<http://code.google.com/p/ff-activex-host/>
"This Firefox plugin makes it possible to use ActiveX controls in Firefox. It is based on the Gecko NPAPI and provides full access to the hosted control (events, functions, properties)." | You used to be able to in Firefox 1.5 but not any longer I believe, the [plugin](http://www.iol.ie/~locka/mozilla/mozilla.htm) doesnt seem to be supported anymore.
More info [here](http://groups.google.com/group/mozilla.dev.tech.plugins/browse_thread/thread/c1ffb11ac6bcf0e0/4209766365b7146f) | Is there a way to run ActiveX components in Firefox through the use of a plugin? | [
"",
"c++",
"firefox",
"browser",
"activex",
"xul",
""
] |
I would like to return a string with all of the contents of a CSS rule, like the format you'd see in an inline style. I'd like to be able to do this without knowing what is contained in a particular rule, so I can't just pull them out by style name (like `.style.width` etc.)
The CSS:
```
.test {
width:80px;
h... | Adapted from [here](http://www.javascriptkit.com/domref/cssrule.shtml), building on scunliffe's answer:
```
function getStyle(className) {
var cssText = "";
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classe... | Since the accepted answer from "nsdel" is only avilable with one stylesheet in a document this is the adapted full working solution:
```
/**
* Gets styles by a classname
*
* @notice The className must be 1:1 the same as in the CSS
* @param string className_
*/
function getStyle(classN... | How do you read CSS rule values with JavaScript? | [
"",
"javascript",
"html",
"css",
""
] |
I'm testing how the classes FileStream and StreamReader work togheter. Via a Console application.
I'm trying to go in a file and read the lines and print them on the console.
I've been able to do it with a while-loop, but I want to try it with a foreach loop.
```
using System;
using System.Collections.Generic;
using ... | To read all lines in New Text Document.txt:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace testing
{
public class Program
{
public static void Main(string[] args)
{
string file = @"C:\Temp\New Folder\New Text Doc... | If you want to read a file line-by-line via foreach (in a reusable fashion), consider the following iterator block:
```
public static IEnumerable<string> ReadLines(string path)
{
using (StreamReader reader = File.OpenText(path))
{
string line;
while ((line = reader.ReadL... | FileStream StreamReader problem in C# | [
"",
"c#",
""
] |
I want to enumerate all available drive letters (which aren't already taken) in Windows using VC++.
How can I do this? | [::GetLogicalDrives()](https://msdn.microsoft.com/en-us/library/aa364972(v=vs.85).aspx) returns a list of available (read: used) drives as bits in a mask. This should include mapped network drives. Thus, you can simply walk the bits to find bits that are zero, meaning no drive is present. If in doubt, you can always ca... | [`GetLogicalDriveStrings`](http://msdn.microsoft.com/en-us/library/aa364975(VS.85).aspx) can get you just the list of currently used drive letters.
[`GetVolumeInformation`](http://msdn.microsoft.com/en-us/library/aa364993(VS.85).aspx) can be used to get more information about a specific drive. | Enumerating all available drive letters in Windows | [
"",
"c++",
"winapi",
"drives",
""
] |
What do people recommend for creating popup's in ASP.Net MVC? I have used the AJAX toolkit and component art's methods in the web forms world and am looking something with similar capability.
What JQUERY plugins do people like? SimpleModal, JBOX (I think this was, what it was called)
Is it worth exploring pulling out... | jqModal looks pretty cool <http://dev.iceburg.net/jquery/jqModal/> - have only done some brief experiments, not used in production yet, but have put in the toybox for my current project. | I like [lightBox](http://leandrovieira.com/projects/jquery/lightbox/) | asp.net mvc & popup dialogs | [
"",
"javascript",
"asp.net-mvc",
"modal-dialog",
""
] |
I am running JVM 1.5.0 (Mac OS X Default), and I am monitoring my Java program in the Activity Monitor. I have the following:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
public class MemoryTest {
public static voi... | Many JVMs never return memory to the operating system. Whether it does so or not is implementation-specific. For those that don't, the memory limits specified at startup, usually through the -Xmx flag, are the primary means to reserve memory for other applications.
I am having a hard time finding documentation on this... | There are several command line options for the JVM which help to tune the size of the heap used by Java.
Everybody knows (or should know) about -Xms and -Xmx, which set the minimum and the maximum size of the heap.
But there is also -XX:MinHeapFreeRatio and -XX:MaxHeapFreeRatio which are the respective limits between ... | Java still uses system memory after deallocation of objects and garbage collection | [
"",
"java",
"memory-management",
"memory-leaks",
"garbage-collection",
""
] |
I've got a (SQL Server 2005) database where I'd like to create views on-the-fly. In my code, I'm building a CREATE VIEW statement, but the only way I can get it to work is by building the entire query string and running it bare. I'd like to use parameters, but this:
```
SqlCommand cmd = new SqlCommand("CREATE VIEW @na... | Maybe I've not understood it correctly, but what prevents you to do:
```
viewname="foo";
viewwhere="* from bar";
SqlCommand cmd = new SqlCommand("CREATE VIEW "+viewname+" AS SELECT "+viewwhere);
``` | Parameters are not simply string substitutions. That is why your code won't work.
Its like you cant do
sql = "select \* from orders where orders\_id in (?)"
and pass "1,2,3,5" as parameter.
Parameters are type checked and can only contain scalar values IIRC. | Parameterized CREATE VIEW possible? | [
"",
"sql",
"sql-server-2005",
"parameters",
"view",
""
] |
What exception should I throw if I encounter an illegal state - for instance, an initialization method that should only be called once being called a second time? I don't really see any built-in exception that makes sense. This seems like something that should be in the framework - am I not poking in the right spot? | [InvalidOperationException](http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx) maybe?
> The exception that is thrown when a method call is invalid for the object's current state. | In general you should program your object in such a way *that it cannot reach an invalid state*. If you find out that your object is in an invalid state then you should throw a `SystemException` or an exception *directly derived* from `SystemException`. This is the answer to the question *in the title*.
However, the e... | Is there a built in .NET exception that indicates an illegal object state? | [
"",
"c#",
".net",
"exception",
""
] |
We've been using [jbossmq](http://www.jboss.org/community/docs/DOC-10525) and [csil](http://csil.sourceforge.net). The implementation has been successful in production for 6 years, but I'm wondering if something better is available.
One issue is jbossmq's thread per client model, and scheduled end of life. Another is ... | IKVM for compiling .NET from Java looks interesting.
For .NET messaging check out [RabbitMQ](http://www.rabbitmq.com/). | You should look at an ActiveMQ backend with NMS clients. I've had no problems with it.
I can't vouch for it though because the production system I am using it in is not high volume. | What is the best messaging server for communicating across java and .net? | [
"",
"c#",
"jboss",
""
] |
I don't understand how GCC works under Linux. In a source file, when I do a:
```
#include <math.h>
```
Does the compiler extract the appropriate binary code and insert it into the compiled executable OR does the compiler insert a reference to an external binary file (a-la Windows DLL?)
I guess a generic version of t... | Well. When you include `math.h` the compiler will read the file that contains declarations of the functions and macros that can be used. If you call a function declared in that file (*header*), then the compiler inserts a call instruction into that place in your object file that will be made from the file you compile (... | There are several aspects involved here.
First, **header files**. The compiler simply includes the content of the file at the location where it was included, nothing more. As far as I know, GCC doesn't even treat standard header files differently (but I might be wrong there).
However, header files might actually not ... | Includes with the Linux GCC Linker | [
"",
"c++",
"linux",
"unix",
"gcc",
""
] |
I find it curious that the most obvious way to create `Date` objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.
How do you check that a date, given as a combination of day, month, and year, is a valid date?
For instance, 2008-02-31 (as in yyyy-mm-... | The current way is to use the calendar class. It has the [setLenient](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setLenient%28boolean%29) method that will validate the date and throw and exception if it is out of range as in your example.
Forgot to add:
If you get a calendar instance and set the ... | Key is `df.setLenient(false);`. This is more than enough for simple cases. If you are looking for a more robust (I doubt that) and/or alternate libraries like [joda-time](https://www.joda.org/joda-time/), then look at the [answer by user "tardate"](https://stackoverflow.com/a/892204/1076848)
```
final static String DA... | How to sanity check a date in Java | [
"",
"java",
"validation",
"calendar",
"date",
""
] |
I'm currently using `std::ofstream` as follows:
```
std::ofstream outFile;
outFile.open(output_file);
```
Then I attempt to pass a `std::stringstream` object to `outFile` as follows:
```
GetHolesResults(..., std::ofstream &outFile){
float x = 1234;
std::stringstream ss;
ss << x << std::endl;
outFile << ss;
}... | You can do this, which doesn't need to create the string. It makes the output stream read out the contents of the stream on the right side (usable with any streams).
```
outFile << ss.rdbuf();
``` | If you are using `std::ostringstream` and wondering why nothing get written with `ss.rdbuf()` then use `.str()` function.
```
outFile << oStream.str();
``` | Writing stringstream contents into ofstream | [
"",
"c++",
"stl",
"parameters",
"stringstream",
"ofstream",
""
] |
I was curious if anyone had any hard numbers around the performance difference between annotating Entities using private fields instead of public getter methods. I've heard people say that fields are slower because they're called "through reflection" but then again so are the getter methods, no? Hibernate needs to set ... | Loaded 5000 records into a simple 3 column table. Mapped two classes to that table, one using annotated private fields and another using annotated public getters. Ran 30 runs of Spring's HibernateTemplate.loadAll() followed by a HibernateTemplate.clear() to purge the Session cache. Results in ms below...
methods total... | ok, I can't give numbers haha, but I would guess that accessing the fields through reflection wouldn't be a 'one time' thing. Each object has its own private members.
I honestly don't know much about reflection but the getter/setters should be straight forward. In fact you can try setting one of the methods to private... | Performance difference between annotating fields or getter methods in Hibernate / JPA | [
"",
"java",
"hibernate",
"jpa",
""
] |
Do you have any tricks for generating SQL statements, mainly INSERTs, in Excel for various data import scenarios?
I'm really getting tired of writing formulas with like
`="INSERT INTO Table (ID, Name) VALUES (" & C2 & ", '" & D2 & "')"` | The semi-colon needs to be inside the last double quote with a closing paren. When adding single quotes around a string, remember to add them outside your selected cell.
(spaces added for visibility - remove before inserting)
`=CONCATENATE("insert into table (id, name) values (",C2,",' ",D2," ');")`
Here is another ... | I used to use String concatenation method to create SQL inserts in Excel. It can work well but can also be a little time consuming and 'fiddly'.
I created an Excel Add-In that makes generating Inserts from Excel easier :
(see the video at the bottom of the page)
<http://www.howinexcel.com/2009/06/generating-sql-inser... | Tricks for generating SQL statements in Excel | [
"",
"sql",
"vba",
"excel",
"metaprogramming",
""
] |
How do I get a human-readable file size in bytes abbreviation using .NET?
**Example**:
Take input 7,326,629 and display 6.98 MB | This may not the most efficient or optimized way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.
```
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.L... | using **Log** to solve the problem....
```
static String BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
if (byteCount == 0)
return "0" + suf[0];
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.L... | How do I get a human-readable file size in bytes abbreviation using .NET? | [
"",
"c#",
".net",
"vb.net",
"filesize",
"human-readable",
""
] |
My mission is to create a little app where you can upload a picture, and the app will turn it into ASCII art. I'm sure these exist already but I want to prove that I can do it myself.
This would involve taking an image, making it greyscale and then matching each pixel with a character depending on how dark the picture... | A common formula to convert RGB to greyscale is:
```
Gray scale intensity = 0.30R + 0.59G + 0.11B
``` | As pointed out by [nickf](https://stackoverflow.com/users/9021/nickf) in his [comment](https://stackoverflow.com/questions/276780/making-an-image-greyscale-with-gd-library#276811), the simple formula `(pixel.r + pixel.g + pixel.b) / 3` is not correct. Use the GD-included function `imagefilter()` (no need to iterate ove... | Making an Image Greyscale with GD Library | [
"",
"php",
"image",
"gd",
""
] |
I believe this is a common question / problem but have not been able to find a good clean concise answer.
**The Problem**
How to map entities that appear to have an inheritance relationship:
```
Company
Supplier
Manufacturer
Customer
```
However, a Supplier can be a Manufacturer.
or
```
Person
Doctor
Pa... | You probably want to consider using the Roles. So a Role will have a set of Persons. Or a Person will have a set of Roles or both. This would probably imply that there is an Association class that maps persons to roles.
Define a Person class with all properties that are common to people. Then define a Role super class... | It seems to me that this is more a question around how to model a domain well, rather than an NHibernate mapping issue.
Once you've sorted out your domain modelling, I think you'll find the NHibernate mapping falls out relatively easily.
One place to look to get your head around the idea of modeling Roles is to look ... | How to map classes in NHibernate using Roles or Composition | [
"",
"c#",
"nhibernate",
""
] |
When I switch tabs with the following code
```
tabControl1.SelectTab("MyNextTab");
```
It calls the tabPage\_Enter for the tab it is switching from and the tab it is switching to. I want it to be called for the tab it is switching to, but not the tab it is switching from. How would I turn this off. I do know when it ... | Yes, I repro if I use a button to change the selected tab. TabControl forces the focus onto itself before it changes SelectedIndex. This appears to have been done to avoid problems with the Validating event. The focus change produces the first Enter event, for the active tab, the tab change then produces the second Ent... | Can you check the index of the active tab and workaround using that? | Turn off calling tabPage_Enter method in C# | [
"",
"c#",
"winforms",
"tabcontrol",
""
] |
Let's say I have a table that represents a super class, **students**. And then I have N tables that represent subclasses of that object (**athletes**, **musicians**, etc). How can I express a constraint such that a student must be modeled in one (not more, not less) subclass?
Clarifications regarding comments:
* This... | Here are a couple of possibilities. One is a `CHECK` in each table that the `student_id` does not appear in any of the other sister subtype tables. This is probably expensive and every time you need a new subtype, you need to modify the constraint in all the existing tables.
```
CREATE TABLE athletes (
student_id IN... | Each Student record will have a SubClass column (assume for the sake of argument it's a CHAR(1)). {A = Athlete, M=musician...}
Now create your Athlete and Musician tables. They should also have a SubClass column, but there should be a check constraint hard-coding the value for the type of table they represent. For exa... | Maintaining subclass integrity in a relational database | [
"",
"sql",
"sql-server",
"database-design",
"oop",
""
] |
Parts of my application are in C++ under windows. I need the process id for the current process. Any thoughts? | The [`GetCurrentProcessId`](http://msdn.microsoft.com/en-us/library/ms683180(VS.85).aspx) function will do this. | Having grown accustomed to seeing yards and yards of code to accomplish seemingly straightforward tasks, I was pleasantly surprised at the directness of `GetCurrentProcessId`. Earlier today, I watched it run in a debugger, when I was following a new bit of code in a `DllMain` routine that combines the process ID with a... | ms c++ get pid of current process | [
"",
"c++",
"windows",
"process",
"pid",
""
] |
If I have the following code:
```
MyClass pClass = new MyClass();
pClass.MyEvent += MyFunction;
pClass = null;
```
Will pClass be garbage collected? Or will it hang around still firing its events whenever they occur? Will I need to do the following in order to allow garbage collection?
```
MyClass pClass = new MyCla... | For the specific question "Will pClass be garbage collected": the event subscription has no effect on the collection of pClass (as the publisher).
For GC in general (in particular, the target): it depends whether MyFunction is static or instance-based.
A delegate (such as an event subscription) to an instance method ... | Yes, `pClass` will be garbage collected. The event subscription does not imply that any reference exists to `pClass`.
So no, you will not have to detach the handler in order for `pClass` to be garbage collected. | Do event handlers stop garbage collection from occurring? | [
"",
"c#",
".net",
"event-handling",
"garbage-collection",
""
] |
When C# 4.0 comes out and we have the dynamic keyword as described in this [excellent presentation by Anders Hejlsberg](http://channel9.msdn.com/pdc2008/TL16/), (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)
Would I still need the var keyword ? Is there any... | No, they're very different.
`var` means "infer the type of the variable at compile-time" - but it's still entirely statically bound.
`dynamic` means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls *really* me... | Dynamic and var represent two completely different ideas.
**var**
Var essentially asks the compiler to figure out the type of the variable based on the expression on the right hand side of the assignment statement. The variable is then treated exactly as if it were explicitly declared as the type of the expression. F... | Does the new 'dynamic' C# 4.0 keyword deprecate the 'var' keyword? | [
"",
"c#",
"c#-4.0",
"dynamic-languages",
""
] |
Is it possible to create a list that can be access by either an index or a key?
*I am looking for a Collection type that already exists but has this facility, I want to avoid redefining the indexers* | System.Collections.Specialized.NameValueCollection can do this, but it can only store strings as values.
```
System.Collections.Specialized.NameValueCollection k =
new System.Collections.Specialized.NameValueCollection();
k.Add("B", "Brown");
k.Add("G", "Green");
Console.WriteLine(k[0]); ... | There's a similar question at [What is the best data structure in .NET for look-up by string key or numeric index?](https://stackoverflow.com/questions/137753/what-is-the-best-data-structure-in-net-for-look-up-by-string-key-or-numeric-ind).
Have a look at [KeyedCollection](http://msdn.microsoft.com/en-us/library/ms132... | Built-in List that can be accessed by index and key | [
"",
"c#",
"dictionary",
"list",
""
] |
```
SELECT NR_DZIALU, COUNT (NR_DZIALU) AS LICZ_PRAC_DZIALU
FROM PRACOWNICY
GROUP BY NR_DZIALU
HAVING NR_DZIALU = 30
```
or
```
SELECT NR_DZIALU, COUNT (NR_DZIALU) AS LICZ_PRAC_DZIALU
FROM PRACOWNICY
WHERE NR_DZIALU = 30
GROUP BY NR_DZIALU
``` | The theory (by theory I mean [SQL Standard](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt)) says that WHERE restricts the result set before returning rows and HAVING restricts the result set after bringing all the rows. So WHERE is faster. On SQL Standard compliant DBMSs in this regard, only use HAVING wher... | It might depend on the engine. MySQL for example, applies HAVING almost last in the chain, meaning there is almost no room for optimization. From the [manual](http://dev.mysql.com/doc/refman/5.0/en/select.html):
> The HAVING clause is applied nearly last, just before items are sent to the client, with no optimization.... | Which SQL statement is faster? (HAVING vs. WHERE...) | [
"",
"sql",
"performance",
"grouping",
"if-statement",
""
] |
Here is the code currently used.
```
public String getStringFromDoc(org.w3c.dom.Document doc) {
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf ... | Relies on [DOM Level3 Load/Save](http://www.w3.org/TR/DOM-Level-3-LS/load-save.html):
```
public String getStringFromDoc(org.w3c.dom.Document doc) {
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
... | The transformer API is the only XML-standard way to transform from a DOM object to a serialized form (String in this case). As standard I mean SUN [Java XML API for XML Processing](http://en.wikipedia.org/wiki/Java_API_for_XML_Processing).
Other alternatives such as Xerces [XMLSerializer](http://xerces.apache.org/xerc... | Is there a more elegant way to convert an XML Document to a String in Java than this code? | [
"",
"java",
"xml",
""
] |
In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface? | There really aren't any true "private" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:
```
>>> class Foo( object ):
... def foo( self ):
... print 'FOO!'
...
>>> class Bar( Foo ):
... def foo( self ):
.... | kurosch's method of solving the problem isn't quite correct, because you can still use `b.foo` without getting an `AttributeError`. If you don't invoke the function, no error occurs. Here are two ways that I can think to do this:
```
import doctest
class Foo(object):
"""
>>> Foo().foo()
foo
"""
de... | Python inheritance - how to disable a function | [
"",
"python",
"inheritance",
"interface",
"private",
""
] |
Seems a great C++ unit testing framework. I'm just wanting something a bit more sophisticated than the console output for running the test, also something that makes it really easy to run specific tests (since gtest supports all kinds of test filtering)
If there is nothing, I'll probably roll my own | I opened a google code project that adds UI to google test. Runs on both Windows and Unix.
It is not a plugin to any IDE by design - I did not want to tie myself. Instead you open it in the background and press the "Go" button whenever you want to run.
As of this writing V1.2.1 is out and you are invited to give it a ... | According to the project owner, [there isn't](http://groups.google.com/group/googletestframework/browse_thread/thread/af01d964d65c2144). If you do work on one, do post to the project's [group](http://groups.google.com/group/googletestframework). I'm sure there are some folks there who'd like to help. | Is there a graphical test runner for "Google Test" ( gtest ) for windows? | [
"",
"c++",
"googletest",
""
] |
I have a Flash movie embedded in some DIV. The trouble is that when I change any property of the enclosing DIV dynamically, Firefox (not other browsers) restarts/reinitializes Flash movie effectively resetting the whole progress (eg: file selection for upload, etc.).
Is there some sort of a workaround for this? | Try hiding it with `visibility:hidden` or if all else fails, `position:absolute;left:-9999px`.
I presume Firefox doesn't want to waste memory and CPU on Flash animation that's invisible, so it kills it. | see <https://bugzilla.mozilla.org/show_bug.cgi?id=90268> | Firefox restarts Flash movie if enclosing DIV properties change | [
"",
"javascript",
"flash",
"firefox",
""
] |
I have written C# code for ascx. I am trying to send an email on click of image button which works in Mozilla Firefox but not in Internet Explorer.
This function is called on button click:
```
<%@ Control Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import ... | hai all,
This code is working in IE not mozilla,anyone give idea
document.onkeypress = KeyCheck;
function KeyCheck(e) {
```
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if (KeyID == 0) {
var image = document.getElementById("<%= imagetirukural.ClientID%>");
var label... | In code behind just change
protected void btnSubmit\_Click(object sender, EventArgs e)
with
protected void btnSubmit\_Click(object sender, ImageClickEventArgs e) | .net click on image button not working in Internet Explorer but in Firefox | [
"",
"c#",
"asp.net",
""
] |
Currently I have a ListView (using the Details View). I would like to implement the behaviour whereby when a user selects a single item (log entry) the log entry expands (from one line to multiple lines) to provide more detailed information about the error that occured.
My question is this: Is this possible? If so, is... | Edit: sorry this is wpf
The trick I used to achieve the same thing was creating a trigger to show a secondary grid which is defaulted to collapsed.
Try this out:
```
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDef... | Have a read through the post on CodeProject Here: [Extended List Box](http://www.codeproject.com/KB/miscctrl/ExtendedListBoxControl.aspx)
Should have all the info you need for it :) | c# How can I expand an item within a ListView to occupy multiple lines? | [
"",
"c#",
"wpf",
"winforms",
"listview",
""
] |
I create new ASP.NET web application that use SMTP to send message. The problem is the smtp was not authenticated from who send the message.
How can I make SMTP authenticated in my program? does C# have a class that have attribute for enter username and password? | ```
using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("from@yourdomain.com");
smtpClien... | Ensure you set `SmtpClient.Credentials` **after** calling `SmtpClient.UseDefaultCredentials = false`.
The order is important as setting `SmtpClient.UseDefaultCredentials = false` will reset `SmtpClient.Credentials` to null. | How can I make SMTP authenticated in C# | [
"",
"c#",
"authentication",
"smtp",
""
] |
I have a key that appears to be an empty string, however using `unset($array[""]);` does not remove the key/value pair. I don't see another function that does what I want, so I'm guessing it's more complicated that just calling a function.
The line for the element on a print\_r is `[] => 1`, which indicates to me that... | Try `unset($array[null]);`
If that doesn't work, print the array via `var_export` or `var_dump` instead of `print_r`, since this allows you to see the type of the key. Use `var_export` to see the data in PHP syntax.
`var_export($array);`
Note that var\_export does not work with recursive structures. | Tried:
```
$someList = Array('A' => 'Foo', 'B' => 'Bar', '' => 'Bah');
print_r($someList);
echo '<br/>';
unset($someList['A']);
print_r($someList);
echo '<br/>';
unset($someList['']);
print_r($someList);
echo '<br/>';
```
Got:
```
Array ( [A] => Foo [B] => Bar [] => Bah )
Array ( [B] => Bar [] => Bah )
Array ( [B] =... | How do you remove a value that has an empty key from an associative array in PHP? | [
"",
"php",
"arrays",
"associative-array",
""
] |
How to figure out if a table is in use in SQL (on any type database)? if somebody is already using it, or have it "open" then its in use. | Actually this will give you a better result:
```
select spid
from master..sysprocesses
where dbid = db_id('Works') and spid <> @@spid
``` | Generally speaking, the correct way to find out whether someone else is using the table and will prevent you from doing whatever you want is to try doing what you want and to check whether it fails. If the failure message indicates 'non-exclusive access' or 'table in use' or equivalent, then you guessed wrong.
If your... | Is the Table in Use? | [
"",
"sql",
""
] |
I remember from way back at university using a switch with 'binary search' or 'binary switch'. Something like that, My google foo is broken today. Anyway it goes down like this: You define an array of possible options (Strings usually), some magic happens, and those options in the array become the cases in the switch h... | I think what you are looking for is an [Enum](http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html).
From the link above...
```
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day ... | Did you mean gperf? Or possibly you were referring to the theory (hashing) in general?
<http://www.gnu.org/software/gperf/> | Array as the options for a switch statment | [
"",
"java",
"enums",
"switch-statement",
""
] |
Is there a way to have a function return a editable reference to some internal data. Here's an example I hope helps show what I mean.
```
class foo
{
public int value;
}
class bar
{
bar()
{
m_foo = new foo();
m_foo.value = 42;
}
private m_foo;
foo getFoo(){return m_foo;}
}
class... | Actually, your code sample, after some cleaning up, does demonstrate that when you assign 37 to value, you are changing bar's interman m\_foo too. So the answer is, your function is returning a reference type. Now, maybe your real code is different, and it's returning not an reference type but an int, a value type, or ... | You're already returning the reference of `foo` in `getFoo` (this happens by default). So any changes that you make to the return value of `getFoo` will be reflected in the internal `foo` data structure in `bar`. | Function which returns reference to be edited in c# | [
"",
"c#",
""
] |
I guess it should be a common technique,
However, I tried the following two options:
1) Using my existing POP3 PHP client to access my local mail account. I am getting a "could not connect". Same code works if I run it with my localhost connecting to GoDaddy's pop3 server
2) Parsing the local mbox file - I can't figu... | Seems like I have this figured out. Shared hosting (GoDaddy specifically) does not allow direct TCP connections anywhere, including their own POP3 server. Looks like I can't be able to access the mbox file directly either. So I figure it is just not going to work.
Thanks all repliers!
Maybe there are OTHER inexpensiv... | I'd go with the POP3 option. It should work once you get the right port/host etc.
The other option will result in you duplicating a large part of the functionality already in the mail server, and its quite likely you'll have minor bugs in it resulting in emails not displaying properly, or worse, corruption in the mbox... | Accessing local mailbox using PHP on a shared hosting Linux account (GoDaddy) | [
"",
"php",
"email",
"shared-hosting",
""
] |
I have double (or float) variables that might be "empty", as in holding no valid value. How can I represent this condition with the built in types float and double?
One option would be a wrapper that has a float and a boolean, but that can´t work, as my libraries have containers that store doubles and not objects that... | In Visual C++, there is a non-standard [`_isnan(double)`](http://msdn.microsoft.com/en-us/library/tzthab44.aspx) function that you can import through `float.h`.
In C, there is a [`isnan(double)`](http://www.opengroup.org/onlinepubs/009695399/basedefs/math.h.html) function that you can import through `math.h`.
In C++,... | We have done that by using NaN:
```
double d = std::numeric_limits<double>::signaling_NaN();
bool isNaN = (d != d);
```
NaN values compared for equality against itself will yield false. That's the way you test for NaN, but which seems to be only valid if `std::numeric_limits<double>::is_iec559` is true (if so, it con... | Float or Double Special Value | [
"",
"c++",
"floating-point",
"double",
""
] |
This is for my DB class. I am new to OO, been a procedural lad for some time, so I'm still a bit murky.
My first idea was using a bunch of setter functions/methods.. but after writing a whole bunch, I thought about using PHP's define function, like so.
```
define('MYSQL_USERNAME', 'jimbo');
```
Is this an accepted p... | I use `const` only for creating mnemonic names for immutable constants in the class. The `define()` function does not create constants as part of the class, it creates constants in the global space.
```
class MyClass
{
const CONFIG_FILE = 'myapp.ini';
```
Class configuration data I usually declare as a `protected` ... | there are probably a few options to deal with this:
1. just use setters, it's perfectly acceptable, but can get a bit "wordy" with a lot of config options.
2. use a config object to pass in:
```
$config = (object) array(
'prop1' => 'somevalue',
'prop2' => 'somevalue2',
'prop3' => 'somevalue3',... | What is the best way to get config variables into a class in php 5? | [
"",
"php",
"oop",
""
] |
Is there any way to follow a URL in JavaScript without setting the `document.location.href`?
I have a page that displays a list of objects and each object may have a file download associated with it, which is accessed via a hyperlink. Clicking the link initiates an AJAX request that ultimately leads to a transient fil... | you could open a new window with the new url? or try setting an iframe's url to the new url, both should present a file download (the latter being the better option) | You could use a hidden iframe - set the src of that to the file to download. | Follow a URL using JavaScript | [
"",
"javascript",
"ajax",
""
] |
I've just started building a prototype application in Django. I started out by working through the [Django app tutorial on the Django site](http://docs.djangoproject.com/en/dev/intro/tutorial01/) which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple quest... | You need to look at the Django [forms](http://docs.djangoproject.com/en/dev/topics/forms/#topics-forms-index).
You should never build your own form like that.
You should declare a Form class which includes a [ChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield) and provide the domain of ch... | > I feel like there must be a way to
> create a simple loop that counts from
> 1 to 10 that would generate most of
> those options for me, but I can't
> figure out how to do that...
If you don't want to use Django forms (why btw?), check out this [custom range tag](http://www.djangosnippets.org/snippets/779/) or just ... | Looping in Django forms | [
"",
"python",
"django",
""
] |
If I put a DateTime value into an Excel cell using `Range.set_value` through .Net COM Interop, and then retrieve the value of that same cell using `Range.get_value`, the Millisecond part of the value is not returned, though everything else is correct.
Is this a bug?
What is the workaround? I'm guessing that using the... | As [Jon suggested](https://stackoverflow.com/questions/298458/milliseconds-missing-when-getting-a-datatime-value-from-excel-using-net-interop#298467), converting the DateTime to a double using DateTime.ToOADate (then back again using DateTime.FromOADate) works if you set the value using the Range.Value2 property.
The ... | If you set a date/time with a millisecond value in Excel manually, does it maintain it? I don't know about the Excel internal object model, but it's conceivable that it just doesn't support milliseconds.
EDIT: Okay, now we know that the set fails (the get may also fail, of course)... you could try setting it as a doub... | Milliseconds missing when getting a DateTime value from Excel using .Net Interop | [
"",
"c#",
".net",
"excel",
"com-interop",
""
] |
in javascript, when I receive a focus event, how can I work out which element has lost focus? I'm trying to avoid having to put an onblur event handler on all elements within my web page. | @pbrodka: the target/srcElement property would refer to the element with focus for onfocus events
offhand I can't see a way to get this short of onblur, or if the set of objects you care about all have focus methods you could store a reference to that object instead. It's also possible event bubbling could get you out... | Difficult this. You cannot use event delegation to find out which control last produced a blur as focus/blur do not bubble up. There have been some attempts to 'fix' this but they are buggy and not resiliant cross browser.
Could I ask you why do you need this information as maybe there is an alternative solution. | which HTML element lost focus? | [
"",
"javascript",
"focus",
""
] |
I want to close a System.Windows.Forms.Form if the user clicks anywhere outside it. I've tried using IMessageFilter, but even then none of the messages are passed to PreFilterMessage. How do I receive clicks outside a form's window? | With thanks to [p-daddy](https://stackoverflow.com/users/36388/p-daddy) in [this question](https://stackoverflow.com/questions/298626/what-do-these-wndproc-codes-mean), I've found this solution which allows me to use ShowDialog:
```
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.Capture =... | In your form's Deactivate event, put "this.Close()". Your form will close as soon as you click anywhere else in Windows.
Update: I think what you have right now is a Volume button, and inside the Click event you create an instance of your VolumeSlider form and make it appear by calling ShowDialog() which blocks until ... | How do I close a form when a user clicks outside the form's window? | [
"",
"c#",
"forms",
"click",
""
] |
As the title really, I'm in one part of my code and I would like to invoke any methods that have been added to the Button.Click handler.
How can I do this? | Do you mean you need to access it from elsewhere in your code? It may be an idea to refactor that section to it's own method then call that method whenever you need to access it (including in the Click event) | AVOID. Really. Seems like you handle some important logic right in the event handler.
Move the logic out of the handler. | How can I invoke (web) Button.Click in c#? | [
"",
"c#",
".net",
"asp.net",
"events",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.