Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there a way to tell the debugger to stop just before returning, on whichever statement exits from the method, be it return, exception, or fall out the bottom? I am inspired by the fact that the Java editor shows me all the places that my method *can* exit - it highlights them when you click on the return type of the... | Put a breakpoint on the line of the method signature. That is where you write
```
public void myMethod() {
```
Then right-click on the breakpoint and select "Breakpoint Properties". At the bottom of the pop-up there are two checkboxes: "Method Entry", "Method Exit". Check the latter. | You can set a method breakpoint.
Double click in the margin next to the method declaration. A breakpoint with an arrow decoration appears. Right-clicking to examine the properties, you can set "Suspend on:" for "Method Entry" and/or "Method Exit".
You can read more about them in the [Eclipse Cookbook](http://books.go... | eclipse beakpoint: stop before leaving a Java method | [
"",
"java",
"eclipse",
"debugging",
"breakpoints",
"eclipse-3.4",
""
] |
I just found myself creating a class called "InstructionBuilderFactoryMapFactory". That's 4 "pattern suffixes" on one class. It immediately reminded me of this:
<http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern>
Is this a design smell? Should I impose a limit on this number?
I know some program... | I see it as a design smell - it will make me think if all those levels of abstraction are pulling enough weight.
I can't see why you wanted to name a class 'InstructionBuilderFactoryMapFactory'? Are there other kinds of factories - something that doesn't create an InstructionBuilderFactoryMap? Or are there any other k... | A good tip is: Your class public API (and that includes it's name) should reveal intention, not implementation. I (as a client) don't care whether you implemented the builder pattern or the factory pattern.
Not only the class name looks bad, it also tells nothing about what it does. It's name is based on its implement... | Too many "pattern suffixes" - design smell? | [
"",
"java",
"design-patterns",
"naming-conventions",
""
] |
Are there any **professional** Combobox controls (dropdown list with autosuggestion) based on the jQuery library?
It should be able to handle **large datasets** and have some **skinning** options. A **multi-column result list** would be great too. I'm working with ASP.NET, but it's a not a problem if I had to write a ... | Unfortunately, the best thing I have seen is the [jquery.combobox](http://web.archive.org/web/20130430100104/http://jquery.sanchezsalvador.com/page/jquerycombobox.aspx), but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, bu... | Here's one that looks very promising. It's a true combo - you see what you type. Has a cool feature I haven't seen elsewhere: paging results.
[FlexBox](http://www.codeplex.com/flexbox) | Professional jQuery based Combobox control? | [
"",
"javascript",
"jquery",
"combobox",
"controls",
""
] |
What is the best way to determine whether there is an available Internet connection for a WinForms app. (Programatically of course) I want to disable/hide certain functions if the user is not connected to the Internet. | The following will determine if you are connected to a network, however, that doesn't necessarily mean that you are connected to the Internet:
```
NetworkInterface.GetIsNetworkAvailable()
```
Here is a C# translation of Steve's code that seems to be pretty good:
```
private static int ERROR_SUCCESS = 0;
public stati... | sbeskur's response has a bug in the translation of InternetGetConnectedState. The parameters are both DWORD's (first one is an LPDWORD). Both of these translate to int's in C# (technically, uint but int will work for most scenarios).
Correct translation below.
```
[DllImport("wininet.dll", SetLastError=true)]
public... | How do you determine if an Internet connection is available for your WinForms App? | [
"",
"c#",
".net",
"winforms",
""
] |
So I made some timers for a quiz. The thing is, I just realized when I put
```
javascript: alert("blah");
```
in the address, the popup alert box **pauses** my timer. Which is very unwanted in a quiz.
I don't think there is any way to stop this behaviour... but I'll ask anyway.
If there is not, mind suggesting what... | Apparently the preview rendering differs from the posted rendering. This paragraph is here to make sure the next two lines show up as code.
```
// Preserve native alert() if you need it for something special
window.nativeAlert = window.alert;
window.alert = function(msg) {
// Do something with msg here. I always ... | Never, ever rely on javascript (or any other client-side time) to calculate elapsed times for operations done between postbacks, or different pages.
If you always compare server dates, it will be hard for people to cheat:
1. first page request, store the server time
2. ping with javascript calls each N seconds, compa... | Prevent js alert() from pausing timers | [
"",
"javascript",
"timer",
""
] |
I was always wondering if there is operator for deleting multi dimensional arrays in the standard C++ language.
If we have created a pointer to a single dimensional array
```
int *array = new int[size];
```
the delete looks like:
```
delete [] array;
```
That's great. But if we have two dimension array, we can not... | Technically, there aren't two dimensional arrays in C++. What you're using as a two dimensional array is a one dimensional array with each element being a one dimensional array. Since it doesn't technically exist, C++ can't delete it. | Because there is no way to call
```
int **array = new int[dim1][dim2];
```
All news/deletes must be balanced, so there's no point to a `delete [][]` operator.
`new int[dim1][dim2]` returns a pointer to an array of size `dim1` of type `int[dim2]`. So `dim2` must be a compile time constant. This is similar to allocati... | Why "delete [][]... multiDimensionalArray;" operator in C++ does not exist | [
"",
"c++",
"arrays",
""
] |
I am using trigger\_error to "throw" errors in a custom class. My problem is that trigger\_error prints out the line number where trigger\_error was called. For example, given the following code:
```
01 <?php
02 class Test {
03 function doAction() {
04 $this->doSubAction();
05 ... | Alright, for those of you who are interested in my final solution, I integrated the following piece of code in our framework which returns the correct line number in all the cases that we could of tested. We are using it in production.
[`ErrorHandler` class](http://pastebin.com/f12a290d1)
It catches uncaught PHP exce... | The best thing to do is set up an error handler that shows a full stack trace.
Set up a custom error handler, and call debug\_print\_backtrace() in it. You will find this useful in general, as well in this specific circumstance. | How to get proper line number when using trigger_error in PHP? | [
"",
"php",
"error-handling",
""
] |
I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?
FYI: The reason that there is so many types of data is that this is a piece of java code being wri... | In C#:
Fixed with recommendation from [Mike](https://stackoverflow.com/users/14359/mike-brown)
```
ArrayList list = ...;
// List<object> list = ...;
foreach (object o in list) {
if (o is int) {
HandleInt((int)o);
}
else if (o is string) {
HandleString((string)o);
}
...
}
```
In J... | You can use the `getClass()` method, or you can use instanceof. For example
```
for (Object obj : list) {
if (obj instanceof String) {
...
}
}
```
or
```
for (Object obj : list) {
if (obj.getClass().equals(String.class)) {
...
}
}
```
Note that instanceof will match subclasses. For instance, of `C` is a... | How do I find out what type each object is in a ArrayList<Object>? | [
"",
"java",
"generics",
"reflection",
"arraylist",
""
] |
What is the best way to secure the use/loading of a DLL with a license file? | A couple of things you might want to consider:
Check sum the DLL. Using a [cryptographic hash function](http://en.wikipedia.org/wiki/Cryptographic_hash_function), you can store this inside the license file or inside the DLL. This provides a verification method to determined if my original DLL file is unhacked, or if i... | You can check for a license inside of DllMain() and die if it's not found. | Secure a DLL file with a license file | [
"",
"c++",
"dll",
"licensing",
""
] |
I've got a client that, during testing, is giving me conflicting information. I don't think they are lying but more confused. So, I would like to setup some simple auditing in my ASP.Net application. Specifically, right when any page is called, I want to immediately insert the Querystring and/or form POST data into a l... | All of the form data should be in [Request.Params](http://msdn.microsoft.com/en-us/library/system.web.httprequest.params.aspx). You'd need to do this on every page, though or maybe use an HttpModule.
[EDIT] If you want to get the form parameters separately use [Request.Form](http://msdn.microsoft.com/en-us/library/sys... | You can create a custom HttpModule to capture all request made to your application so you don't need to touch every page and you can use it only during testing just not to slow down performance in production.
A sample implementation would be:
```
public class CustomModule : IHttpModule
{
public void Init(HttpApp... | .Net Form POST | [
"",
"c#",
"asp.net",
"form-post",
""
] |
Has anyone got to some good code to zoom into an image using javascript?
I know I could just resize it etc but was being lazy and looking for something clever to zoom to different levels, move around when zoomed etc | This really depends on what quality you are after. If you need a hires hiquality image with detailed zoom levels and proper interpolation you will need to write a backend service to serve up zoomed portions of your images. If you have no care for quality or speed, you could download the entire image and fit it to displ... | Check this:
* [jQZoom](http://www.mind-projects.it/blog/jqzoom_v10)
* [Zoomimage - jQuery plugin](http://www.eyecon.ro/zoomimage/)
* [jQuery ImgZoom](http://plugins.jquery.com/project/imgzoom)
* [FancyBox](http://fancy.klade.lv/) | Image Zoom using javascript? | [
"",
"javascript",
"imaging",
""
] |
I recall reading somewhere that using references to smart pointers can cause memory corruption. Is this simply because of using the reference of the smart pointer after its been destroyed? Or does the reference counting get messed up?
Thanks for clarifying | Assuming you are talking about shared\_ptr here...
> Is this simply because of using the
> reference of the smart pointer after
> its been destroyed?
This is a good answer. You may not know absolutely the lifetime of the pointer your reference refers too.
To get around this, you'd want to look into boost::weak\_ptr.... | When using smart pointers (or any allocation management object) you are counting on the behaviors defined in the constructor/destructor to manage refs/derefs/locks/unlocks. As a result, those types of objects must be true objects to perform properly. when using references to such objects (or pointers) you are bypassing... | Why shouldn't you use references to smart pointers? | [
"",
"c++",
"smart-pointers",
""
] |
I have a some JPA entities that inherit from one another and uses discriminator to determine what class to be created (untested as of yet).
```
@Entity(name="switches")
@DiscriminatorColumn(name="type")
@DiscriminatorValue(value="500")
public class DmsSwitch extends Switch implements Serializable {}
@MappedSuperclass... | As your switch class is not an entity, it cannot be used in an entity relationship... Unfortunately, you'll have to transform your mappedsuperclass as an entity to involve it in a relationship. | As the previous commentors I agree that the class model should be different. I think something like the following would suffice:
```
@Entity(name="switches")
@DiscriminatorColumn(name="type")
@DiscriminatorValue(value="400")
public class Switch implements ISwitch {
// Implementation details
}
@Entity(name="switches... | JPA and inheritance | [
"",
"java",
"jpa",
""
] |
I want to write a query like this:
```
SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
```
But this isn't how the `MAX` function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows.
Does anyone know how to do it my way? | You'd need to make a `User-Defined Function` if you wanted to have syntax similar to your example, but could you do what you want to do, inline, fairly easily with a `CASE` statement, as the others have said.
The `UDF` could be something like this:
```
create function dbo.InlineMax(@val1 int, @val2 int)
returns int
a... | If you're using SQL Server 2008 (or above), then this is the better solution:
```
SELECT o.OrderId,
(SELECT MAX(Price)
FROM (VALUES (o.NegotiatedPrice),(o.SuggestedPrice)) AS AllPrices(Price))
FROM Order o
```
All credit and votes should go to [Sven's answer to a related question, "SQL MAX of multiple ... | Is there a Max function in SQL Server that takes two values like Math.Max in .NET? | [
"",
"sql",
"sql-server",
"max",
""
] |
I installed Tomcat 6.0.18 on a windows server 2003 box and it will not start as a service.
I'm running it with jdk 1.6.0\_07.
It runs when I start it with tomcat6.exe.
I got a vague error in the System Event Log on Windows.
The Apache Tomcat 6 service terminated with service-specific error 0 (0x0). | I'll bite it :-)
Tomcat Service on windows is dependent on the MS C Runtime library msvcr71.dll. As long as it is in the path, the service will start just fine.
Just to prevent your other windows to be forced to use this version of the runtime library, you might want to copy the DLL to just the tomcat bin path instea... | From [gobaco.wordpress.com](http://gobaco.wordpress.com/2007/07/04/could-not-start-tomcat-6-on-windows-xp/)
Tomcat 6 couldn’t find a file called msvcr71.dll.
I just copied it over from
c:\windows\microsoft.net\framework\v1.1.4322
to
c:\windows\system32
and was able to start tomcat.
I thought this was very strange,... | Tomcat 6.0.18 service will not start on a windows server | [
"",
"java",
"tomcat",
"windows-server-2003",
""
] |
I want to put a `Canvas` with an image in my window, and then I want to *pack* widgets on top of it, so the Canvas acts as a background.
Is it possible to have two states for the `pack` manager: one for one set of widgets and another for another set? | The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent.
However, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if i... | I believe that Bryan's answer is probably the best general solution. However, you may also want to look at the [place](http://www.pythonware.com/library/tkinter/introduction/place.htm) geometry manager. The **place** geometry manager lets you specify the exact size and position of the widget... which can get tedious qu... | How do I overlap widgets with the Tkinter pack geometry manager? | [
"",
"python",
"tkinter",
"geometry",
"pack",
""
] |
I have a curious question about efficiency. Say I have a field on a database that is just a numeric digit that represents something else. Like, a value of 1 means the term is 30 days.
Would it be better (more efficient) to code a SELECT statement like this...
```
SELECT
CASE TermId
WHEN 1 THEN '30 days'
... | Efficiency probably wouldn't matter here - code maintainability does though.
Ask yourself - will these values change? What if they do? What would I need to do after 2 years of use if these values change?
If it becomes evident that scripting them in SQL would mean better maintainability (easier to change), then do it in... | For a number of reasons, I would process the translation in the grid view.
Reason #1: SQL resource is shared. Grid is distributed. Better scalability.
Reason #2: Lower bandwidth to transmit a couple integers vs. strings.
Reason #3: Code can be localized for other languages without affecting the SQL Server code. | Manipulate Results in GridView RowDataBound or Directly in SQL? | [
"",
"asp.net",
"sql",
"optimization",
""
] |
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ... | # UPDATE
The `timeout` command, available from Windows Vista and onwards should be the command used, as described in another [answer](https://stackoverflow.com/a/5483958/6899) to this question. What follows here is an *old* answer.
### Old answer
If you have Python installed, or don't mind installing it (it has othe... | The [`timeout`](http://technet.microsoft.com/en-us/library/cc754891.aspx) command is available from Windows Vista onwards:
```
c:\> timeout /?
TIMEOUT [/T] timeout [/NOBREAK]
Description:
This utility accepts a timeout parameter to wait for the specified
time period (in seconds) or until any key is pressed. ... | Sleeping in a batch file | [
"",
"python",
"batch-file",
""
] |
I'm trying to get the contents of a XML document element, but the element has a colon in it's name.
This line works for every element but the ones with a colon in the name:
```
$(this).find("geo:lat").text();
```
I assume that the colon needs escaping. How do I fix this? | Use a backslash, which itself should be escaped so JavaScript doesn't eat it:
```
$(this).find("geo\\:lat").text();
``` | That isn't just an ordinary element name. That's a qualified name, meaning that it is a name that specifically refers to an element type within a namespace. The element type name is 'lat', and the namespace prefix is 'geo'.
Right now, jQuery can't deal with namespaces very well, see [bug 155](http://dev.jquery.com/tic... | Parsing XML with namespaces using jQuery $().find | [
"",
"javascript",
"jquery",
"xml",
"namespaces",
""
] |
So most Java resources when speaking of packages mention a `com.yourcompany.project` setup. However, I do not work for a company, and don't have a website. Are there any naming conventions that are common? An email address, perhaps? | Use a top-level domain like 'bernard' or something else unique. The important part is that the domain is unique so that you avoid clashes, and not that it starts with a real Internet top-level domain like org or com. E.g.
```
import java.util.*;
import bernard.myProject.*;
import org.apache.commons.lang.*;
``` | If your creating an open source project, you could register it with Sourceforge and use net.sourceforge.myproject. This is common with a lot of Java projects. An example is PMD <http://pmd.sourceforge.net/>. | How should I name packages if I don't have a domain associated with me? | [
"",
"java",
"namespaces",
"package",
""
] |
Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,
```
set[obj] = true;
```
This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to th... | JavaScript objects can only use strings as keys (anything else is converted to a string).
You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:
```
var ObjectReference = [];
ObjectReference.push(obj);
set['Object... | If you want a hashCode() function like Java's in JavaScript, that is yours:
```
function hashCode(string){
var hash = 0;
for (var i = 0; i < string.length; i++) {
var code = string.charCodeAt(i);
hash = ((hash<<5)-hash)+code;
hash = hash & hash; // Convert to 32bit integer
}
ret... | Is there hash code function accepting any object type? | [
"",
"javascript",
"hash",
"set",
"hashcode",
""
] |
Consider a database table holding names, with three rows:
```
Peter
Paul
Mary
```
Is there an easy way to turn this into a single string of `Peter, Paul, Mary`? | If you are on SQL Server 2017 or Azure, see [Mathieu Renda answer](https://stackoverflow.com/a/42778050/1178676).
I had a similar issue when I was trying to join two tables with one-to-many relationships. In SQL 2005 I found that `XML PATH` method can handle the concatenation of the rows very easily.
If there is a ta... | > **This answer may return [unexpected results](https://stackoverflow.com/questions/15138593/nvarchar-concatenation-index-nvarcharmax-inexplicable-behavior/15163136#15163136) For consistent results, use one of the FOR XML PATH methods detailed in other answers.**
Use `COALESCE`:
```
DECLARE @Names VARCHAR(8000)
SELE... | How to concatenate text from multiple rows into a single text string in SQL Server | [
"",
"sql",
"sql-server",
"csv",
"string-concatenation",
"group-concat",
""
] |
I'm looking for some succinct, modern C# code to generate a random date between Jan 1 1995 and the current date.
I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct. | ```
private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}
```
For better performance if this will be called repeatedly, create the `start` and `gen` (and maybe even ... | This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.
```
Func<DateTime> RandomDayFunc()
{
DateTime start = new DateTime(1995, 1, 1);
R... | Random date in C# | [
"",
"c#",
"datetime",
"random",
"date",
""
] |
I have a pretty standard django app, and am wondering how to set the url routing so that I don't have to explicitly map each url to a view.
For example, let's say that I have the following views: `Project, Links, Profile, Contact`. I'd rather not have my `urlpatterns` look like this:
```
(r'^Project/$', 'mysite.app.v... | ```
mods = ('Project','Links','Profile','Contact')
urlpatterns = patterns('',
*(('^%s/$'%n, 'mysite.app.views.%s'%n.lower()) for n in mods)
)
``` | Unless you have a really *huge* number of views, writing them down explicitly is not too bad, from a style perspective.
You can shorten your example, though, by using the prefix argument of the `patterns` function:
```
urlpatterns = patterns('mysite.app.views',
(r'^Project/$', 'project'),
(r'^Links/$', 'links... | Django: How do I create a generic url routing to views? | [
"",
"python",
"django",
"pylons",
""
] |
I have an XmlDocument that already exists and is read from a file.
I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls?
I would like some way of making a string or stringBuilder of a v... | I suggest using [XmlDocument.CreateDocumentFragment](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createdocumentfragment.aspx) if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuild... | Try this:
```
employeeNode.InnerXml = "<Demographic><Age/><DOB/></Demographic>";
```
Alternatively (if you have another XML document that you want to use):
```
employeeNode.AppendChild(employeeNode.OwnerDocument.ImportNode(otherXmlDocument.DocumentElement, true));
``` | Append XML string block to existing XmlDocument | [
"",
"c#",
"xml",
""
] |
Is a new (or different) instance of `TestCase` object is used to run each test method in a JUnit test case? Or one instance is reused for all the tests?
```
public class MyTest extends TestCase {
public void testSomething() { ... }
public void testSomethingElse() { ... }
}
```
While running this test, how many in... | I couldn't find a clear answer in the JUnit docs about your question, but the intent, as anjanb wrote, is that each test is independent of the others, so a new TestCase instance could be created for each test to be run.
If you have expensive test setup ("*fixtures*") that you want to be shared across all test cases in... | Yes, a separate instance is created.
While running that test, 2 instances of MyTest gets created.
If you want a different behavior, one option is to use a similar tool called TestNG(<http://testng.org/doc/>). | JUnit TestCase object instantiation | [
"",
"java",
"junit",
"instantiation",
"testcase",
""
] |
I've just found out about Stack Overflow and I'm just checking if there are ideas for a constraint I'm having with some friends in a project, though this is more of a theoretical question to which I've been trying to find an answer for some time.
I'm not much given into cryptography but if I'm not clear enough I'll tr... | You can do it the way you describe - effectively querying the hash, say, but there's not many systems with that requirement, because at that point the security requirements are interfering with other requirements for the system to be usable - i.e. no partial matches, since the encryption rules that out. It's the same p... | why not encrypt the disk holding the database tables, encrypt the database connections, and let the database operate normally?
[i don't really understand the context/contraints that require this level of paranoia]
EDIT: "law constraints" eh? I hope you're not involved in anything illegal, I'd hate to be an inadverten... | Encrypted database query | [
"",
"sql",
"database",
"encryption",
"theory",
""
] |
When is it better to use a [List](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1) vs a [LinkedList](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1)? | ## Edit
> Please read the comments to this answer. People claim I did not do
> proper tests. I agree this should not be an accepted answer. As I was
> learning I did some tests and felt like sharing them.
## Original answer...
I found interesting results:
```
// Temporary class to show the example
class Temp
{
... | In most cases, `List<T>` is more useful. `LinkedList<T>` will have less cost when adding/removing items in the middle of the list, whereas `List<T>` can only cheaply add/remove at the *end* of the list.
`LinkedList<T>` is only at it's most efficient if you are accessing sequential data (either forwards or backwards) -... | When should I use a List vs a LinkedList | [
"",
"c#",
".net",
"vb.net",
"data-structures",
"linked-list",
""
] |
What is the easiest way to find out how much memory an object uses in .NET?
Preferably without having to resort to a third party tool. Marshal.SizeOf or the sizeof operator look useful but only work with a restricted range of types.
Some related posts:
* [Object Memory Analysis in .NET](https://stackoverflow.com/que... | you could also do something like this:
```
int startMem = GC.GetTotalMemory(true);
YourClass c = new YourClass();
int endMem = GC.GetTotalMemory(true);
int usedMeme = endMem - startMem;
``` | Asked and answered here: [Determine how much memory a class uses?](https://stackoverflow.com/questions/51540/determine-how-much-memory-a-class-uses#51895)
The quick summary is that if you don't want to use a tool, you need to use the [.NET Profiling API](http://msdn.microsoft.com/en-us/library/ms404386.aspx)
The Prof... | What is the easiest way to find out how much memory an object uses in .NET? | [
"",
"c#",
".net",
"memory",
""
] |
I got one big question.
I got a linq query to put it simply looks like this:
```
from xx in table
where xx.uid.ToString().Contains(string[])
select xx
```
The values of the `string[]` array would be numbers like (1,45,20,10,etc...)
the Default for `.Contains` is `.Contains(string)`.
I need it to do this instead: `... | spoulson has it nearly right, but you need to create a `List<string>` from `string[]` first. Actually a `List<int>` would be better if uid is also `int`. `List<T>` supports `Contains()`. Doing `uid.ToString().Contains(string[])` would imply that the uid as a string contains all of the values of the array as a substring... | If you are truly looking to replicate *Contains*, but for an array, here is an [extension method](http://msdn.microsoft.com/en-us/library/bb383977.aspx) and sample code for usage:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ContainsAnyThingy
{
class Program
... | How do I use LINQ Contains(string[]) instead of Contains(string) | [
"",
"c#",
"linq",
"string",
"contains",
""
] |
I'd love to figure it out myself but I was wondering **roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?** For example how does C# turn this:
```
IEnumerator<string> strings(IEnumerable<string> args)
{ IEnumerator<string> enumerator2 = getAnotherEnume... | The particular code sample you are looking at involves a series of transformations.
Please note that this is an approximate description of the algorithm. The actual names used by the compiler and the exact code it generates may be different. The idea is the same, however.
The first transformation is the "foreach" tran... | Just spotted this question - I [wrote an article](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx) on it recently. I'll have to add the other links mentioned here to the article though... | Algorithm for implementing C# yield statement | [
"",
"c#",
"algorithm",
"compiler-construction",
"iterator",
"state-machine",
""
] |
On my homepage I got:
```
<ul id="login">
<li> <a id="loginswitch" href="./login-page">log-in</a> | </li>
<li> <a id="signupswitch" href="./signup-page">sign-up</a> </li>
</ul>
```
Via MooTools, I get these anchor elements by id so that once they're clicked, a flashy div will popup below them that contains the lo... | ```
window.location = self.location;
```
**This JavaScript is executing**.
When it executes, the browser is being told to replace the value of `window.location` with a new value. **Not all browsers** will react the same way here. Some will probably work as you expect, but others will get smart about it and compare th... | Going to an anchor on a page -- which is what `#` signifies -- does not require a reload. | Reloading a page via AJAX when window.location=self.location doesn't work | [
"",
"javascript",
"browser",
"caching",
"reload",
""
] |
I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. I'm using php, and at the moment this little snippet is responsible for generating the UID:
```
$id = tempnam (".", "");
unlink($id);
$id = substr($id, 2);
```
This code is hideous: it creates a temporary file... | ```
string uniqid ([ string $prefix [, bool $more_entropy ]] )
```
Gets a prefixed unique identifier based on the current time in microseconds.
```
USAGE: $id = uniqid(rand(), true);
``` | Since both uniqid() and rand() are functions based on the current time, rand() adds almost no entropy, since the time will change only a tiny amount between the respective calls.
As long as you use the `more_entropy` option, you should never have a collision within a single server. If you use clustering, be sure to in... | Generating a unique ID in PHP | [
"",
"php",
"guid",
"unique",
"uuid",
"identifier",
""
] |
Let's say:
```
<div>
pre text
<div class="remove-just-this">
<p>child foo</p>
<p>child bar</p>
nested text
</div>
post text
</div>
```
to this:
```
<div>
pre text
<p>child foo</p>
<p>child bar</p>
nested text
post text
</div>
```
I've been figuring out using Mootools, jQuery and even (... | Using [jQuery](http://jquery.com/) you can do this:
```
var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);
```
Quick links to the documentation:
* [contents](http://docs.jquery.com/Traversing/contents)( ) : *jQuery*
* [replaceWith](http://docs.jquery.com/Manipulation/replaceWith)( ... | The library-independent method is to insert all child nodes of the element to be removed before itself (which implicitly removes them from their old position), before you remove it:
```
while (nodeToBeRemoved.firstChild)
{
nodeToBeRemoved.parentNode.insertBefore(nodeToBeRemoved.firstChild,
... | How to remove only the parent element and not its child elements in JavaScript? | [
"",
"javascript",
"dom",
""
] |
I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?
Very ... | ```
string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);
```
Output:
```
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
`... | Unfortunately no, it's not as easy as a FormatXMLForOutput method, this is Microsoft were talking about here ;)
Anyway, as of .NET 2.0, the recommended approach is to use the XMlWriterSettingsClass to set up formatting, as opposed to setting properties directly on the XmlTextWriter object. [See this MSDN page](http://... | In C#, what is the best method to format a string as XML? | [
"",
"c#",
"xml",
"string",
"formatting",
"string-formatting",
""
] |
Has anyone got this working in a web application?
No matter what I do it seems that my appSettings section (redirected from web.config using appSettings file=".\Site\site.config") does not get reloaded.
Am I doomed to the case of having to just restart the application? I was hoping this method would lead me to a more... | Make sure you are passing the correct [case sensitive](http://en.wikipedia.org/wiki/Case_sensitivity) value to RefreshSection, i.e.
```
ConfigurationManager.RefreshSection("appSettings");
``` | This seems to be a flaw (maybe a bug) when using an external config file for your appSettings. I've tried it using the configSource attribute and RefreshSection simply never works, I'm assuming this is the same when using the file attribute.
If you move your appSettings back inside your web.config RefreshSection will w... | Reloading configuration without restarting application using ConfigurationManager.RefreshSection | [
"",
"c#",
"asp.net",
"performance",
"settings",
""
] |
I hope this isn't considered a duplicate since it's more pointed than similar questions (I'm curious about a specific weakness in C# to VB.net conversion utilities).
I've been looking at using a tool like this [.net code converter](http://www.developerfusion.com/tools/convert/csharp-to-vb/) to convert a class library ... | We've now updated the code generator to support this scenario. If you spot any others that we're not doing very well, please do drop me a line. | I'd recommend compiling the code and using something like Red-Gate's reflector <http://www.red-gate.com/products/reflector/index.htm> to handle the conversion. Now it's not "perfect," and I'm not sure if it handles automatic properties (though I'd imagine it would).
What makes this possible is that when you compile .N... | A C# to VB.Net conversion utility that handles Automatic properties correctly? | [
"",
"c#",
"vb.net",
"automatic-properties",
""
] |
I need to evaluate a mathmatical expression that is presented to me as a string in C#. Example noddy but gets the point across that the string as the expression.
I need the evaluate to then populate an int.
There is no Eval() in C# like in others langugaes...
```
String myString = "3*4";
```
Edit:
I am on VS2008
... | The way I see it, you have two options - use an expression evaluator or construct, compile
and run C# code on the fly.
I would go with an expression evaluator library, as you do not have to worry about any security issues. That is, you might not be able to use code generation in medium trust environments, such as most... | All the other answers are possible overkill.
If all you need is simple arithmetic, do this.
```
DataTable dummy = new DataTable();
Console.WriteLine(dummy.Compute("15 / 3",string.Empty));
```
EDIT: a little more information. Check out the MSDN documentation for the `Expression` property of the `System.Data.DataColum... | operators as strings | [
"",
"c#",
""
] |
I'd like to get all the permutations of swapped characters pairs of a string. For example:
Base string: `abcd`
Combinations:
1. `bacd`
2. `acbd`
3. `abdc`
etc.
### Edit
I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.
What's the best wa... | Edit: Markdown hates me today...
```
$input = "abcd";
$len = strlen($input);
$output = array();
for ($i = 0; $i < $len - 1; ++$i) {
$output[] = substr($input, 0, $i)
. substr($input, $i + 1, 1)
. substr($input, $i, 1)
. substr($input, $i + 2);
}
print_r($output);
``` | nickf made beautiful solution thank you , i came up with less beautiful:
```
$arr=array(0=>'a',1=>'b',2=>'c',3=>'d');
for($i=0;$i<count($arr)-1;$i++){
$swapped="";
//Make normal before swapped
for($z=0;$z<$i;$z++){
$swapped.=$arr[$z];
}
//Create swapped
$i1=$i+1;
$swapped.=$arr[$i1].$arr[$i];
/... | Swap every pair of characters in string | [
"",
"php",
"string",
""
] |
As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:
```
centroid = average(x), average(y), average(z)
```
where `x`, `y` and `z` are arrays of floating-point num... | Contrary to the common refrain here, there are different ways to define (and calculate) a center of a point cloud. The first and most common solution has been suggested by you already and I will **not** argue that there is anything wrong with this:
`centroid = average(x), average(y), average(z)`
The "problem" here is... | You vaguely mention "a way to get a more accurate centroid". Maybe you're talking about a centroid that isn't affected by outliers. For example, the *average* household income in the USA is probably very high, because a small number of *very* rich people skew the average; they are the "outliers". For that reason, stati... | What's the best way to calculate a 3D (or n-D) centroid? | [
"",
"python",
"math",
"3d",
"geometry",
""
] |
How do I parse the first, middle, and last name out of a fullname field with SQL?
I need to try to match up on names that are not a direct match on full name. I'd like to be able to take the full name field and break it up into first, middle and last name.
The data does not include any prefixes or suffixes. The middl... | Here is a self-contained example, with easily manipulated test data.
With this example, if you have a name with more than three parts, then all the "extra" stuff will get put in the LAST\_NAME field. An exception is made for specific strings that are identified as "titles", such as "DR", "MRS", and "MR".
If the middl... | Alternative simple way is to use `parsename` :
```
select full_name,
parsename(replace(full_name, ' ', '.'), 3) as FirstName,
parsename(replace(full_name, ' ', '.'), 2) as MiddleName,
parsename(replace(full_name, ' ', '.'), 1) as LastName
from YourTableName
```
[source](https://dba.stackexchange.com/a/42398... | SQL: parse the first, middle and last name from a fullname field | [
"",
"sql",
"sql-server",
"t-sql",
"parsing",
""
] |
In VB.NET I often `Catch…When`:
```
Try
…
Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES"
…
End Try
```
Is there a C# equivalent to `Catch…When`?
I don't want to resort to using an `if` statement inside a `catch` if possible. | This functionality was announced for C# 6. It is now possible to write
```
try { … }
catch (MyException e) when (myfilter(e))
{
…
}
```
You can download the preview of [Visual Studio 2015](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx) now to check this out, or wait for the offi... | There's no equivalent to `Catch…When` in C#. You will really have to resort to an `if` statement inside your `catch`, then rethrow if your condition isn't fulfilled:
```
try
{
…
}
catch (ArgumentNullException e)
{
if ("SAMPLES" == e.ParamName.ToUpper())
{
… // handle exception
}
else
{
... | C# equivalent to VB.NET's Catch...When | [
"",
"c#",
"vb.net",
"exception",
"vb.net-to-c#",
""
] |
I am making extensive use of `boost:shared_ptr` in my code. In fact, most of the objects that are allocated on the heap are held by a `shared_ptr`. Unfortunately this means that I can't pass `this` into any function that takes a `shared_ptr`. Consider this code:
```
void bar(boost::shared_ptr<Foo> pFoo)
{
...
}
v... | You can derive from [enable\_shared\_from\_this](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/enable_shared_from_this.html) and then you can use "shared\_from\_this()" instead of "this" to spawn a shared pointer to your own self object.
Example in the link:
```
#include <boost/enable_shared_from_this.hpp>
cla... | Just use a raw pointer for your function parameter instead of the shared\_ptr. The purpose of a smart pointer is to control the lifetime of the object, but the object lifetime is already guaranteed by C++ scoping rules: it will exist for at least as long as the end of your function. That is, the calling code can't poss... | Getting a boost::shared_ptr for this | [
"",
"c++",
"boost",
""
] |
Is there any easy way to create a class that uses **IFormatProvider** that writes out a user-friendly file-size?
```
public static string GetFileSizeString(string filePath)
{
FileInfo info = new FileInfo(@"c:\windows\notepad.exe");
long size = info.Length;
string sizeString = size.ToString(FileSizeFormatPr... | I use this one, I get it from the web
```
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return null;
}
private const string fileSizeFormat = "fs";
private... | OK I'm not going to wrap it up as a Format provider but rather than reinventing the wheel there's a Win32 api call to format a size string based on supplied bytes that I've used many times in various applications.
```
[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
public static extern long StrFormatByteSize( long ... | File-size format provider | [
"",
"c#",
"formatting",
"filesize",
""
] |
What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:
```
class foo
{
private:
static int i;
};
int foo::i = 0;
```
I'm guessing this is because I can't initialize a private member from outside the class. So what's th... | The class declaration should be in the header file, or in the source file, if the class is not used in other files.
```
// foo.h
class foo
{
private:
static int i;
};
```
However, the initialization should be in the source file.
```
// foo.cpp
int foo::i = 0;
```
If the initialization is in the header f... | For a **variable**:
foo.h:
```
class foo
{
private:
static int i;
};
```
foo.cpp:
```
int foo::i = 0;
```
This is because there can only be one instance of `foo::i` in your program. It's sort of the equivalent of `extern int i` in a header file and `int i` in a source file.
For a **constant** you can put the ... | How to initialize private static data members in a header file | [
"",
"c++",
"initialization",
"header-files",
"static-members",
""
] |
How can I disable all table constrains in Oracle with a single command?
This can be either for a single table, a list of tables, or for all tables. | It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL\*Plus or put this thing into a package or procedure. The join to USER\_TABLES is there to avoid view constraints.
It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc).... | To take in count the dependencies between the constraints:
```
SET Serveroutput ON
BEGIN
FOR c IN
(SELECT c.owner,c.table_name,c.constraint_name
FROM user_constraints c,user_tables t
WHERE c.table_name=t.table_name
AND c.status='ENABLED'
ORDER BY c.constraint_type DESC,c.last_change DESC
)
... | Disable all table constraints in Oracle | [
"",
"sql",
"oracle",
""
] |
Since generics were introduced, Class is parametrized, so that List.class produces Class<List>. This is clear.
What I am not able to figure out is how to get a instance of Class of type which is parametrized itself, i.e. Class<List<String>>. Like in this snippet:
```
public class GenTest {
static <T> T instantiat... | The Class class is a run-time representation of a type. Since parametrized types undergo type erasure at runtime, the class object for Class would be the same as for Class<List<Integer>> and Class<List<String>>.
The reason you cannot instantiate them using the .class notation is that this is a special syntax used for ... | Classes represent classes loaded by a class loader, which are raw types. To represent a parameterized type, use java.lang.reflect.ParameterizedType. | How to get parametrized Class instance | [
"",
"java",
"generics",
""
] |
My group is a Perl shop in an organization that is very heterogenous. Although we support the odd Java, PHP, or Python installation, we're using Perl for nearly all of our web applications and systems/data marshalling tasks. All of our boxes are Linux, although we interface with IIS systems as well.
We're coming under... | Is there a specific technical reason for switching to Java? Is there something you can do in Java but not Perl? Is there a performance difference? Is some other group/person all about Java and doesn't want to learn Perl?
My experience has been that you should stick with what you know. Your group knows Perl really well... | If your team is going to be supporting the applications, then stick with what you know.
If another team is supporting your apps then you may need to consider Java as it definetly has a greater penetration in today's corporate world.
Management are told that Java is the only way, or "real enterprises use Java", and th... | Java development in a Perl shop: How to select the right tool? | [
"",
"java",
"perl",
""
] |
I am trying to copy a file using the following code:
```
File targetFile = new File(targetPath + File.separator + filename);
...
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = f... | Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename:
```
File targetFile = new File(targetPath, filename);
``` | This can occur when filename has timestamp with colons, eg. `myfile_HH:mm:ss.csv` Removing colons fixed the issue. | What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect" | [
"",
"java",
"exception",
"file-io",
""
] |
I am wondering what security concerns there are to implementing a `PHP evaluator` like this:
```
<?php eval($_POST['codeInput']); %>
```
This is in the context of making a `PHP sandbox` so sanitising against `DB input` etc. isn't a massive issue.
Users destroying the server the file is hosted on is.
I've seen `Ruby... | could potentially be in really big trouble if you `eval()`'d something like
```
<?php
eval("shell_exec(\"rm -rf {$_SERVER['DOCUMENT_ROOT']}\");");
?>
```
it's an extreme example but it that case your site would just get deleted. hopefully your permissions wouldn't allow it but, it helps illustrate the need for san... | don't do that.
they basically have access to anything you can do in PHP (look around the file system, get/set any sort of variables, open connections to other machines to insert code to run, etc...) | What are the security concerns of evaluating user code? | [
"",
"php",
"security",
""
] |
This snippet works well if I try to write in a user directory but as soon as I try to write in Program Files, it just executes silently and the file has not been copied (no exception). If I try to copy the file in C:\ or in C:\Windows I catch an UnauthorizedAccessException.
Do you know another way to get the permissio... | If you are running under Vista then the system just redirects writes to the program files folder, this is done so old program that keep their configuration in the program directory will continue to work when the user is not an Admin (or UAC is enabled).
All you have to do is add a manifest to your program that specify... | **Don't write in the Program Files folder.**
That's a big no-no, and will especially cause problems when the day comes where your code runs in Vista or on a machine at a company where users only get standard security rather than admin rights. Use the Application Data folder instead. | Can't copy file with appropriate permissions using FileIOPermission | [
"",
"c#",
"file",
"permissions",
"copy",
""
] |
I'm trying to use boost::signal to implement a callback mechanism, and I'm getting a memory access assert in the boost::signal code on even the most trivial usage of the library. I have simplified it down to this code:
```
#include <boost/signal.hpp>
typedef boost::signal<void (void)> Event;
int main(int argc, char*... | I've tested your code on my system, and it works fine. I think that there's a mismatch between your compiler, and the compiler that your Boost.Signals library is built on. Try to download the Boost source, and compile Boost.Signals using the same compiler as you use for building your code.
Just for my info, what compi... | I have confirmed this as a problem - Stephan T Lavavej (STL!) at Microsoft [blogged about this](http://blogs.msdn.com/vcblog/archive/2007/02/26/stl-destructor-of-bugs.aspx).
Specifically, he said:
> The general problem is that the linker does not diagnose all One Definition Rule (ODR) violations. Although not impossi... | Boost::signal memory access error | [
"",
"c++",
"boost-signals",
""
] |
On an ASP.NET website, are static classes unique to each web request, or are they instantiated whenever needed and GCed whenever the GC decides to disposed of them?
The reason I ask is because I've written some static classes before in C# and the behavior is different than I would have expected. I would have expected ... | Your static classes and static instance fields are shared between all requests to the application, and has the same lifetime as the application domain. Therefore, you should be careful when using static instances, since you might have synchronization issues and the like. Also bear in mind, that static instances will no... | Static members have a scope of the current worker process only, so it has nothing to do with requests, because different requests may or may not be handled by the same worker process.
* In order to share data with a specific user and across requests, use HttpContext.Current.Session.
* In order to share data within a s... | Are static class instances unique to a request or a server in ASP.NET? | [
"",
"c#",
"asp.net",
"static",
""
] |
I have a database issue that i currently cannot wrap my head around with an easy solution. In my db I have a table that stores event values.. 0's and 1's with a timestamp. Issue being that it is possible for there to be the same event to occur twice as a business rule. Like below
* '2008-09-22 16:28:14.133', 0
* '2008... | This uses a SQL Server Common Table Expression, but it can be inlined, with table t with columns dt and cyclestate:
```
;WITH Firsts AS (
SELECT t1.dt
,MIN(t2.dt) AS Prevdt
FROM t AS t1
INNER JOIN t AS t2
ON t1.dt < t2.dt
AND t2.cyclestate <> t1.cyclestate
GROUP BY t1.dt
)
SELEC... | (preface.......i've only done this in oracle, but I'm pretty sure if the db supports triggers it's all possible)
Have a before insert trigger that selects the row with the max timestamp value. If that row's value is the same as the one you wish to insert, ignore it.
This should keep them all in a correct state.
Now,... | Filtering out duplicate values at runtime in a sql database - set based | [
"",
"sql",
"filtered-lookup",
""
] |
Greetings!
I am trying to check directory write-permissions from within a Windows MFC/ATL program using C++. My first guess is to use the C-standard \_access function, e.g.:
```
if (_access("C:\mydir", 2) == -1)
// Directory is not writable.
```
But apparently on Windows 2000 and XP, \_access can't determine dire... | You can call CreateFile with GENERIC\_WRITE access to check this.
<http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx>
It's not a C++ library but it still counts as elegant because it directly does what you want... | Use sec api.
You can ask on Adv. Win32 api newsgroup :
news://194.177.96.26/comp.os.ms-windows.programmer.win32
where it has often been discussed (C/C++ code) | Code for checking write-permissions for directories in Win2K/XP | [
"",
"c++",
"windows",
"security",
"permissions",
"atl",
""
] |
Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on you... | Okay, I figured it out. I will post it here in case it help anyone else. This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think.
```
var MenuManager = Class.create({
initialize: function initialize(menuElt) {
... | Thanks for the effort of sharing this code.
I made some small changes to make it work with the current release of Prototype.
```
var TableHeaderManager = Class.create({
initialize: function initialize(headerElt) {
this.tableHeader = $(headerElt);
this.homePosn = { x: this.tableHeader.cumulativeOffs... | How can I get a fixed-position menu like slashdot's comment filtration menu | [
"",
"javascript",
"css",
""
] |
Sometimes when using eclipse it loses references to the JRE.
i.e. It cannot find classes like Object or Arraylist.
Some projects report a problem while others don't and they both use the same JRE.
I have found that if you switch the installed JRE to another and then back again to the one you want to use, it will the... | I may have a resolution for this. Eclipse was losing the JRE references on many of my Java projects almost daily, and restarting or starting with -clean wasn't helping. I realised that it is clearly a classloader issue of some kind, so what I did was to open the ".classpath" file of each project in the editor and manua... | The JRE reference in your project is stored using the name you give it in the Installed JREs preference page. Change the name and you break the reference. Just pick names you can keep reusing when switching JREs, or select the workspace default as the JRE for the project. | How to stop Eclipse 3.4 losing reference to the JRE in projects | [
"",
"java",
"eclipse",
"eclipse-3.4",
"ganymede",
""
] |
I've just started using Java's enums in my own projects (I have to use JDK 1.4 at work) and I am confused as to the best practice of using JavaDoc for an enum.
I have found that this method works, but the resultant code is a little unrefined:
```
/**
* Doc for enum
*/
public enum Something {
/**
* First thing
*/
FIRS... | To answer the first part of your question, you do have to separate each enum value with a comma. As far as I know, there's no way around that.
Personally I don't have a problem with the code the way you've presented it. Seems like a perfectly reasonable way to document an enum to me. | As Mike mentioned, you do have to separate the enum values with commas, and they have to be the first things listed in the enum declaration (instance variables, constants, constructors and methods may follow).
I think the best way to document enums is similar to regular classes: the enum type gets a description of the... | What is the best way to use JavaDoc to document a Java enum? | [
"",
"java",
"enums",
"javadoc",
""
] |
Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:
```
<?xml version="1.0" encoding="utf-8" ?>
<myElement>foo</myElement>
```
I want to change the text value of 'foo' to 'bar' resulting in the following:
```
<?xml version="1.0" encoding="utf-8" ?>
<myElement>bar</myElement>... | Use Python's [minidom](http://docs.python.org/library/xml.dom.minidom.html)
Basically you will take the following steps:
1. Read XML data into DOM object
2. Use DOM methods to modify the document
3. Save new DOM object to new XML document
The python spec should hold your hand rather nicely though this process. | For quick, non-critical XML manipulations, i really like [P4X](http://ponderer.org/p4x). It let's you write like this:
```
import p4x
doc = p4x.P4X (open(file).read)
doc.myElement = 'bar'
``` | What is the best way to change text contained in an XML file using Python? | [
"",
"python",
"xml",
"text",
""
] |
I've downloaded the IKVM sources (<http://www.ikvm.net/>) from <http://sourceforge.net/cvs/?group_id=69637>
Now I'm trying to get it to build in Visual Studio 2008 and am stuck. Does anyone know of documentation of how to build the thing, or could even give me pointers?
I've tried opening the ikvm8.sln, which opens a... | OK just got the following reply from the author: <http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf>
> If you want to build from cvs, you're on your own. However, you can more easily build from source if you use an official release.
>
> If you download ikvm-0.36.0.11.zip, classpath-0.95... | I don't know that this would do it for you but can you try building from the command line?
msbuild \_\_\_\_\_\_\_\_
I think that's how I built the application due to the same issues. | How to get IKVM to build in Visual Studio 2008? | [
"",
"c#",
"visual-studio-2008",
"compiler-errors",
"ikvm",
""
] |
Can anyone recommend a good .NET based lexical analyser, preferably written in C#? | ANTLR has a [C# target](http://www.antlr.org/wiki/display/ANTLR3/Antlr+3+CSharp+Target) | Download the Visual Studio SDK; it includes a managed parser/lexer generator.
(Edit: It was written on my university campus, apparantly :D) | Recommendations for a good C#/ .NET based lexical analyser | [
"",
"c#",
"lexical-analysis",
""
] |
When I want to validate my XML docuemnts against a schema in my server-side Java, I use the built-in JRE Xerces implementation and javax.xml.validation.Schema. It works fine, but when validation fails, Xerces gives error messages that are very close to useless, for example:
```
cvc-minLength-valid: Value '' with lengt... | In your handler for the validation, you should receive a SAXParseException with that message, as well as the [column number and the line number](http://xerces.apache.org/xerces2-j/javadocs/api/org/xml/sax/SAXParseException.html#method_summary) in the XML file. Isnt't it the case? | We use [Castor](http://www.castor.org).
> Castor is an Open Source data binding framework for Java[tm]. It's the shortest path between Java objects, XML documents and relational tables. Castor provides Java-to-XML binding, Java-to-SQL persistence, and more. | What do you use for validation against XML schema? | [
"",
"java",
"validation",
"xsd",
""
] |
Some ways to iterate through the characters of a string in Java are:
1. Using `StringTokenizer`?
2. Converting the `String` to a `char[]` and iterating over that.
What is the easiest/best/most correct way to iterate? | I use a for loop to iterate the string and use `charAt()` to get each character to examine it. Since the String is implemented with an array, the `charAt()` method is a constant time operation.
```
String s = "...stuff...";
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
`... | Two options
```
for(int i = 0, n = s.length() ; i < n ; i++) {
char c = s.charAt(i);
}
```
or
```
for(char c : s.toCharArray()) {
// process c
}
```
The first is probably faster, then 2nd is probably more readable. | What is the easiest/best/most correct way to iterate through the characters of a string in Java? | [
"",
"java",
"string",
"iteration",
"character",
"tokenize",
""
] |
I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable `x` is equal to the int `0`. If this is `true` the ABSOLUTE value of the variable `y` is returned... this is when I lose the plot, why would the return statement then go on to include `<= ESPILON`? Surel... | Floating-point math is by its nature inaccurate, so rather than testing for equivalence (which is always a bad idea), instead the developer has chosen a small number (1x10^-14 in this case) as the acceptable tolerance for proximity to zero. The return statement returns a comparison, so what this will do is take the abs... | It returns true if the absolute value of y is <= EPSILON, and false otherwise. The <= is evaluated before the return statement. This code is equivalent:
```
if(x == 0)
{
boolean ret = Math.abs(y) <= EPSILON;
return ret;
}
```
The code isn't simply read from left to right. A simpler example is
```
int x = 3 + 4... | Confusing return statement | [
"",
"java",
"floating-point",
"operator-precedence",
""
] |
.NET has a lot of complex data structures. Unfortunately, some of them are quite similar and I'm not always sure when to use one and when to use another. Most of my C# and VB books talk about them to a certain extent, but they never really go into any real detail.
What's the difference between Array, ArrayList, List, ... | Off the top of my head:
* `Array`\* - represents an old-school memory array - kind of like a alias for a normal `type[]` array. Can enumerate. Can't grow automatically. I would assume very fast insert and retrival speed.
* `ArrayList` - automatically growing array. Adds more overhead. Can enum., probably slower than a... | **If at all possible, use generics.** This includes:
* List instead of ArrayList
* Dictionary instead of HashTable | .Net Data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each? | [
"",
"c#",
".net",
"vb.net",
"arrays",
"data-structures",
""
] |
I'm experiencing what I believe is a circular dependency issue with my PHP application. Please let me know if this is incorrect. Here is the situation:
Two classes, LogManager and DBSession.
DBSession is used to interact with the database, and LogManager is used to log to files. Both are widely used in my application... | Don't extend LogManager, let it be an aggregate type. And delay the choice of where you want to log, i.e.:
```
$logManager = new LogManager();
$dbSession = new DbSession($logManager);
$logManager->add(new FileLog($filename) );
$logManager->add(new DBLog($dbSession) );
```
Where of course FileLog and DBLog share a com... | One of these objects doesn't actually need the other: you guessed it, it's the DBSession. Modify that object so that the logger can be attached to it after construction. | Possible circular dependency issue with PHP application | [
"",
"php",
"oop",
"dependencies",
"instantiation",
"circular-dependency",
""
] |
In Python, you can do this:
```
print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30})
```
What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)
One of the really excellent benefits of this is that you can store the pre-processe... | You can also use
```
printf "1: %<key1>s 2: %<key2>s\n", {:key1 => "value1", :key2 => "value2"}
```
or
```
data = {:key1 => "value1", :key2 => "value2"}
printf "1: %<key1>s 2: %<key2>s\n", data
```
or (this needs ruby 1.9, for the other examples I'm not sure)
```
data = {key1: "value1", key2: "value2"}
printf "1:... | you do it like this:
```
values = {:hello => 'world', :world => 'hello'}
puts "%{world} %{hello}" % values
```
Read this for more info:
<http://ruby.runpaint.org/strings#sprintf-hash>
If you need something more sophisticated, read about ERB, and google template engines.
If you need to generate web pages, emails etc.... | How do I emulate Python's named printf parameters in Ruby? | [
"",
"python",
"ruby",
"string",
"printf",
""
] |
I've inherited a mobile app which sends auth credentials (userid/password) in the clear.
I'd imagine that I have 2 choices:
a) use TLS.
b) write my own auth protocol.
If I choose (b) what are the key guidelines that I must follow to make it it secure.
e.g. how to avoid replay attacks, encryption strategies. | For both *"you can't get sued for it"* and *"reasonably protected"* definitions of 'safe', for a mobile application, you can assume that the line is secure vs man-in-the-middle attacks and wide open to eavesdropping. SSL/TLS sounds the easiest way to go, but this might depend on your carrier and target phones.
If you ... | If you use b), the key guidelines are: Don't. If you want it secure, that is.
Try to stick with a). | Searching for a safe way to do authentication from a mobile app | [
"",
"java",
"security",
"mobile",
""
] |
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericCount
{
class Program
{
static int Count1<T>(T a) where T : IEnumerable<T>
{
return a.Count();
}
static void Main(string[] args)
{
List<str... | You want this
```
static int Count1<T>(IEnumerable<T> a)
{
return a.Count();
}
``` | Your generic constraint is wrong. You cannot enforce it to implement IEnumerabl<T> | Generic method call | [
"",
"c#",
"generics",
""
] |
I am starting my first independent for profit venture. I am having a hard time deciding what language to use. I want to write my app in Perl, but I don't think it will be simple enough to compile. If I don't write it in Perl I will write it in C++.
The application will have many features, including [wxwidgets](http://... | Why not use a hybrid of both? It's generally the way a lot of development is going these days.
I'd suggest a Lua/C++ or a Python/C++ combo (I'm not sure how well a Perl/C++ combo works, but that may be a good option too).
Personally I've done a bunch with the Lua/C++ combo and it's pretty fantastic. | I'm both a C++ and Perl programmer. C++ is a nice language, but whenever I have the choice, I go with Perl since development simply proceeds so much more quickly.
A couple of comments:
1. PAR, perlapp, and perl2exe are not compilers. They are packagers. There is no Perl compiler except perl itself. If you want some f... | New project: I am having troubles picking a language to use | [
"",
"c++",
"perl",
"wxwidgets",
"packaging",
""
] |
Suppose I have a set of values, stored in a std::set:
{1, 2, 6, 8}
and I have a search key, say, 3. I want to put 3 into a function and get the first value greater than or equal to 3, in this case I would want to get 6.
The find() function provided in map/set/multimap/and set will, of course, return the end iterator... | Yes: `upper_bound(X)` returns an iterator pointing to the first element greater than `X`. There is also a `lower_bound(X)` function which returns an iterator pointing to the first element not less than `X`. Thus, all of the elements in the half-open interval `[lower_bound(X), upper_bound(X))` will be equal to X. | You want the [upper\_bound](http://www.sgi.com/tech/stl/upper_bound.html) function.
```
map<int, int> mymap = { 1,2,6,8 };
map<int,int>::iterator i = mymap.upper_bound(3); // returns an iterator to the '6' element.
``` | With a STL map/set/multiset/multimap, How to find the first value greater than or equal to the search key? | [
"",
"c++",
"stl",
"containers",
""
] |
I have some c(++) code that uses sprintf to convert a uint\_64 to a string. This needs to be portable to both linux and Solaris.
On linux we use %ju, but there does not appear to be any equivalent on Solaris. The closest I can find is %lu, but this produces incorrect output. Some sample code:
```
#include <stdio.h>
#... | If you have have inttypes.h available you can use the macros it provides:
```
printf( "%" PRIu64 "\n", val);
```
Not pretty (I seem to be saying that a lot recently), but it works. | On a C99 compliant system:
```
#include <inttypes.h>
uint64_t big = ...;
printf("%" PRIu64 "\n", big);
```
See section 7.8 of the C99 standard.
The specifiers are {PRI,SCN}[diouxX]{N,LEASTN,MAX,FASTN,PTR}
Where PRI is for the printf() family, SCN is for the scanf() family, d and i for signed integral types; o,u,x,... | printf + uint_64 on Solaris 9? | [
"",
"c++",
"c",
"printf",
""
] |
I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas? :
**My Main method:**
```
static void Main(string[] args)
{
No... | This is really ugly and there may be some issues with the string replacement, but it produces the expected results:
```
public static class JSonify
{
public static string GetJsonTable<T>(
this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)
{
string... | Thanks for the quick response.
However, note the required output does not have property names in the "cell" array ( that's why I was using object[]):
"cell":["FAMIA","Familia Arquibaldo",...
vs.
"cell":{"CustomerID":"FAMIA","CompanyName","Familia Arquibaldo",...
The result is meant to be used with a JQuery grid calle... | Dynamic linq:Creating an extension method that produces JSON result | [
"",
"c#",
"linq",
"json",
""
] |
I am designing a contact management system and have come across an interesting issue regarding modeling geographic locations in a consistent way. I would like to be able to record locations associated with a particular person (mailing address(es) for work, school, home, etc.) My thought is to create a table of locales ... | You might want to have a look at Freebase.com as a site that's had some open discussion about what a "location" means and what it means when a location is included in another. These sorts of questions can generate a lot of discussion.
For example, there is the obvious "geographic nesting", but there are less obvious l... | Sounds like a good approach to me. The one thing that I'm not clear on when reading you post is what "parents of themselves" means - if this is to indicate that the locale does not have a parent, you're better off using null than the ID of itself. | Modeling Geographic Locations in an Relational Database | [
"",
"sql",
"database-design",
""
] |
I subscribe to a newsletter from www.sqlservercentral.com that I like because each day I get an email digest with some interesting headlines & summaries of SQL Server articles that are already out there on the web. It's a great way to learn something new a bit at a time.
Is there something like this for C#?
(If your ... | In addition to [codeproject](http://www.codeproject.com/), I believe there are other sites like [C# Corner](http://www.c-sharpcorner.com/), [C# help](http://www.csharphelp.com/) which does the same..
Couple more I found useful (Not specific to C#):
[visualstudiomagazine](http://visualstudiomagazine.com/)
[Dr. Dobb's... | Have you ever considered subscribing to blogs? You can often get better content than the daily subscription emails and if you want can even become a part of the discussion through the comments. Two that are generally good for learning more about the trade and C# are [CodingBetter.com](http://codebetter.com/Default.aspx... | Is there a site that emails out daily C# tips and tricks? | [
"",
"c#",
"newsletter",
""
] |
I'm currently in the planning stage for a web application and I find myself trying to decide on using Grails or Django. From an operation perspective:
1. Which ecosystem is easier to maintain (migrations, backup, disaster recovery etc.)? If using grails it'll probably be a typical tomcat + mysql on linux. If django it... | You can run grails in 256 megs of ram. Many members of the community are doing so. That being said I would say in either platform you want much more ram than that to make sure your performant. But I might also reccomend checking out www.linode.com. You can get quality hosting for a very reasonable cost and adding a bit... | With Java hosting you don't need to do all the stupid tricks with apache, or nginx. Jetty itself can host everything you need, that's how the guys at www.mor.ph do it, and they find it to be pretty fast.
The memory usage that way is pretty minimal, I host mine on a 256MB Ubuntu server from RapidXen, so it's about $10/... | Running a web app in Grails vs Django | [
"",
"python",
"django",
"grails",
"groovy",
"web-applications",
""
] |
Let's look at an example - books. A book can have 1..n authors. An author can have 1..m books. What is a good way to represent all of the authors of a book?
I came up with an idea to create a Books table and an Authors table. The Authors table has a primary AuthorID key the author's name. The Books table has a primary... | Add another table called BookAuthors with columns for BookID, AuthorID, and NameUsed. A NULL value for NameUsed would mean to pull it from the Author's table instead. This is called an Intersection table. | You'd need three tables -
1. Book
2. Author
3. BookAuthors
Book would contain book id, book title, and all the other information you need to collect about the book.
Author would contain author ID as well as other information such as First name, last name that you need to collect about any given author.
BookAuthors ... | How do you deal with m..n relationships in a relational database? | [
"",
"sql",
"database",
"database-design",
""
] |
I'm creating a Firefox extension for demo purposes.
I to call a specific JavaScript function in the document from the extension.
I wrote this in my HTML document (not inside extension, but a page that is loaded by Firefox):
```
document.funcToBeCalled = function() {
// function body
};
```
Then, the extension will... | It is for security reasons that you have limited access to the content page from extension. See [XPCNativeWrapper](http://developer.mozilla.org/en/docs/XPCNativeWrapper) and [Safely accessing content DOM from chrome](http://developer.mozilla.org/en/Safely_accessing_content_DOM_from_chrome),
If you control the page, th... | ```
document.wrappedJSObject.funcToBeCalled();
```
This is **not secure** and allows a malicious page to elevate its permissions to those of your extension... But, it does do what you asked. Read up on the early [greasemonkey vulnerabilities](http://www.oreillynet.com/pub/a/network/2005/11/01/avoid-common-greasemonkey... | How do I execute a page-defined JavaScript function from a Firefox extension? | [
"",
"javascript",
"firefox",
"dom",
"document",
""
] |
Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista?
Some more clarification:
I have written a program that modifies the windows hosts file (c:\Windows\system32\drivers\etc\hosts) in Vista the program will not run and will fail with an exception unless you right-click a... | Do you mean that you want Windows to prompt for elevation when your program is run? This is controlled by adding a UAC manifest to the EXE's resources. [This blog entry](http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx) explains how to create the manifest and how to compile it into a .RES file.
I don't kno... | Following the examples from `Python2x\Lib\site-packages\py2exe\samples\user_access_control` just add `uac_info="requireAdministrator"` to console or windows dict:
```
windows = [{
'script': "admin.py",
'uac_info': "requireAdministrator",
},]
``` | Running compiled python (py2exe) as administrator in Vista | [
"",
"python",
"windows-vista",
"permissions",
"py2exe",
""
] |
I'm trying to do a custom button to my form (which has FormBorderStyle = none) using Visual Studio 2005. I have my 3 states button images in an ImageList linked to the button.
```
this.btnClose.AutoSize = false;
this.btnClose.BackColor = System.Drawing.Color.Transparent;
this.btnClose.BackgroundImageLayout = System.Wi... | The grey background is due to the setting of "System.Windows.Forms.FlatStyle.Flat", it's the default behaviour, since it need to highlight the button when you hover. To eliminate that, you might have to write a custom button class, inherit from the original button and do some custom painting to achieve that.
Btw, inst... | ```
btnClose.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
``` | Custom button in C#: How to remove hover background? | [
"",
"c#",
".net",
"winforms",
"button",
""
] |
Does anyone know of a faster decimal implementation in python?
As the example below demonstrates, the standard library's decimal module is ~100 times slower than `float`.
```
from timeit import Timer
def run(val, the_class):
test = the_class(1)
for c in xrange(10000):
d = the_class(val)
d + ... | The [GMP](http://gmplib.org) library is one of the best arbitrary precision math libraries around, and there is a Python binding available at [GMPY](http://www.aleax.it/gmpy.html). I would try that method. | You can try [cdecimal](http://www.bytereef.org/mpdecimal/index.html):
```
from cdecimal import Decimal
```
As of Python 3.3, the cdecimal implementation is now the built-in implementation of the `decimal` standard library module, so you don't need to install anything. Just use `decimal`.
For Python 2.7, installing `... | Is there a faster alternative to python's Decimal? | [
"",
"python",
"python-decimal",
""
] |
I have a function that looks like this
```
class NSNode {
function insertAfter(NSNode $node) {
...
}
}
```
I'd like to be able to use that function to indicate that the node is being inserted at the start, therefore it is after *nothing*. The way I think about that is that `null` means "nothing", so I... | sure, just set a default "null"
```
function(NSNode $node = null) {
// stuff....
}
```
result being:
```
$obj->insertAfter(); // no error
$obj->insertAfter(new NSNode); // no error
$obj->insertAfter($somevar); // error expected NSNode
``` | No, you can't pass something else to the function as that defeats the purpose of the static typing. In this situation, something like C# nullable would be nice i.e. NSNode?
I'd suggest creating NSNode::insertFirst() although I think that you have it the wrong way round, why is a node inserting itself, shouldn't the co... | PHP5: Specifying a datatype in method parameters | [
"",
"php",
"parameters",
""
] |
How do you set up your .NET development tree? I use a structure like this:
```
-projectname
--config (where I put the configuration files)
--doc (where I put all the document concerning the project: e-mails, documentation)
--tools (all the tools I use: Nunit, Moq)
--lib (all the libraries used by the solution: ... | We use a very similar layout as covered in JP Boodhoo's blog post titled [Directory Structure For Projects](http://blog.developwithpassion.com/2007/10/01/directory-structure-for-projects/). | Check out these other StackOverflow questions...
* [Structure of Projects in Version Control](https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control#16915)
* [Best Practice: Collaborative Environment, Bin Directory, SVN](https://stackoverflow.com/questions/265/best-practice-collaborative-en... | How do you set up your .NET development tree? | [
"",
"c#",
".net",
"development-environment",
""
] |
I am looking for instructions on how to setup a PEAR channel for our project so that we can deploy it with the pear installer. I have searched the web for a while and cannot find any straightforward information. I followed [this tutorial](http://greg.chiaraquartet.net/archives/123-Setting-up-your-own-PEAR-channel-with-... | It looks like you are one of the few people who want to do this. That tutorial you linked to appears to be the latest (!) but the package is still [somewhat in development](http://pear.chiaraquartet.net/index.php?package=Chiara_PEAR_Server). The documentation in that package is also non-existent. It looks like it's up ... | What problems are you encountering on following the tutorial that you linked to?
You could set up your own channel with pirum or the chiara server ( <http://pear.chiaraquartet.net/> ) but you could also look into getting an account on <http://pearfarm.org> and hosting your packages there (or on <http://pearhub.org>). | How to set up your own PEAR Channel? | [
"",
"php",
"deployment",
"pear",
""
] |
I have an asp.net text form that contains numerous decimal fields that are optional. I want to selectively update the database but not inserting a "0" for fields that do not have data (maintaining the null status).
Typically, I would create multiple functions, each with a different signature to handle this. However, I... | [Nullable Types](http://msdn.microsoft.com/en-us/library/b3h38hb0(VS.80).aspx) are meant for the same purpose. They represent value types with the possibility of having no data in them. Presence of value can be checked using HasValue property of these types.
Pseudo code to read the fields:
```
decimal? dValue; // def... | You may be able to define your parameters as nullable decimals. The C# syntax for a nullable value type like this:
```
decimal? rebateAmountOrWhatever;
```
You can then store nulls in the variable and compare the variable to null.
```
new SqlParameter("@RebateAmount",
rebateAmountOrWhatever == null ? (object)DBNu... | Update the database maintaining the Null status | [
"",
"c#",
"asp.net",
"sql-server",
"web-services",
""
] |
Is there anyway to build a solution to target 64 bit environment in vs2003? My solution is native c++ not visual c++. Any help would be greatly appreciated.
cheers,
RWendi | This page on 2003's lack of 64-bit targeting seems to address your issue: <http://www.toymaker.info/Games/html/64_bit.html>.
> The first step was to set up my development environment for 64 bit development. I use Visual Studio 2003 which has little built in support for 64 bit development.
>
> In order to create 64 bit... | As Warren points out, this isn't easy with VS2003. You need to install the x64 compiler from the [platform SDK](http://www.microsoft.com/downloads/details.aspx?FamilyID=a55b6b43-e24f-4ea3-a93e-40c0ec4f68e5&DisplayLang=en).
We ran this way for a couple of years (starting with even earlier versions and the IA64 compiler... | How to build a solution to target 64 bit environment? | [
"",
"c++",
"64-bit",
"visual-studio-2003",
""
] |
Just looking at ways of getting named constants in python.
```
class constant_list:
(A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3)
```
Then of course you can refer to it like so:
```
constant_list.A_CONSTANT
```
I suppose you could use a dictionary, using strings:
```
constant_dic = {
"A_CONSTANT" : 1,
... | For 2.3 or after:
```
class Enumerate(object):
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)
```
To use:
```
codes = Enumerate('FOO BAR BAZ')
```
`codes.BAZ` will be 2 and so on.
If you only have 2.2, precede this with:
```
from __future__ impor... | I find the enumeration class recipe (Active State, [Python Cookbook](http://code.activestate.com/recipes/67107/)) to be very effective.
Plus it has a lookup function which is nice.
Pev | Is there a better way to get a named series of constants (enumeration) in Python? | [
"",
"python",
""
] |
How do I read a time value and then insert it into a TimeSpan variables? | If I understand you correctly you're trying to get some user input in the form of "08:00" and want to store the time in a timespan variable?
So.. something like this?
```
string input = "08:00";
DateTime time;
if (!DateTime.TryParse(input, out time))
{
// invalid input
return;
}
TimeSpan timeSpan = new TimeS... | From [MSDN](http://msdn.microsoft.com/en-us/library/system.timespan.aspx): A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day.
Here's how you... | How do I read a time value and then insert it into a TimeSpan variable | [
"",
"c#",
".net",
"time",
"timespan",
""
] |
I have a web page in which people go to register for my site. I use server side validation to authenticate them. I need to call some Javascript to tell GA that user was or was not registered. Later I need stats on success in registration.
How can I call the GA function on my server side C# code? | I don't think Google Analytics is set up to do what you are trying to do.
You should just be pasting the code into your master page. From there, you should be able to get a good idea of how many people have registered based on how many visited the landing page after they register. | A project i have released under open source allows for easy integration with Google Analytics from .net native code to fire page views, events etc through code.
It's called GaDotNet and can be found here:
<http://www.diaryofaninja.com/projects/details/ga-dot-net> | How do I use Google Analytics in ASP.NET? | [
"",
"c#",
"asp.net",
"google-analytics",
""
] |
Are there are good uses of Partial Classes outside the webforms/winforms generated code scenarios? Or is this feature basically to support that? | It is in part to support scenarios (WebForms, WinForms, LINQ-to-SQL, etc) mixing generated code with programmer code.
There are more reasons to use it. For example, if you have big classes in large, unwieldy files, but the classes have groups of logically related methods, partial classes may be an option to make your ... | I use partial classes as a means of separating out the different sub elements of custom controls that I write. Also, when used with entity creation software, it allows products like LLBLGen to create generated versions of classes, as well as a custom, user edited version, that won't get replaced if the entities need to... | Partial Classes in C# | [
"",
"c#",
"partial-classes",
""
] |
I know this is a subjective question, but why does Hibernate seem to be designed for short lived sessions? Generally in my apps I create DAOs to abstract my data layer, but since I can't predict how the entity objects are going to be used some of its collections are lazy loaded, or I should say fail to load once the se... | Becuase once you move out of your transaction boundary you can't hit the database again without starting a new transaction. Having long running transactions 'just in case' is a bad thing (tm).
I guess you want to lazy load object from your view - take a look [here](http://www.hibernate.org/43.html) for some options. I... | I worked on a desktop app that used EJB and Hibernate. We had to set `lazy=false` everywhere, because when the objects get serialized, they lose their ability to be fetched from the backend. That's just how it goes, unfortunately.
If you are concerned with performance, you could use caching on the backend so that your... | Why does Hibernate seem to be designed for short lived sessions? | [
"",
"java",
"hibernate",
""
] |
Given a simple (id, description) table t1, such as
```
id description
-- -----------
1 Alice
2 Bob
3 Carol
4 David
5 Erica
6 Fred
```
And a parent-child relationship table t2, such as
```
parent child
------ -----
1 2
1 3
4 5
5 6
```
Oracle offers a way of traversing this as ... | In your query, replace T2 with a subquery that joins T1 and T2, and returns parent, child and child description. Then in the sys\_connect\_by\_path function, reference the child description from your subquery. | Based on Mike McAllister's idea, the following uses a derived table to achieve the desired result:
```
select
T.PARENT
,T.CHILD
,sys_connect_by_path(T.CDESC, '/')
from
(
select
t2.parent as PARENT
,t2.child as CHILD
,t1.description as CDESC
... | Joining other tables in oracle tree queries | [
"",
"sql",
"oracle",
"tree",
"connect-by",
""
] |
How do I create a file-like object (same duck type as File) with the contents of a string? | For Python 2.x, use the [StringIO](https://docs.python.org/2/library/stringio.html) module. For example:
```
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
```
I use cStringIO (which is faster), but note that it doesn't [accept Unicode strings that cannot be encoded as plain ASCII strin... | In Python 3.0:
```
import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
```
The output is:
```
'abcdefgh'
``` | How do I wrap a string in a file in Python? | [
"",
"python",
"string",
"file",
"stringio",
""
] |
I need to profile a java application for a customer. It's an eclipse/maven project, so I decided on using eclipse TPTP ( <http://www.eclipse.org/tptp> ).
I tried to install eclipse TPTP through the update manager from a standard eclipse installation, but I gave up because of the unbelievable complex setup and download... | An alternative is to use Netbeans to profile an Eclipse Application.
I have a blog post on the link below that explains how to configure both applications:
<http://www.jroller.com/ortegon/entry/on_profiling_eclipse_rcp_applications>
It works very well. I've been profiling this way from over a year. Easy to use, easy... | [VisualVM 1.1.1](https://visualvm.dev.java.net/) is a nice alternative to using NetBeans, being a standalone app, so you don't have to bring a Maven/Ant/Eclipse project into it's project format. It can see any local Java process upon opening, so just double click your app in the list of Java processes and off you go. Y... | How to set up Eclipse TPTP | [
"",
"java",
"eclipse",
"jakarta-ee",
"profiling",
""
] |
I have just found a static nested interface in our code-base.
```
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
```
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would... | The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter t... | The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a `Listener`. If you had a class `Foo` and you wanted other classes to be able to listen for events on it, you could declare an interface named `FooListen... | Why would a static nested interface be used in Java? | [
"",
"java",
"interface",
"static",
""
] |
I enjoy developing algorithms using the STL, however, I have this recurring problem where my data sets are too large for the heap.
I have been searching for drop-in replacements for STL containers and algorithms which are disk-backed, i.e. the data structures on stored on disk rather than the heap.
A friend recently ... | I have implemented some thing very similar. Implementing the iterators is the most challenging. I used **[boost::iterator\_facade](http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/iterator_facade.html)** to implement the iterators. Using `boost::iterator_facade` you can **easy adapt** any cached on **disk data st... | I've never had to do anything quite like this, but It might be possible to do what you want to do by writing a custom allocator that makes use of a memory mapped files to back your data.
See [boost::interprocesses](http://www.boost.org/doc/libs/1_36_0/doc/html/interprocess/sharedmemorybetweenprocesses.html#interproces... | Disk-backed STL container classes? | [
"",
"c++",
"algorithm",
"data-structures",
"stl",
"on-disk",
""
] |
I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower [CamelCasing](http://en.wikipedia.org/wiki/CamelCase). They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables... | I use what the Framework uses, as it's the de-facto best practice. However, so long as the code in your company is **consistently** using their style, then you're much better off getting used to it. If every developer has their own standard, then there's no standard at all. | A link to the official [design guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/) might help. Specifically, read the section on [Capitalization styles](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions#capitalizing-compound-words-and-common-ter... | Pascal casing or Camel Casing for C# code? | [
"",
"c#",
".net",
"naming-conventions",
"standards",
""
] |
I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However... | **Session Cookies**
Remember that HTTP is **stateless**, so sessions are tracked on your server, but the **client** has to identify itself with each request. When you declare session\_start(), **your browser is usually setting a cookie** (the "PHP Session Id"), and then identifying itself by sending the cookie value w... | *Will a PHP session only be created if a browser is requesting the page?*
**Short answer**: Yes. Sessions were created specifically to solve the HTTP stateless problem by leveraging browser features. APC, memcached, DB, etc. don't matter. Those are just storage methods for the session, and will suffer from the same pr... | In PHP will a session be created if a browser is not used | [
"",
"php",
"session",
"browser",
""
] |
I'm looking for an add-in to VS2008 that can enable structural highlighting (**vertical** lines in blocks of code) in the C# code editor.
I tried out CodeRush, but while the structural highlighting was great, I was annoyed with all the other stuff in CodeRush. No matter how much I disabled in the options, I couldn't q... | While browsing the [ViEmu](http://viemu.com) site, I saw the [Codekana](http://codekana.com) product which looks like it may do what you want. | Is the Indentation Guide from the [SlickEdit Free Gadgets](http://www.slickedit.com/content/view/441) what you're looking for? | C# structural highlighting in Visual Studio 2008 | [
"",
"c#",
"visual-studio",
""
] |
[Ryan Delucchi](https://stackoverflow.com/users/9931/ryan-delucchi) asked [here](https://stackoverflow.com/questions/194698/how-to-load-a-jar-file-at-runtime#194712) in comment #3 to [Tom Hawtin](https://stackoverflow.com/users/4725/tom-hawtin-tackline)'s answer:
> why is Class.newInstance() "evil"?
this in response ... | The Java API documentation explains why (<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()>):
> Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would... | One more reason:
Modern IDEs allow you to find class usages - it helps during refactoring, if you and your IDE know what code is using class that you plan to change.
When you don't do an explicit usage of the constructor, but use Class.newInstance() instead, you risk not to find that usage during refactoring and this... | Why is Class.newInstance() "evil"? | [
"",
"java",
"constructor",
"runtime",
"instantiation",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.