Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
oOo a highly exciting build issue. Compact framework occasionally goes funny when building. Usually when messing with xmta files but this is the first time i've seen it go awry in this scenario.
I created a abstract base class with an abstract method. Placed this in one of my core dlls. This was fine. I then, in a "la... | If I make the method virtual as opposed to abstract the problem disappears. | It's an issue with genasm in Visual Studio 2005/2008, that it must instantiate types to generate the asmmeta files, so you can't have public abstract types, unfortunately.
Check this [MSDN thread](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=96477&SiteID=1) with a similar issue,(with generics). There's also s... | Error 1150 genasm.exe(1) : error There was an error finalizing type . Method 'DoParse' | [
"",
"c#",
".net",
"compact-framework",
""
] |
I realize that CHAR is recommended if all my values are fixed-width. But, so what? Why not just pick VARCHAR for all text fields just to be safe. | The general rule is to pick **CHAR** if all rows will have close to the *same length*. Pick **VARCHAR** (or *NVARCHAR*) when the *length varies* significantly. CHAR may also be a bit faster because all the rows are of the same length.
It varies by DB implementation, but generally, VARCHAR (or *NVARCHAR*) uses one or t... | If you're working with me and you're working with Oracle, I would probably make you use `varchar` in almost every circumstance. The assumption that `char` uses less processing power than `varchar` may be true...for now...but database engines get better over time and this sort of general rule has the making of a future ... | What are the use cases for selecting CHAR over VARCHAR in SQL? | [
"",
"sql",
"t-sql",
""
] |
I have the following class
```
public class Car
{
public Name {get; set;}
}
```
and I want to bind this programmatically to a text box.
How do I do that?
Shooting in the dark:
```
...
Car car = new Car();
TextEdit editBox = new TextEdit();
editBox.DataBinding.Add("Name", car, "Car - Name");
...
```
I get the f... | You want
```
editBox.DataBindings.Add("Text", car, "Name");
```
The first parameter is the name of the property on the control that you want to be databound, the second is the data source, the third parameter is the property on the data source that you want to bind to. | Without looking at the syntax, I'm pretty sure it's:
```
editBox.DataBinding.Add("Text", car, "Name");
``` | How can I do Databinding in c#? | [
"",
"c#",
"winforms",
"data-binding",
""
] |
I am using Java 1.4 with Log4J.
Some of my code involves serializing and deserializing value objects (POJOs).
Each of my POJOs declares a logger with
```
private final Logger log = Logger.getLogger(getClass());
```
The serializer complains of org.apache.log4j.Logger not being Serializable.
Should I use
```
privat... | How about using a static logger? Or do you need a different logger reference for each instance of the class? Static fields are not serialized by default; you can explicitly declare fields to serialize with a private, static, final array of `ObjectStreamField` named `serialPersistentFields`. [See Oracle documentation](h... | The logger must be static; this would make it non-serializable.
There's no reason to make logger non-static, unless you have a strong reason to do it so. | Should a Log4J logger be declared as transient? | [
"",
"java",
"logging",
"serialization",
"log4j",
""
] |
In Java, say you have a class that wraps an `ArrayList` (or any collection) of objects.
How would you return one of those objects such that the caller will not see any future changes to the object made in the ArrayList?
i.e. you want to return a deep copy of the object, but you don't know if it is cloneable. | Turn that into a spec:
-that objects need to implement an interface in order to be allowed into the collection
Something like `ArrayList<ICloneable>()`
Then you can be assured that you always do a deep copy - the interface should have a method that is guaranteed to return a deep copy.
I think that's the best you ca... | One option is to use serialization. Here's a blog post explaining it:
<http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html> | Java return copy to hide future changes | [
"",
"java",
"deep-copy",
"cloning",
""
] |
In my SWT Java app I often want to return information from inside a Display.syncExec() call. The best way I've found so far to do this is:
```
final ArrayList<Integer> result = new ArrayList<Integer>();
GUI.display().syncExec(new Runnable(){ public void run() {
MessageBox mb = /* ... */;
/* set up messagebox */... | [`ArrayList` is not thread-safe](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html). You can obtain a thread-safe `List` with [`Collections.synchronizedList`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29). However, it is much simpler to use an ... | I just tackled this problem and my first try was similar - array or list of desired type items. But after a while I made up something like this:
```
abstract class MyRunnable<T> implements Runnable{
T result;
}
MyRunnable<Integer> runBlock = new MyRunnable<Integer>(){
MessageBox mb = /* ... */;
/* set up me... | What's the best way to return variables from a syncExec? | [
"",
"java",
"multithreading",
"swt",
""
] |
How do I end a Tkinter program? Let's say I have this code:
```
from Tkinter import *
def quit():
# code to exit
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
```
How should I define the `quit` function to exit my application? | **You should use `destroy()` to close a Tkinter window.**
```
from Tkinter import *
#use tkinter instead of Tkinter (small, not capital T) if it doesn't work
#as it was changed to tkinter in newer Python versions
root = Tk()
Button(root, text="Quit", command=root.destroy).pack() #button to close the window
root.main... | ```
def quit()
root.quit()
```
or
```
def quit()
root.destroy()
``` | How do I close a tkinter window? | [
"",
"python",
"tkinter",
""
] |
If I was to create a ipfw divert rule to forward all FTP traffic to a specific socket, is it possible to use Java to connect to the socekt and read the packet information? If so, how would i go about reading/writing to the scoket? | not sure what you mean. If you're using a divert rule, then all you have to do is listen on that ip:port combination in your java app and you're all set. If you want to read the actual destination endpoint information, you'll need to use JNI for that. | Yes, it's like a normal socket, you can read/write from/to it, but on Mac OS X, if you do want to modify the packet and insert it back, you need to recalculate the tcp check sum first.
<http://blog.loudhush.ro/2006/08/using-divert-sockets-on-mac-os-x.html>
This is a good post that introduce the basic usage of the div... | Read divert sockets in java? | [
"",
"java",
"ftp",
"tcp",
"ipfw",
""
] |
I come from the Microsoft world (and I come in peace). I want to rapidly prototype a web app and if it works out, take it live - and I don't want to use ASP.Net.
I am not sure which web application toolkit to use though. Should I use GWT, DOJO...other recommendations? I am open to any server-side language but am looki... | If you're open to doing Java, GWT is the way to go. It allows you to have a relatively uniform codebase across client-server, and to only use one language on both.
There are some limitations to doing very off-the-beaten-path AJAXy things (which GWT makes difficult, but not impossible), but it doesn't sound like that's... | If you want to write the front and back end in JAVA, and want to do complex ajax type thing, then GWT is a great way to go.
The easiest way to think about it is that building a GWT app is kind of like building a JAVA swing application that hooks into a server. Just like a swing app that uses a server you can make it f... | GWT or DOJO or something else? | [
"",
"javascript",
"web-applications",
"gwt",
"frameworks",
"dojo",
""
] |
When refactoring away some `#defines` I came across declarations similar to the following in a C++ header file:
```
static const unsigned int VAL = 42;
const unsigned int ANOTHER_VAL = 37;
```
The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible du... | The `static` means that there will be one copy of `VAL` created for each source file it is included in. But it also means that multiple inclusions will not result in multiple definitions of `VAL` that will collide at link time. In C, without the `static` you would need to ensure that only one source file defined `VAL` ... | The `static` and `extern` tags on file-scoped variables determine whether they are accessible in other translation units (i.e. other `.c` or `.cpp` files).
* `static` gives the variable internal linkage, hiding it from other translation units. However, variables with internal linkage can be defined in multiple transla... | Variable declarations in header files - static or not? | [
"",
"c++",
"c",
"static",
""
] |
My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:
1. I put a `DropDownList` of the 4-digit year on the page.
2. I validate the expiration date in a `DateTime` field to be sure that the expiration date being passed to the CC processor ... | If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:
```
DateTime expirationDate = new DateTime(2008, 1, 31); // random date
string lastTwoDigitsOfYear = expirationDate.ToString("yy");
```
Edit: Be careful with your dates though if you... | **1st solution** (fastest) :
```
yourDateTime.Year % 100
```
**2nd solution** (more elegant in my opinion) :
```
yourDateTime.ToString("yy")
``` | Converting a year from 4 digit to 2 digit and back again in C# | [
"",
"c#",
"datetime",
"2-digit-year",
""
] |
I was surprised to find today that I couldn't track down any simple way to write the contents of an `InputStream` to an `OutputStream` in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).
So, given an `InputS... | # Java 9
Since Java 9, `InputStream` provides a method called `transferTo` with the following signature:
```
public long transferTo(OutputStream out) throws IOException
```
As the [documentation](https://docs.oracle.com/javase/9/docs/api/java/io/InputStream.html#transferTo-java.io.OutputStream-) states, `transferTo`... | As WMR mentioned, `org.apache.commons.io.IOUtils` from Apache has a method called [`copy(InputStream,OutputStream)`](http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/IOUtils.html#copy(java.io.InputStream,%20java.io.OutputStream)) which does exactly what you're looking for.
So, you hav... | Easy way to write contents of a Java InputStream to an OutputStream | [
"",
"java",
"io",
"stream",
""
] |
I was going to ask what the best way to do this is, but then decided I should ask whether or not it is even necessary. I have never seen it done in `JSP` development, but it appears to be common practice in `PHP`. What is the reasoning behind this, and if I do not protect against this, what else should I be taking into... | The reason this is more common in PHP than other similar languages has to do with PHP's history. Early versions of PHP had the "register\_globals" setting on as a default (in fact, it may not have even been a setting in really early versions). Register\_globals tells PHP to define global variables according to the quer... | If you include everything from outside web root then it's not an issue as nothing **can be** loaded directly. | Is "do not load this page directly" really necessary in PHP? | [
"",
"php",
"methodology",
""
] |
I'm trying to figure out what a Java applet's class file is doing under the hood. Opening it up with Notepad or Textpad just shows a bunch of gobbledy-gook.
Is there any way to wrangle it back into a somewhat-readable format so I can try to figure out what it's doing?
* Environment == Windows w/ VS 2008 installed. | [jd-gui](http://jd.benow.ca/) is the best decompiler at the moment. it can handle newer features in Java, as compared to the getting-dusty JAD. | If you don't mind reading bytecode, javap should work fine. It's part of the standard JDK installation.
```
Usage: javap <options> <classes>...
where options include:
-c Disassemble the code
-classpath <pathlist> Specify where to find user class files
-extdirs <dirs> Over... | How can I open Java .class files in a human-readable way? | [
"",
"java",
"windows",
"class",
"applet",
""
] |
The default 64 MB max heap memory can be small for a large Java application. Are there any applet parameter to increment this for a signed applet?
For a Java program this is a simple command line parameter but how this work for an applet in the browser. | The [new plugin architecture in JDK6u10](http://www.oracle.com/technetwork/java/javase/plugin2-142482.html#COMMAND_LINE_ARGS) supports this. Prior to that, the only way to do it was in the Java control panel. | Use the JavaConsole -> Java -> Java Applet Runtime settings to define the initial and maximum memory allocation (using -Xms128 -Xmx512 or similar).
I understand that newer versions of Java (6?) allow the developer some influence over these settings but I haven't been there yet... | How can I start an Java applet with more memory? | [
"",
"java",
"memory",
"applet",
"next-generation-plugin",
""
] |
In C++, when is it best to use the stack? When is it best to use the heap? | Use the stack when your variable will not be used after the current function returns. Use the heap when the data in the variable is needed beyond the lifetime of the current function. | As a rule of thumb, avoid creating huge objects on the stack.
* Creating an object on the stack frees you from the burden of remembering to cleanup(read delete) the object. But creating too many objects on the stack will increase the chances of stack overflow.
* If you use heap for the object, you get the as much memo... | When is it best to use the stack instead of the heap and vice versa? | [
"",
"c++",
""
] |
A while ago, I came across some code that marked a data member of a class with the `mutable` keyword. As far as I can see it simply allows you to modify a member in a `const`-qualified member method:
```
class Foo
{
private:
mutable bool done_;
public:
void doSomething() const { ...; done_ = true; } ... | It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.
Since c++11 `m... | The `mutable` keyword is a way to pierce the `const` veil you drape over your objects. If you have a const reference or pointer to an object, you cannot modify that object in any way **except** when and how it is marked `mutable`.
With your `const` reference or pointer you are constrained to:
* only read access for a... | Does the 'mutable' keyword have any purpose other than allowing a data member to be modified by a const member function? | [
"",
"c++",
"class",
"keyword",
"mutable",
"datamember",
""
] |
I'm wanting to get the full value of a char[] variable in the VC6 watch window, but it only shows a truncated version. I can copy the value from a debug memory window, but that contains mixed lines of hex and string values. Surely there is a better way?? | For large strings, you're pretty much stuck with the memory window - the tooltip would truncate eventually.
Fortunately, the memory window is easy to get data from - I tend to show it in 8-byte chunks so its easy to manage, find your string data and cut&paste the lot into a blank window, then use alt+drag to select co... | Push come to shove you can put in the watch
given
```
char bigArray[1000];
```
watch:
```
&bigArray[0]
&bigArray[100]
&bigArray[200]
...
```
or change the index for where in the string you want to look...
Its clunky, but its worked for me in the past. | How can I get full string value of variable in VC6 watch window? | [
"",
"c++",
"debugging",
"visual-c++-6",
""
] |
Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the r... | The answer is you do neither. Instead you want to do something suggested by Item 24 of [Effective STL](https://rads.stackoverflow.com/amzn/click/com/0201749629) by [Scott Meyers](http://www.aristeia.com/):
```
typedef map<int, int> MapType; // Your map type may vary, just change the typedef
MapType mymap;
// Add e... | The answer to this question also depends on how expensive it is to create the value type you're storing in the map:
```
typedef std::map <int, int> MapOfInts;
typedef std::pair <MapOfInts::iterator, bool> IResult;
void foo (MapOfInts & m, int k, int v) {
IResult ir = m.insert (std::make_pair (k, v));
if (ir.secon... | std::map insert or std::map find? | [
"",
"c++",
"optimization",
"stl",
"stdmap",
""
] |
I really want to get the google Calendar Api up an running. I found a [great article](http://www.ibm.com/developerworks/library/x-googleclndr/) about how to get started. I downloaded the Zend GData classes. I have php 5 running on my dev box and all the exetensions should be loading.
I cant get openssl running and rec... | I think this use of SSL is part of the Zend GData library so I assume it is correct. I think not having OpenSSL correctly installed is my main issue. | First it would be helpful if you mentioned your OS, I'll assume windows.
Check the output of
```
<?php echo phpinfo();?>
```
If the OpenSSL library is enabled "Registered Stream Socket Transports" will mention ssl
Your php.ini should have
```
[PHP_OPENSSL]
extension=php_openssl.dll
```
If its not there, or you ad... | Easy expanation of setting up Openssl on Windows | [
"",
"php",
"openssl",
"gdata-api",
"google-calendar-api",
""
] |
Suppose I have some XAML like this:
```
<Window.Resources>
<v:MyClass x:Key="whatever" Text="foo\nbar" />
</Window.Resources>
```
Obviously I want a newline character in the MyClass.Text property, but the XAML parser constructs the object with the literal string "foo\nbar".
Is there (a) a way to convince the parse... | You can use XML character escaping
```
<TextBlock Text="Hello World!"/>
``` | Off the top of my head, try;
1. A custom binding expression perhaps?
> `<v:MyClass x:Key="whatever" Text="{MyBinder foo\nbar}"/>`
2. Use a string static resource?
3. Make Text the default property of your control and;
> ```
> <v:MyClass x:Key="whatever">
> foo
> bar
> </v:MyClass>
> ``` | WPF and string formatting | [
"",
"c#",
"wpf",
"xaml",
"escaping",
""
] |
Is it possible to get a thread dump of a Java Web Start application? And if so, how?
It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically?
In the Java Web Start Console I can get ... | In the console, press V rather than T:
```
t: dump thread list
v: dump thread stack
```
This works under JDK6. Don't know about others.
Alternative, under JDK5 (and possibly earlier) you can send a full stack trace of all threads to standard out:
*Under Windows:* type ctrl-break in the Java console.
*Under Uni... | Try
```
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
```
Then you can iterate over the collection to show the top x stack elements you're interested in. | How do I create a thread dump of a Java Web Start application | [
"",
"java",
"multithreading",
"debugging",
"java-web-start",
"thread-dump",
""
] |
I noticed in another post, someone had done something like:
```
double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));
```
Why did they use the convert function, rather than:
```
double d = 3.1415;
int i = (int)d;
```
which has an implicit floor and convert.
Also, more concerning, I noticed in some production ... | Casting to int is implicit truncation, not implicit flooring:
```
double d = -3.14;
int i = (int)d;
// i == -3
```
I choose Math.Floor or Math.Round to make my intentions more explicit. | Rounding is also handled differently:
x=-2.5 (int)x=-2 Convert.ToInt32(x)=-2
x=-1.5 (int)x=-1 Convert.ToInt32(x)=-2
x=-0.5 (int)x= 0 Convert.ToInt32(x)= 0
x= 0.5 (int)x= 0 Convert.ToInt32(x)= 0
x= 1.5 (int)x= 1 Convert.ToInt32(x)= 2
x= 2.5 (int)x= 2 Convert.ToInt32(x)= 2
Notice the x=-1.5 and x=1.5 cases. ... | System.Convert.ToInt vs (int) | [
"",
"c#",
"types",
""
] |
I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating `/tmp/hsperfdata_username` directories, which I would like to prevent. Is there any way to stop java from creating these files? | Try JVM option **-XX:-UsePerfData**
[more info](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html)
The following might be helpful that is from link <https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html>
```
-XX:+UsePerfData
Enables the perfdata feature. This option is ... | Use the JVM option **`-XX:-UsePerfData`**.
This will not have a negative effect on performance, as some other answers say.
By default jvmstat instrumentation is turned on in the HotSpot JVM. The JVM option `-XX:-UsePerfData` turns it off. If anything, I would speculate, turning off the instrumentation would improve p... | How can I prevent Java from creating hsperfdata files? | [
"",
"java",
"performance",
"report",
""
] |
I have lots of unrelated named things that I'd like to do quick searches against. An "aardvark" is always an "aardvark" everywhere, so hashing the string and reusing the integer would work well to speed up comparisons. The entire set of names is unknown (and changes over time). What is a fast string hashing algorithm t... | One of the [FNV variants](http://isthe.com/chongo/tech/comp/fnv/) should meet your requirements. They're fast, and produce fairly evenly distributed outputs. | [Murmur Hash](http://murmurhash.googlepages.com/) is pretty nice. | Fast String Hashing Algorithm with low collision rates with 32 bit integer | [
"",
"c++",
"algorithm",
"string",
"hash",
""
] |
I`d like to be able to read the content of office documents (for a custom crawler).
The office version that need to be readable are from 2000 to 2007. I mainly want to be crawling words, excel and powerpoint documents.
I don`t want to retrieve the formatting, only the text in it.
The crawler is based on lucene.NET i... | Here's a [nice little post on c-charpcorner](http://www.c-sharpcorner.com/UploadFile/Globalking/fileAccessingusingcsharp02242006050207AM/fileAccessingusingcsharp.aspx) by Krishnan LN that gives basic code to grab the text from a Word document using the Word Primary Interop assemblies.
Basically, you get the "WholeStor... | If you're already using Lucene.NET you might just want to take advantage of the various IFilters already available for doing this. Take a look at the open source [SeekAFile](http://sourceforge.net/projects/seekafile/"SeekAFile") project. It will show you how to use an IFilter to open and extract this information from a... | Parsing Office Documents | [
"",
"c#",
"asp.net",
"ms-office",
""
] |
Is it possible to use both JScript and VBScript in the same HTA? Can I call VBScript functions from JScript and vice-versa? Are there any "gotchas," like the JScript running first and the VBScript running second (classic ASP pages have this issue). | Yeah, just separate them into different script tags:
```
<script language="javascript">
// javascript code
</script>
<script language="vbscript">
' vbscript code
</script>
```
Edit: And, yeah, you can cross call between Javascript and VBScript with no extra work.
Edit: This is also true of ANY Windows Scripti... | Also you can give references between them. For example:
at the background some function on vbscript handle with database and FSO issues, and let javascript create user interfaces and dialogs etc. with DOM in frontline.
Whenever you need you can call both functions from each script sides.
In js you can call vbs function... | Can I Mix VBScript and JScript in a Single HTA? | [
"",
"vbscript",
"javascript",
"hta",
""
] |
I'd like to add some functionality to a site that would allow users to record video using their webcam and easily store it online. I don't even know if this is possible right now, but I think flash has access to local webcams running through the browser.
Do you have any suggestions or resources to get me started on th... | This is possible with [Adobe's Flash Media Server](http://www.adobe.com/products/flashmediaserver/). [Red5](http://osflash.org/red5) is an open source alternative. The protocol they use for this is [RTMP](http://en.wikipedia.org/wiki/Real_Time_Messaging_Protocol). | On the server side, you have three alternatives:
1. [Adobe's Flash Media Server](http://www.adobe.com/products/flashmediaserver/)
2. [Red5](http://osflash.org/red5), an open source version
3. [Wowza Media Server Pro](http://www.wowzamedia.com/products.html), a commercial alternative
You can either run any of these on... | How would I allow a user to stream video to a web application for storage? | [
"",
"java",
"flash",
"applet",
"web-applications",
""
] |
I have an asp.net url path which is being generated in a web form, and is coming out something like "/foo/bar/../bar/path.aspx", and is coming out in the generated html like this too. It should be shortened to "/foo/bar/path.aspx".
Path.Combine didn't fix it. Is there a function to clean this path up? | You could create a helper class which wrapped the UriBuilder class in System.Net
```
public static class UriHelper
{
public static string NormalizeRelativePath(string path)
{
UriBuilder _builder = new UriBuilder("http://localhost");
builder.Path = path;
return builder.Uri.Absolut... | Whatever you do, don't use a static UriBuilder. This introduces all sorts of potential race conditions that you might not detect until you are under heavy load.
If two different threads called UriHelper.NormalizeRelativePath at the same time, the return value for one could be passed back to the other caller arbitraril... | Asp.net path compaction | [
"",
"c#",
"asp.net",
"path",
""
] |
I'm working on a .NET 3.5 website, with three projects under one solution. I'm using jQuery in this project. I'd like to use the Visual Studio JavaScript debugger to step through my JavaScript code. If I set a breakpoint in any of the .js files I get a warning that says:
> The breakpoint will not currently be hit. No ... | I was experiencing the same behavior in Visual Studio 2008, and after spending several minutes trying to get the symbols to load I ended up using a workaround - adding a line with the "debugger;" command in my JavaScript file.
After adding `debugger;` when you then reload the script in Internet Explorer it'll let you ... | Make sure you turn on [script debugging](http://msdn.microsoft.com/en-us/library/z959x58c.aspx) in your internet options. And if you think it's on, double check it. | "No symbols loaded for the current document" while debugging JavaScript in Visual Studio | [
"",
"javascript",
"asp.net",
"visual-studio",
"debugging",
""
] |
We are using PowerDesigner at work for database modelling. But there is a hell of a price tag on that piece of software. And frankly, all I use is physical diagrams for MS SQL, which is about 1% of what PD knows.
Are there any good alternatives? I know about Visio and MS SQL Diagrams, but looking for other options. | I just use SQL Server using the diagrams folder. The designer is pretty simple to use, and can be used to generate tables fairly quickly. Considering it's free with the software, I don't see the issue. | [Power\*Architect](http://www.sqlpower.ca/page/architect) is the way to go. It's free, open source, and does a really great job helping you build your ERDs. Plus, it works on Windows, Linux, and OSX. | Free/cheap PowerDesigner alternative? | [
"",
"sql",
"sql-server",
"database",
"modeling",
""
] |
How do I create a resource that I can reference and use in various parts of my program easily?
My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time. | Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.
**How to create a resource:**
In my case, I want to create an icon. It's a similar p... | The above didn't actually work for me as I had expected with Visual Studio 2010. It wouldn't let me access Properties.Resources, said it was inaccessible due to permission issues. I ultimately had to change the Persistence settings in the properties of the resource and then I found how to access it via the Resources.De... | How to create and use resources in .NET | [
"",
"c#",
"visual-studio",
"resources",
"icons",
""
] |
I have a list of objects I wish to sort based on a field `attr` of type string. I tried using `-`
```
list.sort(function (a, b) {
return a.attr - b.attr
})
```
but found that `-` doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string? | Use [`String.prototype.localeCompare`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/localeCompare) as per your example:
```
list.sort(function (a, b) {
return ('' + a.attr).localeCompare(b.attr);
})
```
We force a.attr to be a string to avoid exceptions. `localeCompare` has ... | ## An updated answer (October 2014)
I was really annoyed about this string natural sorting order so I took quite some time to investigate this issue.
### Long story short
`localeCompare()` character support is badass; just use it.
As [pointed out by Shog9](https://stackoverflow.com/questions/51165/how-to-sort-string... | How to sort strings in JavaScript | [
"",
"javascript",
"string",
""
] |
I have:
```
class MyClass extends MyClass2 implements Serializable {
//...
}
```
In MyClass2 is a property that is not serializable. How can I serialize (and de-serialize) this object?
Correction: MyClass2 is, of course, not an interface but a class. | As someone else noted, chapter 11 of Josh Bloch's [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683) is an indispensible resource on Java Serialization.
A couple points from that chapter pertinent to your question:
* assuming you want to serialize the state of the non-serializable field in MyC... | MyClass2 is just an interface so techinicaly it has no properties, only methods. That being said if you have instance variables that are themselves not serializeable the only way I know of to get around it is to declare those fields transient.
ex:
```
private transient Foo foo;
```
When you declare a field transient... | Java Serialization with non serializable parts | [
"",
"java",
"serialization",
""
] |
I came across this recently, up until now I have been happily overriding the equality operator (**==**) and/or **Equals** method in order to see if two references types actually contained the same **data** (i.e. two different instances that look the same).
I have been using this even more since I have been getting mor... | It looks like you're coding in C#, which has a method called Equals that your class should implement, should you want to compare two objects using some other metric than "are these two pointers (because object handles are just that, pointers) to the same memory address?".
I grabbed some sample code from [here](http://... | Implementing equality in .NET correctly, efficiently and *without code duplication* is hard. Specifically, for reference types with value semantics (i.e. [immutable types that treat equvialence as equality](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-... | What is "Best Practice" For Comparing Two Instances of a Reference Type? | [
"",
"c#",
".net",
"comparison",
"operator-overloading",
"equality",
""
] |
There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a `java.util.HashMap` in this way?
(Currently, I'm happily using a `java.util.concurrent.ConcurrentHashMap`, and have n... | Your idiom is safe **if and only if** the reference to the `HashMap` is *safely published*. Rather than anything relating the internals of `HashMap` itself, *safe publication* deals with how the constructing thread makes the reference to the map visible to other threads.
Basically, the only possible race here is betwe... | Jeremy Manson, the god when it comes to the Java Memory Model, has a three part blog on this topic - because in essence you are asking the question "Is it safe to access an immutable HashMap" - the answer to that is yes. But you must answer the predicate to that question which is - "Is my HashMap immutable". The answer... | Is it safe to get values from a java.util.HashMap from multiple threads (no modification)? | [
"",
"java",
"multithreading",
"concurrency",
"hashmap",
""
] |
I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works grea... | Let me guess: the help "icon" is actually a link with a `javascript:` url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved.
```
<!-- clicking this link will do nothing. No onbeforeunload handler triggered.
Noth... | **EDIT:** My "workaround" below is complete overkill, based on my lack of understanding. Go with Shog9's answer above.
OK so while I was writing the question, I came up with a workaround which will work for now.
I put a global JavaScript variable in act as a boolean on whether or not the icon is being hovered over. T... | Can I override onbeforeunload for a particular element? | [
"",
"javascript",
"events",
""
] |
I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships.
```
public class Person
{
public Pe... | The fact that it is adding two records to the table looks like you are missing an [inverse attribute](http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#example-many-to-many-mapping-file). Since both the person and the group are being changed, NHibernate is persisting the relation twice (once for each ob... | @Santiago I think you're right.
The answer might just be that you need to remove one of your ManyToMany declarations, looking more at Fluent it looks like it might be smart enough to just do it for you. | Fluent NHibernate Many-to-Many | [
"",
"c#",
"nhibernate",
"fluent-nhibernate",
"fluent",
""
] |
Assume a table structure of `MyTable(KEY, datafield1, datafield2...)`.
Often I want to either update an existing record, or insert a new record if it doesn't exist.
Essentially:
```
IF (key exists)
run update command
ELSE
run insert command
```
What's the best performing way to write this? | don't forget about transactions. Performance is good, but simple (IF EXISTS..) approach is very dangerous.
When multiple threads will try to perform Insert-or-update you can easily
get primary key violation.
Solutions provided by @Beau Crawford & @Esteban show general idea but error-prone.
To avoid deadlocks and PK... | See my [detailed answer to a very similar previous question](https://stackoverflow.com/questions/234)
[@Beau Crawford's](https://stackoverflow.com/a/108416/1165522) is a good way in SQL 2005 and below, though if you're granting rep it should go to the [first guy to SO it](https://stackoverflow.com/questions/13540). Th... | Solutions for INSERT OR UPDATE on SQL Server | [
"",
"sql",
"sql-server",
"database",
"insert",
"upsert",
""
] |
I am having difficulty reliably creating / removing event sources during the installation of my .Net Windows Service.
Here is the code from my ProjectInstaller class:
```
// Create Process Installer
ServiceProcessInstaller spi = new ServiceProcessInstaller();
spi.Account = ServiceAccount.LocalSystem;
// Create Servi... | The best recommendation would be to not use the Setup Project in Visual Studio. It has very severe limitations.
I had very good results with [WiX](http://wix.sourceforge.net/) | The `ServiceInstaller` class automatically creates an `EventLogInstaller` and puts it inside its own Installers collection.
Try this code:
```
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
serviceProcessInstaller.Password = null;
serviceProcessInstaller.Username = null;
serviceProce... | What is the most reliable way to create a custom event log and event source during the installation of a .Net Service | [
"",
"c#",
".net",
"windows-services",
"event-log",
"eventlog-source",
""
] |
I have noticed that cURL in PHP returns different data when told to output to a file via `CURLOPT_FILE` as it does when told to send the output to a string via `CURLOPT_RETURNTRANSFER`.
`_RETURNTRANSFER` seems to strip newlines and extra white space as if parsing it for display as standard HTML code. `_FILE` on the ot... | Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.
This works just fine:`$cresult... | In most scripting langage (it's also true in Bash for instance), simple quotes are used to represent things as they are written, whereas double quotes are "analysed" (i don't think it's the appropriate word but i can't find better).
```
$str = 'foo';
echo '$str'; // print “$str” to the screen
echo "$str"; // print “fo... | cURL in PHP returns different data in _FILE and _RETURNTRANSFER | [
"",
"php",
"curl",
""
] |
Using C#, I want to get the total amount of RAM that my computer has.
With the PerformanceCounter I can get the amount of Available ram, by setting:
```
counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
```
But I can't seem to find a way to get the total amount of memory. How would I go about... | The Windows API function [`GlobalMemoryStatusEx`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex) can be called with p/invoke:
```
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public... | Add a reference to `Microsoft.VisualBasic` and a `using Microsoft.VisualBasic.Devices;`.
The `ComputerInfo` class has all the information that you need. | How do you get total amount of RAM the computer has? | [
"",
"c#",
"memory",
"performancecounter",
""
] |
Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod\_A, mod\_B, mod\_C etc. Each has the column section\_id.
Now, I am looking for all entries for a specific section\_id, and I'm hoping there's another way besides "Select \* from mod\_a, mod\_b, ... | If the tables are changing over time, you can inline code gen your solution in an SP (pseudo code - you'll have to fill in):
```
SET @sql = ''
DECLARE CURSOR FOR
SELECT t.[name] AS TABLE_NAME
FROM sys.tables t
WHERE t.[name] LIKE 'SOME_PATTERN_TO_IDENTIFY_THE_TABLES'
```
-- or this
```
DECLARE CURSOR FOR
SELECT t.[... | I have two suggestions.
1. Perhaps you need to consolidate all your tables. If they all contain the same structure, then why not have one "master" module table, that just adds one new column identifying the module ("A", "B", "C", ....)
If your module tables are mostly the same, but you have a few columns that are ... | how do I query multiple SQL tables for a specific key-value pair? | [
"",
"sql",
"lazy-evaluation",
""
] |
Say I have a table called myTable. What is the SQL command to return all of the field names of this table? If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well. | MySQL 3 and 4 (and 5):
```
desc tablename
```
which is an alias for
```
show fields from tablename
```
SQL Server (from 2000) and MySQL 5:
```
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'tablename'
```
Completing the answer: like people below have said, in SQL Server you can also use t... | SQL-92 standard defines INFORMATION\_SCHEMA which conforming rdbms's like MS SQL Server support. The following works for MS SQL Server 2000/2005/2008 and MySql 5 and above
```
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'myTable'
```
MS SQl Server Specific:
```
exec sp_help 'myTable'
```
T... | What is the SQL command to return the field names of a table? | [
"",
"sql",
"mysql",
"sql-server",
"database",
""
] |
I've been using the (Java) [Highlighter for Lucene](http://lucene.apache.org/java/2_4_1/lucene-sandbox/index.html#Term%20Highlighter) (in the Sandbox package) for some time. However, this isn't really very accurate when it comes to matching the correct terms in search results - it works well for simple queries, for exa... | There is a new faster highlighter (needs to be patched in but will be part of release 2.9)
<https://issues.apache.org/jira/browse/LUCENE-1522>
and a [back-reference](https://issues.apache.org/jira/browse/LUCENE-1522?focusedCommentId=12688408&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#acti... | You could look into using Solr. <http://lucene.apache.org/solr>
Solr is a sort of generic search application that uses Lucene and supports highlighting. It's possible that the highlighting in Solr is usable as an API outside of Solr. You could also look at how Solr does it for inspiration. | Is there a fast, accurate Highlighter for Lucene? | [
"",
"java",
"lucene",
""
] |
How do you convert decimal values to their hexadecimal equivalent in JavaScript? | Convert a number to a hexadecimal string with:
```
hexString = yourNumber.toString(16);
```
And reverse the process with:
```
yourNumber = parseInt(hexString, 16);
``` | If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function `toString(16)` will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.
```
function decimalToHexSt... | How to convert decimal to hexadecimal in JavaScript | [
"",
"javascript",
"hex",
"number-formatting",
"radix",
""
] |
Now, before you say it: I **did** Google and my `hbm.xml` file **is** an Embedded Resource.
Here is the code I am calling:
```
ISession session = GetCurrentSession();
var returnObject = session.Get<T>(Id);
```
Here is my mapping file for the class:
```
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xml... | Sounds like you forgot to add a mapping assembly to the session factory configuration..
If you're using app.config...
```
.
.
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="Project.DomainModel"/> <!-- Here -->
... | Something obvious, yet quite useful for someone new to NHibernate.
All XML Mapping files should be treated as *Embedded Resources* rather than the default *Content*. This option is set by editing the Build Action attribute in the file's properties.
XML files are then embedded into the assembly, and parsed at project ... | NHibernate.MappingException: No persister for: XYZ | [
"",
"c#",
".net",
"nhibernate",
""
] |
Someone told me about a C++ style difference in their team. I have my own viewpoint on the subject, but I would be interested by *pros* and *cons* coming from everyone.
So, in case you have a class property you want to expose via two getters, one read/write, and the other, readonly (i.e. there is no set method). There... | Well, for one thing, getAsConst *must* be called when the 'this' pointer is const -- not when you want to receive a const object. So, alongside any other issues, it's subtly misnamed. (You can still call it when 'this' is non-const, but that's neither here nor there.)
Ignoring that, getAsConst earns you nothing, and p... | C++ should be perfectly capable to cope with method A in almost all situations. I always use it, and I never had a problem.
Method B is, in my opinion, a case of violation of OnceAndOnlyOnce. And, now you need to go figure out whether you're dealing with const reference to write the code that compiles first time.
I g... | "get() const" vs. "getAsConst() const" | [
"",
"c++",
"coding-style",
"constants",
""
] |
I'm having an issue with my regex.
I want to capture <% some stuff %> and i need what's inside the <% and the %>
This regex works quite well for that.
```
$matches = preg_split("/<%[\s]*(.*?)[\s]*%>/i",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
```
I also want to catch `&% some stuff %&... | In your case, it's better to use preg\_match with its additional parameter and parenthesis:
```
preg_match("#((?:<|<)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|>))#i",$markup, $out);
print_r($out);
Array
(
[0] => <% your stuff %>
[1] => <%
[2] => your stuff
[3] => %>
)
```
By the way, check this online too... | ```
<?php
$code = 'Here is a <% test %> and <% another test %> for you';
preg_match_all('/(<|<)%\s*(.*?)\s*%(>|>)/', $code, $matches);
print_r($matches[2]);
?>
```
Result:
```
Array
(
[0] => test
[1] => another test
)
``` | How do I match one letter or many in a PHP preg_split style regex | [
"",
"php",
"regex",
""
] |
How solid is Mono for C# development on Linux and OS X? I've been thinking about learning C# on the side, and was wondering if learning using Mono would suffice. | I have been using mono for upwards of 2 years now. Work is windows and .Net, home is mono on GNU/Linux. I have been able to run both GUI and ASP.NET apps with no problems from the same SVN repository. The only changes I had to make were in connection strings. ASP.NET works well under mod\_mono for apache and xsp2. Some... | It should be just fine. It supports C# 3.0 now. I usually try to stick with targeting 2.0 though and it is very stable.
Winforms and ASP.NET have both worked fine for me. The only thing to consider is there is currently no support for WPF. | Learning C# in Mono | [
"",
"c#",
".net",
"mono",
"cross-platform",
""
] |
The pages in question contain a lot of javascript and CSS. How well are these supported by mobile platforms generally?
Is there a browser emulator (or equivalent tool) to assist testing? | [Opera](http://www.opera.com) has an option to view pages as through a mobile device. I've found it useful in the past. | I can tell you that [Apple's Mobile Safari](http://www.apple.com/iphone/features/safari.html) on the iPhone renders Stack Overflow *perfectly*, which I find rather amazing.
This is a site for programmers, not average users, so we accepted a lot of JavaScript dependencies.
I do wish more mobile devices had browsers as... | What are the quickest and easiest ways to ensure existing web pages display well on mobile platforms? | [
"",
"javascript",
"css",
"browser",
"mobile",
""
] |
I have a div with `id="a"` that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of th... | With jQuery, the actual DOM element is at index zero, this should work
```
$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');
``` | A regex splitting on word boundary `\b` isn't the best solution for this:
```
var prefix = "prefix";
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ").trim();
```
or as a jQuery mixin:
```
$.fn.removeClassPrefix = function(prefi... | Remove all classes that begin with a certain string | [
"",
"javascript",
"jquery",
"css",
""
] |
I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the `java.io.Console` class to manage output and, more importantly, user input.
The problem is that `System.console()` returns `null` when an application is run "through" Eclipse. Eclipse run the program on a background proce... | I assume you want to be able to use step-through debugging from Eclipse. You can just run the classes externally by setting the built classes in the bin directories on the JRE classpath.
```
java -cp workspace\p1\bin;workspace\p2\bin foo.Main
```
You can debug using the remote debugger and taking advantage of the cla... | The workaround that I use is to just use System.in/System.out instead of Console when using Eclipse. For example, instead of:
```
String line = System.console().readLine();
```
You can use:
```
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = bufferedReader.readLine... | java.io.Console support in Eclipse IDE | [
"",
"java",
"eclipse",
"console",
"java-io",
""
] |
How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.
I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, et... | UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to [RFC 4122](https://www.ietf.org/rfc/rfc4122.txt), are identifiers designed to provide certain uniqueness guarantees.
While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see [... | *[Edited 2023-03-05 to reflect latest best-practices for producing RFC4122-compliant UUIDs]*
[`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID) is now standard on all modern browsers and JS runtimes. However, because [new browser APIs are restricted to secure contexts](https://... | How do I create a GUID / UUID? | [
"",
"javascript",
"guid",
"uuid",
""
] |
What is the C# version of VB.NET's `InputBox`? | Add a reference to `Microsoft.VisualBasic`, `InputBox` is in the `Microsoft.VisualBasic.Interaction` namespace:
```
using Microsoft.VisualBasic;
string input = Interaction.InputBox("Prompt", "Title", "Default", x_coordinate, y_coordinate);
```
Only the first argument for `prompt` is mandatory | Dynamic creation of a dialog box. You can customize to your taste.
*Note there is no external dependency here except winform*
```
private static DialogResult ShowInputDialog(ref string input)
{
System.Drawing.Size size = new System.Drawing.Size(200, 70);
Form inputBox = new Form();
inputB... | What is the C# version of VB.NET's InputBox? | [
"",
"c#",
"vb.net",
""
] |
I am trying to make a div, that when you click it turns into an input box, and focuses it. I am using prototype to achieve this. This works in both Chrome and Firefox, but not in IE. IE refuses to focus the newly added input field, even if I set a 1 second timeout.
Basically the code works like this:
```
var viewElem... | My guess is that IE hasn't updated the DOM yet when you make the call to focus(). Sometimes browsers will wait until a script has finished executing before updating the DOM.
I would try doing the update, then doing
```
setTimeout("setFocus", 0);
function setFocus()
{
editElement.focus();
}
```
Your other option... | What version IE? What's your DocType set to? is it strict, standards or quirks mode? Any javascript errors appearing (check the status bar bottom left for a little yellow warning sign) ? Enable error announcing for all errors via Tools > Options > Advanced.
Oisin | Adding an input field to the dom and focusing it in IE | [
"",
"javascript",
"internet-explorer",
"focus",
"prototypejs",
""
] |
in short: **is there any way to find the current directory full path of a xul application?**
long explanation:
I would like to open some html files in a xul browser application. The path to the html files should be set programmatically from the xul application. The html files reside outside the folder of my xul appli... | I found a workaround: <http://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO> i cannot exactly open a file using a relative path "../../index.html" but i can get the app directory and work with that.
```
var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties");
var p... | Yes, html files within your extension can be addressed using chrome URIs.
An example from one of my extensions:
```
content.document.location.href = "chrome://{appname}/content/logManager/index.html"
``` | xul: open a local html file relative to "myapp.xul" in xul browser | [
"",
"javascript",
"file-io",
"xul",
""
] |
In Java you can give the number zero as a single parameter for the Socket or DatagramSocket constructor. Java binds that Socket to a free port then. Is it possible to limit the port lookup to a specific range? | Hrm, after reading the docs, I don't think you can. You can either bind to any port, then rebind if it is not acceptable, or repeatedly bind to a port in your range until you succeed. The second method is going to be most "efficient".
I am uneasy about this answer, because it is... inelegant, yet I really can't find a... | Binding the socket to any free port is (usually) a feature of the operating system's socket support; it's not specific to java. Solaris, for example, supports adjusting the ephemeral port range through the *ndd* command. But only root can adjust the range, and it affects the entire system, not just your program.
If th... | How do you specify a port range for Java sockets? | [
"",
"java",
"tcp",
"sockets",
"udp",
""
] |
This code in JS gives me a popup saying "i think null is a number", which I find slightly disturbing. What am I missing?
```
if (isNaN(null)) {
alert("null is not a number");
} else {
alert("i think null is a number");
}
```
I'm using Firefox 3. Is that a browser bug?
Other tests:
```
console.log(null == Na... | I believe the code is trying to ask, "is `x` numeric?" with the specific case here of `x = null`. The function `isNaN()` can be used to answer this question, but semantically it's referring specifically to the value `NaN`. From Wikipedia for [`NaN`](http://en.wikipedia.org/wiki/NaN):
> NaN (**N**ot **a** **N**umber) i... | I just ran into this issue myself.
For me, the best way to use isNaN is like so
`isNaN(parseInt(myInt))`
taking phyzome's example from above,
```
var x = [undefined, NaN, 'blah', 0/0, null, 0, '0', 1, 1/0, -1/0, Number(5)]
x.map( function(n){ return isNaN(parseInt(n))})
[true, true, ... | Why is isNaN(null) == false in JS? | [
"",
"javascript",
""
] |
Here's something I haven't been able to fix, and I've looked **everywhere**. Perhaps someone here will know!
I have a table called dandb\_raw, with three columns in particular: dunsId (PK), name, and searchName. I also have a trigger that acts on this table:
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER... | I think David and Cervo combined have hit on the problem here.
I'm pretty sure part of what was happening was that we were using #newMatches in multiple triggers. When one trigger changed some rows, it would fire another trigger, which would attempt to use the connection scoped #newMatches.
As a result, it would try ... | What is companies\_contactInfo\_updateTerritories? The actual reference mentions procedure "companies\_contactInfo\_updateTerritories" but I do not see it in the code given. Also I do not see where it is being called. Unless it is from your application that is calling the SQL and hence irrelevant....
If you tested eve... | T-SQL triggers firing a "Column name or number of supplied values does not match table definition" error | [
"",
"sql",
"t-sql",
"triggers",
""
] |
Can anyone point me to a tutorial on the best way to open a connection from client to server, read in a binary file and send its contents reliably across the network connection? Even better, is there an open source library that already does this that I could refer to? | You should look into binary serialization and sending it over a TCP socket.
Good explanation on different types of serialization:
<http://www.dotnetspider.com/resources/408-XML-serialization-Binary-serialization.aspx>
Good primer on TCP Client/Server in C#:
<http://www.codeproject.com/KB/IP/tcpclientserver.aspx> | This depends what you mean by network - if you're copying on a local network you can just use the file copy operations inside System.IO. If you're wanting to send to remote servers I do this using web services. I compress byte arrays and send them over and decompress on the remote side. The byte array is super easy to ... | What's the best way to send a file over a network using C#? | [
"",
"c#",
".net",
"ftp",
"tcp",
"data-transfer",
""
] |
For deployment reasons, I am trying to use IJW to wrap a C# assembly in C++ instead of using a COM Callable Wrapper.
I've done it on other projects, but on this one, I am getting an EEFileLoadException. Any help would be appreciated!
Managed C++ wrapper code (this is in a DLL):
```
extern "C" __declspec(dllexport) I... | The problem was where the DLLs were located.
* c:\dlls\managed.dll
* c:\dlls\wrapper.dll
* c:\exe\my.exe
I confirmed this by copying managed.dll into c:\exe and it worked without issue. Apparently, the CLR won't look for managed DLLs in the path of the unmanaged DLL and will only look for it where the executable is. ... | The first issue is to make sure the Debugger type is set to mixed. Then you get useful exceptions. | EEFileLoadException when using C# classes in C++(win32 app) | [
"",
"c#",
"managed-c++",
""
] |
I am trying to fix memory leaks in IE 7. Using Drip for investigations but it is not helping much when most dynamically generated DOM elements do not have unique ids.
Tips? | You should try the [Javascript Memory Leak detector](https://learn.microsoft.com/en-us/archive/blogs/gpde/javascript-memory-leak-detector-v2) developed internally at Microsoft. | Well, Your best bet is to understand what causes them, so you can look critically at your code, identify patterns that may cause a leak, and then avoid or refactor around them.
Here's a couple of links to get you started, both very informative:
* <http://www-128.ibm.com/developerworks/web/library/wa-memleak/>
* <http... | What tools and techniques do you use to fix browser memory leaks? | [
"",
"javascript",
"internet-explorer",
"memory",
""
] |
I have a console application that will be kicked off with a scheduler. If for some reason, part of that file is not able to be built I need a GUI front end so we can run it the next day with specific input.
Is there as way pass parameters to the application entry point to start the console application or the GUI appli... | It sounds like what you want is to either run as a console app or a windows app based on a commandline switch.
If you look at the last message in [this thread](http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/fd89cf64-eab4-4cc5-8f35-74ec848d8a60), Jeffrey Knight posted code to do what you are asking.... | Go to your main method (Program.cs). You'll put your logic there, and determine what to do , and conditionally execute Application.Run() | Passing parameters to start as a console or GUI application? | [
"",
"c#",
""
] |
If a class defined an annotation, is it somehow possible to force its subclass to define the same annotation?
For instance, we have a simple class/subclass pair that share the `@Author @interface.`
What I'd like to do is force each further subclass to define the same `@Author` annotation, preventing a `RuntimeExceptio... | You can do that with JSR 269, at compile time.
See : <http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api>
Edit 2020-09-20: Link is dead, archived version here : <https://web.archive.org/web/20150516080739/http://today.java.net/p... | I am quite sure that this is impossible to do at compile time.
However, this is an obvious task for a "unit"-test. If you have conventions like this that you would like enforced, but which can be difficult or impossible to check with the compiler, "unit"-tests are a simple way to check them.
Another possibility is to... | How do I force a Java subclass to define an Annotation? | [
"",
"java",
"annotations",
"subclass",
""
] |
Had a conversation with a coworker the other day about this.
There's the obvious using a constructor, but what are the other ways there? | There are four different ways to create objects in java:
**A**. Using `new` keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
```
MyObject object = new MyObject();
```
**B**. Using `Class.forName()`
If we know the name of the class & if it has a publ... | There are various ways:
* Through `Class.newInstance`.
* Through `Constructor.newInstance`.
* Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).
* Through `Object.clone` (**does not call a constructor**).
* Through JNI (should call a constructor).
* Through any othe... | What are all the different ways to create an object in Java? | [
"",
"java",
""
] |
We're in an early stage of a new web project. The project will grow and become complex over time. From the beginning we will have unit and integration tests using JUnit and system tests using HtmlUnit. We might also add some static code analysis tools to the build process if they prove to be of value to us.
If you're ... | Hudson (the best). [Hudson Website](http://hudson-ci.org/) | JetBrains TeamCity Pro. <http://www.jetbrains.com/teamcity/index.html>
The Professional Edition does not require any license key. TeamCity starts running automatically with the Professional Edition Server if no license key is entered in the program. A single Professional Edition Server installation grants the rights t... | Which software to use for continuous integration of a Java web project | [
"",
"java",
"continuous-integration",
""
] |
What do wikis/stackoverflow/etc. do when it comes to storing text? Is the text broken at newlines? Is it broken into fixed-length chunks? How do you best store arbitrarily long chunks of text? | nvarchar(max) ftw. because over complicating simple things is bad, mmkay? | I guess if you need to offer the ability to store large chunks of text and you don't mind not being able to look into their content too much when querying, you can use CLobs. | What's the canonical way to store arbitrary (possibly marked up) text in SQL? | [
"",
"sql",
"text",
""
] |
While refactoring code and ridding myself of all those #defines that we're now taught to hate, I came across this beauty used to calculate the number of elements in a structure:
```
#define STRUCTSIZE(s) (sizeof(s) / sizeof(*s))
```
Very useful as it is but can it be converted into an inline function or template?
OK... | As been stated, the code actually work out the number of elements in an array, not struct. I would just write out the sizeof() division explicitly when I want it. If I were to make it a function, I would want to make it clear in its definition that it's expecting an array.
```
template<typename T,int SIZE>
inline size... | [KTC](https://stackoverflow.com/users/12868/ktc)'s solution is clean but it can't be used at compile-time and it is dependent on compiler optimization to prevent code-bloat and function call overhead.
One can calculate array size with a compile-time-only metafunction with zero runtime cost. [BCS](https://stackoverflow... | Can this macro be converted to a function? | [
"",
"c++",
"macros",
"c-preprocessor",
""
] |
Should I catch exceptions for logging purposes?
```
public foo(..)
{
try
{
...
} catch (Exception ex) {
Logger.Error(ex);
throw;
}
}
```
If I have this in place in each of my layers (DataAccess, Business and WebService) it means the exception is logged several times.
Does it make sense to ... | Definitely not. You should find the correct place to **handle** the exception (actually do something, like catch-and-not-rethrow), and then log it. You can and should include the entire stack trace of course, but following your suggestion would litter the code with try-catch blocks. | Unless you are going to change the exception, you should only log at the level where you are going to handle the error and not rethrow it. Otherwise your log just has a bunch of "noise", 3 or more of the same message logged, once at each layer.
My best practice is:
1. Only try/catch in public methods (in general; obv... | Should I catch exceptions only to log them? | [
"",
"c#",
"logging",
"exception",
""
] |
Long story short, I have a substantial Python application that, among other things, does outcalls to "losetup", "mount", etc. on Linux. Essentially consuming system resources that must be released when complete.
If my application crashes, I want to ensure these system resources are properly released.
Does it make sen... | I like top-level exception handlers in general (regardless of language). They're a great place to cleanup resources that may not be immediately related to resources consumed inside the method that throws the exception.
It's also a fantastic place to **log** those exceptions if you have such a framework in place. Top-l... | A destructor (as in a \_\_del\_\_ method) is a bad idea, as these are not guaranteed to be called. The atexit module is a safer approach, although these will still not fire if the Python interpreter crashes (rather than the Python application), or if os.\_exit() is used, or the process is killed aggressively, or the ma... | Does an application-wide exception handler make sense? | [
"",
"python",
"exception",
""
] |
I have a .NET 3.5 (target framework) web application. I have some code that looks like this:
```
public string LogPath { get; private set; }
public string ErrorMsg { get; private set; }
```
It's giving me this compilation error for these lines:
```
"must declare a body because it is not marked abstract or extern."
`... | add to web.config
```
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
<providerOption name="CompilerVersion" value="v3.5" />
... | Your code is valid - it should work fine. Go in to the property pages of your project and make sure that the "Target Framework" is .NET 3.0 or 3.5. | .NET property generating "must declare a body because it is not marked abstract or extern" compilation error | [
"",
"c#",
"properties",
"compilation",
""
] |
After making [some comments](https://stackoverflow.com/questions/75882/what-in-your-mind-is-the-best-php-mvc-framework#89095), I've been inspired to get some feedback on the PHP MVC framework [PRADO](http://pradosoft.com/). I've been using it for over a year now and I've very much enjoyed working with it, however I not... | The first time I looked into PRADO, I spent about 10 days using it and kept saying to myself: "This framework is amazing!". A couple of months later, I started working on a big project where the customer had chosen to use PRADO... And Hell began... As long as we kept using PRADO's base components, everything was perfec... | I've played with PRADO some, but I felt that if I'm going to be forced into post-back-hell i might as well do it on the platform that it was built for in the beginning - .NET, other then that PRADO is relatively "untalked" about in the blogs, etc. I don't know why really though. | Are there many users of PRADO out there? | [
"",
"php",
"model-view-controller",
"frameworks",
"prado",
""
] |
Ran into this problem today, posting in case someone else has the same issue.
```
var execBtn = document.createElement('input');
execBtn.setAttribute("type", "button");
execBtn.setAttribute("id", "execBtn");
execBtn.setAttribute("value", "Execute");
execBtn.setAttribute("onclick", "runCommand();");
```
Turns out to g... | to make this work in both FF and IE you must write both ways:
```
button_element.setAttribute('onclick','doSomething();'); // for FF
button_element.onclick = function() {doSomething();}; // for IE
```
thanks to [this post](http://mcarthurgfx.com/blog/article/assigning-onclick-with-new-element-breaks-in-ie).
... | works great!
using both ways seem to be unnecessary now:
```
execBtn.onclick = function() { runCommand() };
```
apparently works in every current browser.
tested in current Firefox, IE, Safari, Opera, Chrome on Windows; Firefox
and Epiphany on Ubuntu; not tested on Mac or mobile systems.
* Craig: I'd try "document... | Why does an onclick property set with setAttribute fail to work in IE? | [
"",
"javascript",
"internet-explorer",
""
] |
How do you install Boost on MacOS?
Right now I can't find bjam for the Mac. | Download [MacPorts](https://www.macports.org/), and run the following command:
```
sudo port install boost
``` | You can get the latest version of Boost by using [Homebrew](http://brew.sh/).
`brew install boost`. | How do you install Boost on MacOS? | [
"",
"c++",
"macos",
"boost",
""
] |
We'd like a trace in our application logs of these exceptions - by default Java just outputs them to the console. | There is a distinction between uncaught exceptions in the EDT and outside the EDT.
[Another question has a solution for both](https://stackoverflow.com/questions/75218/how-can-i-detect-when-an-exceptions-been-thrown-globally-in-java#75439) but if you want just the EDT portion chewed up...
```
class AWTExceptionHandle... | Since Java 7, you have to do it differently as the `sun.awt.exception.handler` hack does not work anymore.
[Here is the solution](https://stackoverflow.com/a/27858065/2003986) (from [Uncaught AWT Exceptions in Java 7](http://www.javaspecialists.eu/archive/Issue196.html)).
```
// Regular Exception
Thread.setDefaultUnc... | How can I catch AWT thread exceptions in Java? | [
"",
"java",
"swing",
"exception",
"awt",
""
] |
In my C# application I am using the Microsoft Jet OLEDB data provider to read a CSV file. The connection string looks like this:
```
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Data;Extended Properties="text;HDR=Yes;FMT=Delimited
```
I open an ADO.NET OleDbConnection using that connection string and select all th... | There's a schema file you can create that would tell ADO.NET how to interpret the CSV - in effect giving it a structure.
Try this: [http://www.aspdotnetcodes.com/Importing\_CSV\_Database\_Schema.ini.aspx](https://web.archive.org/web/20081009034412/http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx)
... | To expand on Marc's answer, I need to create a text file called Schema.ini and put it in the same directory as the CSV file. As well as column types, this file can specify the file format, date time format, regional settings, and the column names if they're not included in the file.
To make the example I gave in the q... | When reading a CSV file using a DataReader and the OLEDB Jet data provider, how can I control column data types? | [
"",
"c#",
".net",
"csv",
"oledb",
""
] |
Do C#/.NET floating point operations differ in precision between debug mode and release mode? | They can indeed be different. According to the CLR ECMA specification:
> Storage locations for floating-point
> numbers (statics, array elements, and
> fields of classes) are of fixed size.
> The supported storage sizes are
> float32 and float64. Everywhere else
> (on the evaluation stack, as
> arguments, as return ty... | This is an interesting question, so I did a bit of experimentation. I used this code:
```
static void Main (string [] args)
{
float
a = float.MaxValue / 3.0f,
b = a * a;
if (a * a < b)
{
Console.WriteLine ("Less");
}
else
{
Console.WriteLine ("GreaterEqual");
}
}
```
using DevStudio 200... | Float/double precision in debug/release modes | [
"",
"c#",
".net",
"floating-point",
""
] |
On a website if I have a form where the user can input some text and then a page which displays what the user has entered. I know to html encode the values the user has entered to prevent scripting attacks. If the form was sending emails addresses I presume I would do the same but is there any special cases for emails ... | You should definitely HTML encode before assigning posted content to the HTML body of an email. Your code should already be rejecting content such as '<script>' as invalid, not just in the case of an email but in all cases.
There are no other considerations you need to worry about. | While it would still be a good idea to strip `<script>` tags from your document before sending it, I think that the threat is low. I believe that you would be hard pressed to find an email client (still receiving support) that does not strip scripts before rendering an email. | Encoding user input for emails | [
"",
"javascript",
"email",
""
] |
The point of const-correctness is to be able to provide a view of an instance that can't be altered or deleted by the user. The compiler supports this by pointing out when you break constness from within a const function, or try to use a non-const function of a const object. So without copying the const approach, is th... | I've come across this issue a lot of times too and ended up using interfaces.
I think it's important to drop the idea that C# is any form, or even an evolution of C++. They're two different languages that share almost the same syntax.
I usually express 'const correctness' in C# by defining a read-only view of a class... | To get the benefit of const-craziness (or pureness in functional programming terms), you will need to design your classes in a way so they are immutable, just like the String class of c# is.
This approach is way better than just marking an object as readonly, since with immutable classes you can pass data around easil... | "const correctness" in C# | [
"",
"c#",
"theory",
"const-correctness",
""
] |
Is there a way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself?
For example, something along these lines
```
class A
{
public void DoSomething()
{
StaticClass.ExecuteMethod();
}
... | I do not believe you can. Even the StackTrace and StackFrame classes just give you naming information, not access to instances.
I'm not sure exactly why you'd want to do this, but know that even if you could do it it would likely be very slow.
A better solution would be to push the instance to a thread local context ... | Consider making the method an extension method. Define it as:
```
public static StaticExecute(this object instance)
{
// Reference to 'instance'
}
```
It is called like:
```
this.StaticExecute();
```
I can't think of a way to do what you want to do directly, but I can only suggest that if you find something, yo... | Can I get the calling instance from within a method via reflection/diagnostics? | [
"",
"c#",
".net",
"reflection",
""
] |
How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?
```
if (!isObjectLoaded(someVar)) {
someVar= loadObject();
}
``` | If it is an object then you should just be able to check to see if it is [null](http://javascript.about.com/od/reference/g/rnull.htm) or [undefined](http://javascript.about.com/od/reference/g/sundefined.htm) and then load it if it is.
```
if (myObject === null || myObject === undefined) {
myObject = loadObject();
}... | ```
if(typeof(o) != 'object') o = loadObject();
``` | How to check if a variable is loaded in JavaScript? | [
"",
"javascript",
"object",
""
] |
I'm writing a report view of an audit trail, and I need to display this in a .jsp. What's the "best" way to get the data from the database to the screen?
We're using Spring for dependency injection, Data Access Objects, and Hibernate.
I can use hibernate or straight jdbc for this report.
If I load all the records int... | It seems like this is a natural place to use pagination of your Hibernate results -- run the query at the Servlet level, and paginate results in a way similar to how this person describes:
<http://blog.hibernate.org/Bloggers/Everyone/Year/2004/Month/08/Day/14#pagination>
This is the easiest method of implementing Hib... | The [Display Tag Library](http://displaytag.org) is very good at presenting paginated result sets in servlets or portlets. But it normally works with the whole list loaded into memory. So you will have to do a little work to get it to work with paginated result sets by implementing the `org.displaytag.pagination.Pagina... | What is the best way to present data from a very large resultset? | [
"",
"java",
"hibernate",
"web-applications",
"jdbc",
""
] |
I have a History Table in SQL Server that basically tracks an item through a process. The item has some fixed fields that don't change throughout the process, but has a few other fields including status and Id which increment as the steps of the process increase.
Basically I want to retrieve the last step for each ite... | It's kind of hard to make sense of your table design - I think SO ate your delimiters.
The basic way of handling this is to GROUP BY your fixed fields, and select a MAX (or MIN) for some unqiue value (a datetime usually works well). In your case, I *think* that the GROUP BY would be BatchRef and ItemCount, and Id will... | Assuming you have an identity column in the table...
```
select
top 1 <fields>
from
HistoryTable
where
BatchRef = @BatchRef
order by
<IdentityColumn> DESC
``` | Get last item in a table - SQL | [
"",
"sql",
"sql-server",
"database",
"t-sql",
""
] |
I'm using the `cacheCounter` in `CakePHP`, which increments a counter for related fields.
Example, I have a Person table a Source table. Person.source\_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows.
`cacheCounter` is working great when I change the valu... | To monitor changes in a field, you can use this logic in your model with no changes elsewhere required:
```
function beforeSave() {
$this->recursive = -1;
$this->old = $this->find(array($this->primaryKey => $this->id));
if ($this->old){
$changed_fields = array();
foreach ($this->data[$this-... | With reference to ***Alexander Morland*** Answer.
How about this instead of looping through it in before filter.
```
$result = array_diff_assoc($this->old[$this->alias],$this->data[$this->alias]);
```
You will get key as well as value also. | In CakePHP, how can you determine if a field was changed in an edit action? | [
"",
"php",
"cakephp",
""
] |
I have two `DateTime` objects: `StartDate` and `EndDate`. I want to make sure `StartDate` is before `EndDate`. How is this done in C#? | ```
if (StartDate < EndDate)
// code
```
if you just want the dates, and not the time
```
if (StartDate.Date < EndDate.Date)
// code
``` | ```
if(StartDate < EndDate)
{}
```
DateTime supports normal comparision operators. | How to check if one DateTime is greater than the other in C# | [
"",
"c#",
""
] |
I'm currently using ImageMagick to determine the size of images uploaded to the website. By calling ImageMagick's "identify" on the command line it takes about 0.42 seconds to determine a 1MB JPEG's dimensions along with the fact that it's a JPEG. I find that a bit slow.
Using the Imagick PHP library is even slower as... | Sorry I can't add this as a comment to a previous answer but I don't have the rep. Doing some quick and dirty testing I also found that exec("identify -ping... is about 20 times faster than without the -ping. But getimagesize() appears to be about 200 times faster still.
So I would say getimagesize() is the faster met... | If you're using PHP with GD support, you can try [getimagesize()](http://www.php.net/manual/en/function.getimagesize.php). | Fastest way to determine image resolution and file type in PHP or Unix command line? | [
"",
"php",
"image",
"png",
"imagemagick",
"jpeg",
""
] |
Given this class
```
class Foo
{
// Want to find _bar with reflection
[SomeAttribute]
private string _bar;
public string BigBar
{
get { return this._bar; }
}
}
```
I want to find the private item \_bar that I will mark with a attribute. Is that possible?
I have done this with propert... | Use `BindingFlags.NonPublic` and `BindingFlags.Instance` flags
```
FieldInfo[] fields = myType.GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance);
``` | You can do it just like with a property:
```
FieldInfo fi = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance);
if (fi.GetCustomAttribute(typeof(SomeAttribute)) != null)
...
``` | Find a private field with Reflection? | [
"",
"c#",
".net",
"reflection",
".net-attributes",
""
] |
I want to perform cascade delete for some tables in my database, but I'm interested in what happens in case there's a failure when deleting something. Will everything rollback? | In general¹, yes, cascade deletes are done in the same transaction (or subtransaction) as your original delete. You should read the documentation of your SQL server, though.
¹ The exception is if you're using a database that doesn't support transactions, like MySQL with MyISAM tables. | Cascade deletes are indeed atomic, they would be of little use without that property. It is in the documentation. | Does CASCADE Delete execute as transaction? | [
"",
"sql",
"cascade",
""
] |
The default Python install on OS X 10.5 is 2.5.1 with a FAT 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past, I have run Apache and MySQL to match this install in 32 bit mode (even stripping out the 64 bit stuff from Apache to make it work).
I want to upgrade Python to 64 bit.... | Personally, I wouldn't worry about it until you see a problem. Messing with the default python install on a \*Nix system can cause more trouble than it's worth. I can say from personal experience that you never truly understand what python has done for the nix world until you have a problem with it.
You can also add a... | Hyposaurus,
It is possible to have multiple versions of Python installed simultaneously. Installing two versions in parallel solves your problem and helps avoid the problems laid out by Jason Baker above.
The easiest way, and the way I recommend, is to use [MacPorts](http://www.macports.org/), which will install all ... | Install Python to match directory layout in OS X 10.5 | [
"",
"python",
"macos",
"64-bit",
""
] |
This is my first real question of need for any of those Gridview experts out there in the .NET world.
I an creating a Gridview from codebehind and I am holding a bunch of numerical data in the columns. Although, I do add the comma in the number fields from codebehind. When I load it to the Gridview, I have the sorting... | Instead, I just resorted to the JQUERY Table Sorter.
can be found here: [tablesorter](http://tablesorter.com/docs/) | If you do end up implementing your own comparer and sorting them as strings, the algorithm for treating numbers 'properly' is called Natural Sorting. Jeff wrote a pretty good entry on it here:
[Sorting for Humans : Natural Sort Order](https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/)
You can find... | .Net Gridview alpha sorting, it needs to be numerically sorted | [
"",
"c#",
".net",
"gridview",
""
] |
First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one.
If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I hav... | You probably want Ruby, because it's the native language for Metasploit, which is the de facto standard open source penetration testing framework. Ruby's going to give you:
* [Metasploit's](http://www.metasploit.com/) framework, opcode and shellcode databases
* Metasploit's [Ruby lorcon](http://rubyforge.org/projects/... | [Disclaimer: I am primarily a Perl programmer, which may be colouring my judgement. However, I am not a particularly tribal one, and I think on this particular question my argument is reasonably objective.]
Perl was designed to blend seamlessly into the Unix landscape, and that is why it feels so alien to people with ... | Which of these scripting languages is more appropriate for pen-testing? | [
"",
"python",
"ruby",
"perl",
"security",
"penetration-testing",
""
] |
I once wrote this line in a Java class. This compiled fine in Eclipse but not on the command line.
This is on
* Eclipse 3.3
* JDK 1.5
* Windows XP Professional
Any clues?
Error given on the command line is:
```
Icons.java:16: code too large
public static final byte[] compileIcon = { 71, 73, 70, 56, 57,... | Taking from [this forum on Sun's support site](http://forums.sun.com/thread.jspa?threadID=747860&messageID=4278559), no method can be more than 64 KB long:
When you have code (pseudo) like the following...
```
class MyClass
{
private String[] s = { "a", "b", "c"}
public MyClass()
{
}
```
The compiler ends u... | What you have seems to compile.
If possible, I would suggest trying to embed the resource in the Jar and using
ClassLoader.getResourceAsStream(). | Code compiling in eclipse but not on command line | [
"",
"java",
"eclipse",
"debugging",
"eclipse-3.3",
""
] |
The \_\_doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??
It's a simple asp:LinkButton with an OnClick event
```
<asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you wa... | Check your User Agent string. This same thing happened to me one time and I realized it was because I was testing out some pages as "googlebot". The JavaScript that is generated depends on knowing what the user agent is.
From <http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&for... | I had this same problem (\_\_doPostBack not working) in Firefox- caused a solid hour of wasted time. The problem turned out to be the HTML. If you use HTML like this:
```
<input type="button" id="yourButton" onclick="doSomethingThenPostBack();" value="Post" />
```
Where "doSomethingThenPostBack" is just a JavaScript ... | __doPostBack is not working in firefox | [
"",
"c#",
"asp.net",
""
] |
I use Emacs primarily for coding Python but sometimes I use IDLE. Is there a way to change the key bindings easily in IDLE to match Emacs? | IDLE provides Emacs keybindings without having to install other software.
1. Open up the menu item Options -> Configure IDLE...
2. Go to Keys tab
3. In the drop down menu on the right
side of the dialog change the select
to "IDLE Classic Unix"
It's not the true emacs key bindings but you get the basics like mov... | There's a program for Windows called `XKeymacs` that allows you to specify emacs keybindings for different programs. It should work with IDLE.
<http://www.cam.hi-ho.ne.jp/oishi/indexen.html>
-Mark | How can I get Emacs' key bindings in Python's IDLE? | [
"",
"python",
"emacs",
"ide",
"keyboard",
""
] |
I want to keep logs of some things that people do in my app, in some cases so that it can be undone if needed.
Is it best to store such logs in a file or a database? I'm completely at a loss as to what the pros and cons are except that it's another table to setup.
Is there a third (or fourth etc) option that I'm not ... | You will almost certainly want to use a database for flexible, record based access and to take advantage of the database's ability to handle concurrent data access. If you need to track information that may need to be undone, having it in a structured format is a benefit, as is having the ability to update a row indica... | There is at least one definite reason to go for storing in the database. You can use INSERT DELAYED in MySQL (or similar constructs in other databases), which returns immediately. You won't get any return data from the database with these kinds of queries, and they are not guaranteed to be applied.
By using INSERT DEL... | Logging in a PHP webapp | [
"",
"php",
"logging",
""
] |
I'm using Google App Engine and Django templates.
I have a table that I want to display the objects look something like:
```
Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
```
The Django template is:
```
<table>
<tr align="center">
<th>user</th>
{% for item in r... | I found a "nicer"/"better" solution for getting variables inside
Its not the nicest way, but it works.
You install a custom filter into django which gets the key of your dict as a parameter
To make it work in google app-engine you need to add a file to your main directory,
I called mine *django\_hack.py* which contai... | I'm assuming that the part the doesn't work is `{{ user.item }}`.
Django will be trying a dictionary lookup, but using the string `"item"` and not the value of the `item` loop variable. Django did the same thing when it resolved `{{ user.name }}` to the `name` attribute of the `user` object, rather than looking for a ... | Django templates and variable attributes | [
"",
"python",
"django",
"google-app-engine",
""
] |
I need an associative container that makes me index a certain object through a string, but that also keeps the order of insertion, so I can look for a specific object by its name or just iterate on it and retrieve objects in the same order I inserted them.
I think this [hybrid of linked list and hash map](http://www.d... | [Boost documentation of unordered containers](http://www.boost.org/doc/libs/1_36_0/doc/html/unordered.html)
The difference is in the method of how you generate the look up.
In the map/set containers the `operator<` is used to generate an ordered tree.
In the unordered containers, an `operator( key ) => index` is use... | You've asked for the canonical reason why Boost::MultiIndex was made: list insertion order with fast lookup by key. [Boost MultiIndex tutorial: list fast lookup](http://www.boost.org/doc/libs/1_36_0/libs/multi_index/doc/tutorial/basics.html#list_fast_lookup) | I don't understand std::tr1::unordered_map | [
"",
"c++",
"tr1",
"unordered-map",
""
] |
For example I have such query:
```
Query q = sess.createQuery("from Cat cat");
List cats = q.list();
```
If I try to make something like this it shows the following warning
```
Type safety: The expression of type List needs unchecked conversion to conform to List<Cat>
List<Cat> cats = q.list();
```
Is there a way... | Using `@SuppressWarnings` everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call `q.list()`.
There are two other techniques I'd suggest:
**Write a cast-helper**
Simply refactor all your `@SuppressWarnings` into one place:
```
List<Cat> cats = MyHibernateUt... | It is been a long time since the question was asked but I hope my answer might be helpful to someone like me.
If you take a look at javax.persistence [api docs](http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#createQuery(java.lang.String,%20java.lang.Class)), you will see that some new methods... | How to avoid type safety warnings with Hibernate HQL results? | [
"",
"java",
"generics",
""
] |
Anyone know how to turn off code folding in visual studio 2008? Some of my colleagues love it, but I personally always want to see all the code, and never want code folded out of sight. I'd like a setting that means my copy of Visual Studio never folds `#regions`or function bodies. | # Edit: [I recommend this other answer](https://stackoverflow.com/questions/115694/how-to-permanently-disable-region-folding-in-visual-studio-2008/6209270#6209270)
Go to the Tools->Options menu.
Go to Text Editor->C#->Advanced. Uncheck "Enter outlining mode when files open".
That will disable all outlining, including... | The accepted answer turns off ALL code folding. If you want to disable #region folding but collapse comments, loops, methods, etc I wrote a plugin that does this for you.
**Make #regions suck less (for free):**
<http://visualstudiogallery.msdn.microsoft.com/0ca60d35-1e02-43b7-bf59-ac7deb9afbca>
* Auto Expand regions... | How to permanently disable region-folding in Visual Studio 2008 | [
"",
"c#",
"visual-studio-2008",
"text-editor",
"outlining",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.