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 "later" .dll inherited from it. Now I get this error:
> Error 1150 genasm.exe(1) : error There
> was an error finalizing type . Method
> 'DoParse' in type
> 'MyComanyName.PlatformName.ProductName.Configuration.ConfigurationParser'
> from assembly
> 'UICore.WindowsCE.asmmeta,
> Version=1.0.3187.17348,
> Culture=neutral, PublicKeyToken=null'
> does not have an
> implementation. UICore
And yes, I have implemented this method in this class. I have also tried a full clean and rebuild and a close and restart VS.
Out of interest, I also have a warning that is "Object not set to instance of object" which is slightly unusual.
**Update:** If I make the method virtual as opposed to abstract the problem disappears.
**Update:**
* CF 2.0 SP1
* Visual Studio 2005 SP1
* The method is not generic
* However I do give an object with a generic method to the constructor of this object.
|
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 some workarounds discussed.
|
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 two more bytes of storage (for length or termination) in addition to the actual data. So (assuming you are using a one-byte character set) storing the word "FooBar"
* **CHAR(6)** = 6 bytes *(no overhead)*
* **VARCHAR(100)** = 8 bytes *(2 bytes of overhead)*
* **CHAR(10)** = 10 bytes *(4 bytes of waste)*
The bottom line is **CHAR** *can* be *faster* and more *space-efficient* for data of relatively the same length (within two characters length difference).
**Note**: Microsoft SQL has 2 bytes of overhead for a VARCHAR. This may vary from DB to DB, but generally, there is at least 1 byte of overhead needed to indicate length or EOL on a VARCHAR.
As was pointed out by *[Gaven](https://stackoverflow.com/users/1106569/gavin-towey)* in the comments: Things change when it comes to [multi-byte characters](http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-utf8.html) sets, and is a is case where VARCHAR becomes a much better choice.
*A note about the declared length of the **VARCHAR***: Because it stores the length of the actual content, then you don't waste unused length. So storing 6 characters in *VARCHAR(6), VARCHAR(100), *or* VARCHAR(MAX)* uses the same amount of storage. Read more about the differences when using [VARCHAR(MAX)](https://stackoverflow.com/a/8512232/255). You declare a *maximum* size in VARCHAR to limit how much is stored.
In the comments [AlwaysLearning](https://stackoverflow.com/users/10990028/alwayslearning) pointed out that the [Microsoft Transact-SQL docs](https://learn.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql?view=sql-server-ver15) seem to say the opposite. I would suggest that is an error or at least the docs are unclear.
|
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 "myth".
Another thing: I have never seen a performance problem because someone decided to go with `varchar`. You will make much better use of your time writing good code (fewer calls to the database) and efficient SQL (how do indexes work, how does the optimizer make decisions, why is `exists` faster than `in` usually...).
Final thought: I have seen all sorts of problems with use of `CHAR`, people looking for '' when they should be looking for ' ', or people looking for 'FOO' when they should be looking for 'FOO (bunch of spaces here)', or people not trimming the trailing blanks, or bugs with Powerbuilder adding up to 2000 blanks to the value it returns from an Oracle procedure.
|
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 following error
> "Cannot bind to the propery 'Name' on the target control.
What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development.
|
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
```
private final transient Logger log = Logger.getLogger(getClass());
```
instead?
|
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](http://java.sun.com/developer/technicalArticles/ALT/serialization/#2)
Added content:
As you use [getLogger(getClass())](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html#getLogger(java.lang.String)), you will use the same logger in each instance. If you want to use separate logger for each instance you have to differentiate on the name of the logger in the getLogger() -method. e.g. getLogger(getClass().getName() + hashCode()). You should then use the transient attribute to make sure that the logger is not serialized.
|
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 can do.
|
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 */
result.add(mb.open());
}});
if (SWT.OK == result.get(0)) { /* ... */ }
```
I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?
|
[`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 `AtomicInteger` in your case or `AtomicReference` in a more general case.
```
final AtomicInteger resultAtomicInteger = new AtomicInteger();
Display.getCurrent().syncExec(new Runnable() {
public void run() {
MessageBox mb = /* ... */;
/* set up messagebox */
resultAtomicInteger.set(mb.open());
}});
if (SWT.OK == resultAtomicInteger.get()) { /* ... */ }
```
|
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 messagebox */
result = mb.open();
}
GUI.display().syncExec(runBlock);
runBlock.result; //holds a result Integer
```
It's much tidier and removes redundant variables.
BTW. My really first try was to use UIThreadRunnable, but I didn't want SWTBot dependency, so I dropped this solution. After I made my own solution I found out, they use similar work around in there.
|
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.mainloop()
```
---
**Explanation:**
```
root.quit()
```
The above line just ***bypasses*** the `root.mainloop()`, i.e., `root.mainloop()` will still be running ***in the background*** if `quit()` command is executed.
```
root.destroy()
```
While `destroy()` command vanishes out `root.mainloop()`, i.e., `root.mainloop()` stops. `<window>.destroy()` ***completely*** destroys and *closes* the window.
So, if you want to exit and close the program completely, you should use `root.destroy()`, as it stops the `mainloop()` and destroys the window and all its widgets.
But if you want to run some infinite loop and don't want to destroy your Tkinter window and want to execute some code after the `root.mainloop()` line, you should use `root.quit()`. Example:
```
from Tkinter import *
def quit():
global root
root.quit()
root = Tk()
while True:
Button(root, text="Quit", command=quit).pack()
root.mainloop()
#do something
```
See [What is the difference between root.destroy() and root.quit()?](https://stackoverflow.com/questions/2307464/what-is-the-difference-between-root-destroy-and-root-quit).
|
```
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 divert socket on Mac OS X. You can actually create the rule in your C code.
For you case, just scan the packet for TCP or IP header and parse for whatever you want
|
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 looking at RoR, Php or even Java (J2EE to be precise). I am not much of a Javascript/CSS guy so a toolkit that might make it relatively easy on me on those fronts would be preferable.
Also, I am a mac user at home. What IDEs go along with the framework you would recommend?
Any recommendations guys?
|
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 your use case anyway.
GWT will allow you to scale up by using more of its features as your app gets more complex - and your prototype won't be throwaway code.
|
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 fat or thin. When you're done it all compiles down into HTML and javascript, and has very good modern browser support (ie6+ ff, opera, safari).
It does abstract all the javascript and HTML away, but if you want it to look good you'll still need to understand CSS.
I think anyone who says that that it ruins MVC or that it's a muddying of client vs server doesn't understand GWT. GWT is a CLIENT side framework. And it is only used on the CLIENT. GWT does provide an RPC mechanism to hook it into JAVA (and other) back ends, but that's just a communication protocol, it doesn't mean that your server code magically becomes your client code. Sure you can write a whole bunch of business rules into your UI if you really wanted to, but you can do this with any framework, so it would be silly to say that GWT is somehow different in that respect.
|
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 due to the classic `#ifndef HEADER` `#define HEADER` `#endif` trick (if that matters).
Does the static mean only one copy of `VAL` is created, in case the header is included by more than one source file?
|
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` while the other source files declared it `extern`. Usually one would do this by defining it (possibly with an initializer) in a source file and put the `extern` declaration in a header file.
`static` variables at global level are only visible in their own source file whether they got there via an include or were in the main file.
---
*Editor's note:* In C++, `const` objects with neither the `static` nor `extern` keywords in their declaration are implicitly `static`.
|
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 translation units.
* `extern` gives the variable external linkage, making it visible to other translation units. Typically this means that the variable must only be defined in one translation unit.
The default (when you don't specify `static` or `extern`) is one of those areas in which C and C++ differ.
* In C, file-scoped variables are `extern` (external linkage) by default. If you're using C, `VAL` is `static` and `ANOTHER_VAL` is `extern`.
* In C++, file-scoped variables are `static` (internal linkage) by default if they are `const`, and `extern` by default if they are not. If you're using C++, both `VAL` and `ANOTHER_VAL` are `static`.
From a draft of the [C specification](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf):
> 6.2.2 Linkages of identifiers
> ...
> -5- If the declaration of an identifier for a function has no storage-class specifier, its linkage
> is determined exactly as if it were declared with the storage-class specifier extern. If
> the declaration of an identifier for an object has file scope and no storage-class specifier,
> its linkage is external.
From a draft of the [C++ specification](http://www.kuzbass.ru:8086/docs/isocpp/dcl.html):
> 7.1.1 - Storage class specifiers [dcl.stc]
> ...
> -6- A name declared in a namespace scope without a storage-class-specifier has external linkage unless it has internal linkage because of a previous declaration and provided it is not declared const. Objects declared const and not explicitly declared extern have internal linkage.
|
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 isn't expired.
3. I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.
Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the `DateTime` object. Or should I just keep processing it as I am?
|
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 use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.
|
**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 `InputStream` `in` and an `OutputStream` `out`, is there a simpler way to write the following?
```
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
```
|
# 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` will:
> Reads all bytes from this input stream and writes the bytes to the
> given output stream in the order that they are read. On return, this
> input stream will be at end of stream. This method does not close
> either stream.
>
> This method may block indefinitely reading from the
> input stream, or writing to the output stream. The behavior for the
> case where the input and/or output stream is asynchronously closed, or
> the thread interrupted during the transfer, is highly input and output
> stream specific, and therefore not specified
So in order to write contents of a Java `InputStream` to an `OutputStream`, you can write:
```
input.transferTo(output);
```
|
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 have:
```
InputStream in;
OutputStream out;
IOUtils.copy(in,out);
in.close();
out.close();
```
...in your code.
Is there a reason you're avoiding `IOUtils`?
|
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 consideration?
|
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 query string. So if you queried such a script thusly:
```
http://site.com/script.php?hello=world&foo=bar
```
... the script would automatically define a variable $hello with value "world" and $foo with value "bar."
For such a script, if you knew the names of key variables, it was possible to exploit the script by specifying those variables on the query string. The solution? Define some magic string in the core script and then make all the ancilliary scripts check for the magic string and bail out if it's not there.
Thankfully, almost nobody uses register\_variables anymore, but many scripts are still very poorly written and make stupid assumptions that cause them to do damage if they are called out of context.
Personally, I avoid the whole thing by using the Symfony framework, which (at least in its default setup) keeps the controllers and templates out of the web root altogether. The only entry point is the front controller.
|
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> Override location of installed extensions
-help Print this usage message
-J<flag> Pass <flag> directly to the runtime system
-l Print line number and local variable tables
-public Show only public classes and members
-protected Show protected/public classes and members
-package Show package/protected/public classes
and members (default)
-private Show all classes and members
-s Print internal type signatures
-bootclasspath <pathlist> Override location of class files loaded
by the bootstrap class loader
-verbose Print stack size, number of locals and args for methods
If verifying, print reasons for failure
```
|
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 memory the OS can provide, much larger than the stack, but then again you must make sure to free the memory when you are done. Also, creating too many objects too frequently in the heap will tend to fragment the memory, which in turn will affect the performance of your application.
|
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; }
};
```
Is this the only use of this keyword, or is there more to it than meets the eye? I have since used this technique in a class, marking a `boost::mutex` as `mutable`, allowing `const` functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.
|
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 `mutable` can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):
```
int x = 0;
auto f1 = [=]() mutable {x = 42;}; // OK
auto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda
```
|
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 any visible data members
* permission to call only methods that are marked as `const`.
The `mutable` exception makes it so you can now write or set data members that are marked `mutable`. That's the only externally visible difference.
Internally those `const` methods that are visible to you can also write to data members that are marked `mutable`. Essentially the const veil is pierced comprehensively. It is completely up to the API designer to ensure that `mutable` doesn't destroy the `const` concept and is only used in useful special cases. The `mutable` keyword helps because it clearly marks data members that are subject to these special cases.
In practice you can use `const` obsessively throughout your codebase (you essentially want to "infect" your codebase with the `const` "disease"). In this world pointers and references are `const` with very few exceptions, yielding code that is easier to reason about and understand. For a interesting digression look up "referential transparency".
Without the `mutable` keyword you will eventually be forced to use `const_cast` to handle the various useful special cases it allows (caching, ref counting, debug data, etc.). Unfortunately `const_cast` is significantly more destructive than `mutable` because it forces the API **client** to destroy the `const` protection of the objects (s)he is using. Additionally it causes widespread `const` destruction: `const_cast`ing a const pointer or reference allows unfettered write and method calling access to visible members. In contrast `mutable` requires the API designer to exercise fine grained control over the `const` exceptions, and usually these exceptions are hidden in `const` methods operating on private data.
(N.B. I refer to to data and method *visibility* a few times. I'm talking about members marked as public vs. private or protected which is a totally different type of object protection discussed [here](https://stackoverflow.com/questions/224966/private-and-protected-members-c).)
|
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 columns and delete the hex values. Then start at the bottom of the string and continually page up/delete (the newline) to build your string (I use a macro for that bit).
I don't think there's any better way once you get long strings.
|
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 record was or was not inserted?
|
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 elements to map here
int k = 4; // assume we're searching for keys equal to 4
int v = 0; // assume we want the value 0 associated with the key of 4
MapType::iterator lb = mymap.lower_bound(k);
if(lb != mymap.end() && !(mymap.key_comp()(k, lb->first)))
{
// key already exists
// update lb->second if you care to
}
else
{
// the key does not exist in the map
// add it to the map
mymap.insert(lb, MapType::value_type(k, v)); // Use lb as a hint to insert,
// so it can avoid another lookup
}
```
|
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.second) {
// insertion took place (ie. new entry)
}
else if ( replaceEntry ( ir.first->first ) ) {
ir.first->second = v;
}
}
```
For a value type such as an int, the above will more efficient than a find followed by an insert (in the absence of compiler optimizations). As stated above, this is because the search through the map only takes place once.
However, the call to insert requires that you already have the new "value" constructed:
```
class LargeDataType { /* ... */ };
typedef std::map <int, LargeDataType> MapOfLargeDataType;
typedef std::pair <MapOfLargeDataType::iterator, bool> IResult;
void foo (MapOfLargeDataType & m, int k) {
// This call is more expensive than a find through the map:
LargeDataType const & v = VeryExpensiveCall ( /* ... */ );
IResult ir = m.insert (std::make_pair (k, v));
if (ir.second) {
// insertion took place (ie. new entry)
}
else if ( replaceEntry ( ir.first->first ) ) {
ir.first->second = v;
}
}
```
In order to call 'insert' we are paying for the expensive call to construct our value type - and from what you said in the question you won't use this new value 20% of the time. In the above case, if changing the map value type is not an option then it is more efficient to first perform the 'find' to check if we need to construct the element.
Alternatively, the value type of the map can be changed to store handles to the data using your favourite smart pointer type. The call to insert uses a null pointer (very cheap to construct) and only if necessary is the new data type constructed.
|
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 recieve the following error when I try to run any of the example page which should connect to my Google Calendar.
```
Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Unable to Connect to ssl://www.google.com:443. Error #24063472: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?'
```
I have looked in many places to try to get OpenSSL running on my machine and installed.
Does anyone know of a simple failsafe tutorial to get this combination up and running?
|
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 add it and php complains then you should re-run the installer and go through the list of extensions, it would be under OpenSSL.
|
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 parser to translate escape sequences, or (b) a .NET method to interpret a string in the way that the C# compiler would?
I realize that I can go in there looking for `\n` sequences, but it would be nicer to have a generic way to do this.
|
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 a list of threads by pressing 't' but stacktraces are not included.
If answers require certain java versions, please say so.
|
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 Unix:* `kill -3 <java_process_id>`
(e.g. kill -3 5555). This will NOT kill your app.
One other thing: As others say, you can get the stacks programatically via the `Thread` class but watch out for `Thread.getAllStackTraces()` prior to JDK6 as there's a memory leak.
<https://bugs.java.com/bugdatabase/view_bug?bug_id=6434648>
Regards,
scotty
|
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 code I was reading:
```
double d = 3.1415;
float f = Convert.ToSingle(d);
```
Is that the same as:
```
float f = (float)d;
```
Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.
|
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.
In some algorithms, the rounding method used is critical to getting the right answer.
|
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 enabled by default
to allow JVM monitoring and performance testing. Disabling it
suppresses the creation of the hsperfdata_userid directories.
To disable the perfdata feature, specify -XX:-UsePerfData.
```
|
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 performance (a trivial amount).
So the downside of turning off jvmstat instrumentation is that you lose the performance monitoring information.
jvmstat is described here <http://java.sun.com/performance/jvmstat/>
Here's a thread with someone who is worried that by turning **on** jvmstat - with the option `-XX:+UsePerfData` - will hurt performance.
<http://www.theserverside.com/discussions/thread.tss?thread_id=33833>
(It probably won't since jvmstat is designed to be "'always on', yet has negligible performance impact".)
|
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 that will generate small (32 or 16) bit values and have a low collision rate?
I'd like to see an optimized implementation specific to C/C++.
|
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 if that can be of some help and is in c#.
I already used iTextSharp for parsing PDF
|
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 "WholeStory" property out of the Word document, paste it to the clipboard, then pull it from the clipboard while converting it to text format. The clipboard step is presumably done to strip out formatting.
For PowerPoint, you do a similar thing, but you need to loop through the slides, then for each slide loop through the shapes, and grab the "TextFrame.TextRange.Text" property in each shape.
For Excel, since Excel can be an OleDb data source, it's easiest to use ADO.NET. Here's a [good post by Laurent Bugnion](http://geekswithblogs.net/lbugnion/archive/2006/08/25.aspx) that walks through this technique.
|
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 any filetype where an IFilter is available. There are IFilters for Word, Excel, Powerpoint, PDf, and most of the other common document types.
|
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 Scripting technology. It works in WSF files and can include scripts written in any supported ActiveScript language such as Perl as long as the engine is installed.
Edit: The specific "gotcha" of all JScript being executed first, then VBScript is related to how ASP processes scripts. The MSHTA host (which uses IE's engine) does not have this problem. I'm not much into HTAs though, so I can't address any other possible "gotchas".
|
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, and also in vbscript you can call js functions. Then you can use their returns where you call them.
Regards
|
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 this? I'm primarily a java developer so If I could do it in an applet that would be great, but It may be easier to accomplish this using flash or some other technology.
This would mean streaming the video back to the webserver and storing it there.
Uploading a file is easy enough, but I'd rather the user not have to deal with that if it's possible.
Just to be clear. I'm not talking about uploading a video. I'm talking about allowing the user to click "record" in a web application and having the video streamed to the server and stored when the user clicks "stop".
|
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 your own server or else go for a web provider (I found [this list](http://www.flashcomguru.com/articles/hosts.cfm) to be helpful)
On the client side, you'll need a flash file for the user interface. Red5 and Wowza some with the source code for their example recorders so it's easy to customize these for your own use.
|
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.AbsolutePath;
}
}
```
which could then be used like this:
```
string url = "foo/bar/../bar/path.aspx";
Console.WriteLine(UriHelper.NormalizeRelativePath(url));
```
It is a bit hacky but it would work for the specific example you gave.
**EDIT: Updated to reflect Andrew's comments.**
|
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 arbitrarily.
If you want to use UriBuilder to do this, just create a new one when you need it (it's not expensive to create).
|
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 symbols have been loaded for this document.
How do I fix this? I'm guessing that Visual Studio is having some trouble parsing through some of the jQuery code. I will try to replace the minimized version of `jQuery.js` with the expanded version, but I don't think that will fix it.
|
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 bring up a new instance of the script debugger, and it'll stop on your debugger command let you debug from there.
In this scenario I was already debugging the JavaScript in [Firebug](http://en.wikipedia.org/wiki/Firebug_%28software%29), but I wanted to debug against Internet Explorer as well.
|
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 process, no matter what type of data you want to add as a resource though.
* Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
* Click the "Resources" tab.
* The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
* Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
* At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.
**How to use a resource:**
Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.
There is a static class called `Properties.Resources` that gives you access to all your resources, so my code ended up being as simple as:
```
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
```
Done! Finished! Everything is simple when you know how, isn't it?
|
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.Designer.cs file, where it had an automatic getter that let me access the icon, via MyNamespace.Properties.Resources.NameFromAddingTheResource. That returns an object of type Icon, ready to just use.
|
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 been supported [since Internet Explorer 6](https://learn.microsoft.com/en-us/scripting/javascript/reference/localecompare-method-string-javascript) and Firefox 1. You may also see the following code used that doesn't respect a locale:
```
if (item1.attr < item2.attr)
return -1;
if ( item1.attr > item2.attr)
return 1;
return 0;
```
|
## 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-strings-in-javascript/51169#51169), the answer to your question is:
```
return item1.attr.localeCompare(item2.attr);
```
### Bugs found in all the custom JavaScript "natural string sort order" implementations
There are quite a bunch of custom implementations out there, trying to do string comparison more precisely called "natural string sort order"
When "playing" with these implementations, I always noticed some strange "natural sorting order" choice, or rather mistakes (or omissions in the best cases).
Typically, special characters (space, dash, ampersand, brackets, and so on) are not processed correctly.
You will then find them appearing mixed up in different places, typically that could be:
* some will be between the uppercase 'Z' and the lowercase 'a'
* some will be between the '9' and the uppercase 'A'
* some will be after lowercase 'z'
When one would have expected special characters to all be "grouped" together in one place, except for the space special character maybe (which would always be the first character). That is, either all before numbers, or all between numbers and letters (lowercase & uppercase being "together" one after another), or all after letters.
My conclusion is that they all fail to provide a consistent order when I start adding barely unusual characters (i.e., characters with diacritics or characters such as dash, exclamation mark and so on).
Research on the custom implementations:
* ***Natural Compare Lite*** <https://github.com/litejs/natural-compare-lite> : Fails at sorting consistently <https://github.com/litejs/natural-compare-lite/issues/1> and <http://jsbin.com/bevututodavi/1/edit?js,console>, basic Latin characters sorting <http://jsbin.com/bevututodavi/5/edit?js,console>
* ***Natural Sort*** <https://github.com/javve/natural-sort> : Fails at sorting consistently, see issue <https://github.com/javve/natural-sort/issues/7> and see basic Latin characters sorting <http://jsbin.com/cipimosedoqe/3/edit?js,console>
* ***JavaScript Natural Sort*** <https://github.com/overset/javascript-natural-sort>: seems rather neglected since February 2012, Fails at sorting consistently, see issue <https://github.com/overset/javascript-natural-sort/issues/16>
* ***Alphanum*** <http://www.davekoelle.com/files/alphanum.js> , Fails at sorting consistently, see <http://jsbin.com/tuminoxifuyo/1/edit?js,console>
### Browsers' native "natural string sort order" implementations via `localeCompare()`
[localeCompare()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) oldest implementation (without the locales and options arguments) is supported by [Internet Explorer 6](https://en.wikipedia.org/wiki/Internet_Explorer_6) and later, see *[Legacy Microsoft Edge developer documentation](http://msdn.microsoft.com/en-us/library/ie/s4esdbwz(v=vs.94).aspx)* (scroll down to the localeCompare() method).
The built-in `localeCompare()` method does a much better job at sorting, even international and special characters.
The only problem using the `localeCompare()` method is that ["the locale and sort order used are entirely implementation dependent". In other words, when using localeCompare such as stringOne.localeCompare(stringTwo): Firefox, Safari, Chrome, and Internet Explorer have a different sort order for Strings.](https://code.google.com/p/v8/issues/detail?id=459)
Research on the browser-native implementations:
* <http://jsbin.com/beboroyifomu/1/edit?js,console> - basic Latin characters comparison with localeCompare()
<http://jsbin.com/viyucavudela/2/> - basic Latin characters comparison with localeCompare() for testing on [Internet Explorer 8](https://en.wikipedia.org/wiki/Internet_Explorer_8)
* <http://jsbin.com/beboroyifomu/2/edit?js,console> - basic Latin characters in string comparison : consistency check in string vs when a character is alone
* *[String.prototype.localeCompare()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)* - [Internet Explorer 11](https://en.wikipedia.org/wiki/Internet_Explorer_11#Internet_Explorer_11) and later supports the new locales & options arguments
### Difficulty of "string natural sorting order"
Implementing a solid algorithm (meaning: consistent but also covering a wide range of characters) is a very tough task. UTF-8 contains [more than 2000 characters](http://en.wikipedia.org/wiki/UTF-8) and [covers more than 120 scripts (languages)](http://www.unicode.org/standard/supported.html).
Finally, there are some specification for this tasks, it is called the "[Unicode Collation Algorithm](http://www.unicode.org/reports/tr10/)". You can find more information about this on this question I posted, *[Is there a language-agnostic specification for "string natural sorting order"?](https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order)*
## Final conclusion
So considering the current level of support provided by the JavaScript custom implementations I came across, we will probably never see anything getting any close to supporting all these characters and scripts (languages). Hence I would rather use the browsers' native localeCompare() method. Yes, it does have the downside of being non-consistent across browsers, but basic testing shows it covers a much wider range of characters, allowing solid and meaningful sort orders.
So as [pointed out by Shog9](https://stackoverflow.com/questions/51165/how-to-sort-strings-in-javascript/51169#51169), the answer to your question is:
```
return item1.attr.localeCompare(item2.attr);
```
### Further reading:
* *[Is there a language-agnostic specification for "string natural sorting order"?](https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order)*
* *[How to sort strings in JavaScript](https://stackoverflow.com/questions/51165/how-do-you-do-string-comparison-in-javascript)*
* *[Natural sort of alphanumerical strings in JavaScript](https://stackoverflow.com/questions/2802341/natural-sort-of-text-and-numbers-javascript)*
* *[Sort Array of numeric & alphabetical elements (Natural Sort)](https://stackoverflow.com/questions/4373018/sort-array-of-numeric-alphabetical-elements-natural-sort/)*
* *[Sort mixed alpha/numeric array](https://stackoverflow.com/questions/4340227/sort-mixed-alpha-numeric-array)*
* <https://web.archive.org/web/20130929122019/http://my.opera.com/GreyWyvern/blog/show.dml/1671288>
* <https://web.archive.org/web/20131005224909/http://www.davekoelle.com/alphanum.html>
* <http://snipplr.com/view/36012/javascript-natural-sort/>
* *[Sorting for Humans : Natural Sort Order](http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/)*
Thanks to [Shog9's nice answer](https://stackoverflow.com/questions/51165/how-to-sort-strings-in-javascript/51169#51169), which put me in the "right" direction I believe.
|
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 MyClass2, that field must be accessible to MyClass, either directly or through getters and setters. MyClass will have to implement custom serialization by providing readObject and writeObject methods.
* the non-serializable field's Class must have an API to allow getting it's state (for writing to the object stream) and then instantiating a new instance with that state (when later reading from the object stream.)
* per Item 74 of Effective Java, MyClass2 *must* have a no-arg constructor accessible to MyClass, otherwise it is impossible for MyClass to extend MyClass2 and implement Serializable.
I've written a quick example below illustrating this.
```
class MyClass extends MyClass2 implements Serializable{
public MyClass(int quantity) {
setNonSerializableProperty(new NonSerializableClass(quantity));
}
private void writeObject(java.io.ObjectOutputStream out)
throws IOException{
// note, here we don't need out.defaultWriteObject(); because
// MyClass has no other state to serialize
out.writeInt(super.getNonSerializableProperty().getQuantity());
}
private void readObject(java.io.ObjectInputStream in)
throws IOException {
// note, here we don't need in.defaultReadObject();
// because MyClass has no other state to deserialize
super.setNonSerializableProperty(new NonSerializableClass(in.readInt()));
}
}
/* this class must have no-arg constructor accessible to MyClass */
class MyClass2 {
/* this property must be gettable/settable by MyClass. It cannot be final, therefore. */
private NonSerializableClass nonSerializableProperty;
public void setNonSerializableProperty(NonSerializableClass nonSerializableProperty) {
this.nonSerializableProperty = nonSerializableProperty;
}
public NonSerializableClass getNonSerializableProperty() {
return nonSerializableProperty;
}
}
class NonSerializableClass{
private final int quantity;
public NonSerializableClass(int quantity){
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
}
```
|
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 it will be ignored during the serialization and deserialization process. Keep in mind that when you deserialize an object with a transient field that field's value will always be it's default (usually null.)
Note you can also override the readResolve() method of your class in order to initialize transient fields based on other system state.
|
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 more in to automated testing (comparing reference/expected data against that returned).
While looking over some of the [coding standards guidelines in MSDN](http://msdn.microsoft.com/en-us/library/ms229042(VS.80).aspx) I came across an [article](http://msdn.microsoft.com/en-us/library/7h9bszxx(VS.80).aspx) that advises against it. Now I understand *why* the article is saying this (because they are not the same *instance*) but it does not answer the question:
1. **What is the best way to compare two reference types?**
2. Should we implement [IComparable](http://msdn.microsoft.com/en-us/library/system.icomparable.aspx)? (I have also seen mention that this should be reserved for value types only).
3. Is there some interface I don't know about?
4. Should we just roll our own?!
Many Thanks ^\_^
## Update
Looks like I had mis-read some of the documentation (it's been a long day) and overriding [Equals](http://msdn.microsoft.com/en-us/library/336aedhh(VS.71).aspx) may be the way to go..
> If you are implementing reference
> types, you should consider overriding
> the Equals method on a reference type
> if your type looks like a base type
> such as a Point, String, BigNumber,
> and so on. Most reference types should
> not overload the **equality** operator,
> even **if they override Equals**. However,
> if you are implementing a reference
> type that is intended to have value
> semantics, such as a complex number
> type, you should override the equality
> operator.
|
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://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx):
```
class TwoDPoint : System.Object
{
public readonly int x, y;
public TwoDPoint(int x, int y) //constructor
{
this.x = x;
this.y = y;
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public override int GetHashCode()
{
return x ^ y;
}
}
```
Java has very similar mechanisms. The *equals()* method is part of the *Object* class, and your class overloads it if you want this type of functionality.
The reason overloading '==' can be a bad idea for objects is that, usually, you still want to be able to do the "are these the same pointer" comparisons. These are usually relied upon for, for instance, inserting an element into a list where no duplicates are allowed, and some of your framework stuff may not work if this operator is overloaded in a non-standard way.
|
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-value-equality-for-a-type)), you should implement [the `System.IEquatable<T>` interface](https://msdn.microsoft.com/en-us/library/ms131187%28v=vs.110%29.aspx), and you should implement all the different operations (`Equals`, `GetHashCode` and `==`, `!=`).
As an example, here’s a class implementing value equality:
```
class Point : IEquatable<Point> {
public int X { get; }
public int Y { get; }
public Point(int x = 0, int y = 0) { X = x; Y = y; }
public bool Equals(Point other) {
if (other is null) return false;
return X.Equals(other.X) && Y.Equals(other.Y);
}
public override bool Equals(object obj) => Equals(obj as Point);
public static bool operator ==(Point lhs, Point rhs) => object.Equals(lhs, rhs);
public static bool operator !=(Point lhs, Point rhs) => ! (lhs == rhs);
public override int GetHashCode() => HashCode.Combine(X, Y);
}
```
The only movable parts in the above code are the bolded parts: the second line in `Equals(Point other)` and the `GetHashCode()` method. The other code should remain unchanged.
For reference classes that do not represent immutable values, do not implement the operators `==` and `!=`. Instead, use their default meaning, which is to compare object identity.
The code *intentionally* equates even objects of a derived class type. Often, this might not be desirable because equality between the base class and derived classes is not well-defined. Unfortunately, .NET and the coding guidelines are not very clear here. The code that Resharper creates, posted [in another answer](https://stackoverflow.com/q/104158/1968#104209), is susceptible to undesired behaviour in such cases because `Equals(object x)` and `Equals(SecurableResourcePermission x)` *will* treat this case differently.
In order to change this behaviour, an additional type check has to be inserted in the strongly-typed `Equals` method above:
```
public bool Equals(Point other) {
if (other is null) return false;
if (other.GetType() != GetType()) return false;
return X.Equals(other.X) && Y.Equals(other.Y);
}
```
|
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 no measured need to improve performance, but am simply curious if a simple `HashMap` would suffice. Hence, this question is *not* "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?")
|
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 between the construction of the `HashMap` and any reading threads that may access it before it is fully constructed. Most of the discussion is about what happens to the state of the map object, but this is irrelevant since you never modify it - so the only interesting part is how the `HashMap` reference is published.
For example, imagine you publish the map like this:
```
class SomeClass {
public static HashMap<Object, Object> MAP;
public synchronized static setMap(HashMap<Object, Object> m) {
MAP = m;
}
}
```
... and at some point `setMap()` is called with a map, and other threads are using `SomeClass.MAP` to access the map, and check for null like this:
```
HashMap<Object,Object> map = SomeClass.MAP;
if (map != null) {
.. use the map
} else {
.. some default behavior
}
```
This is **not safe** even though it probably appears as though it is. The problem is that there is no [*happens-before*](https://docs.oracle.com/javase/tutorial/essential/concurrency/memconsist.html) relationship between the set of `SomeObject.MAP` and the subsequent read on another thread, so the reading thread is free to see a partially constructed map. This can pretty much do *anything* and even in practice it does things like [put the reading thread into an infinite loop](http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html).
To safely publish the map, you need to establish a *happens-before* relationship between the *writing of the reference* to the `HashMap` (i.e., the *publication*) and the subsequent readers of that reference (i.e., the consumption). Conveniently, there are only a few easy-to-remember ways to [accomplish](https://stackoverflow.com/q/5458848/149138) that[1]:
1. Exchange the reference through a properly locked field ([JLS 17.4.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5))
2. Use static initializer to do the initializing stores ([JLS 12.4](http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4))
3. Exchange the reference via a volatile field ([JLS 17.4.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5)), or as the consequence of this rule, via the AtomicX classes
4. Initialize the value into a final field ([JLS 17.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.5)).
The ones most interesting for your scenario are (2), (3) and (4). In particular, (3) applies directly to the code I have above: if you transform the declaration of `MAP` to:
```
public static volatile HashMap<Object, Object> MAP;
```
then everything is kosher: readers who see a *non-null* value necessarily have a *happens-before* relationship with the store to `MAP` and hence see all the stores associated with the map initialization.
The other methods change the semantics of your method, since both (2) (using the static initalizer) and (4) (using *final*) imply that you cannot set `MAP` dynamically at runtime. If you don't *need* to do that, then just declare `MAP` as a `static final HashMap<>` and you are guaranteed safe publication.
In practice, the rules are simple for safe access to "never-modified objects":
If you are publishing an object which is not *inherently immutable* (as in all fields declared `final`) and:
* You already can create the object that will be assigned at the moment of declarationa: just use a `final` field (including `static final` for static members).
* You want to assign the object later, after the reference is already visible: use a volatile fieldb.
That's it!
In practice, it is very efficient. The use of a `static final` field, for example, allows the JVM to assume the value is unchanged for the life of the program and optimize it heavily. The use of a `final` member field allows *most* architectures to read the field in a way equivalent to a normal field read and doesn't inhibit further optimizationsc.
Finally, the use of `volatile` does have some impact: no hardware barrier is needed on many architectures (such as x86, specifically those that don't allow reads to pass reads), but some optimization and reordering may not occur at compile time - but this effect is generally small. In exchange, you actually get more than what you asked for - not only can you safely publish one `HashMap`, you can store as many more not-modified `HashMap`s as you want to the same reference and be assured that all readers will see a safely published map.
For more gory details, refer to [Shipilev](https://shipilev.net/blog/2014/safe-public-construction/) or [this FAQ by Manson and Goetz](https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight).
---
[1] Directly quoting from [shipilev](https://shipilev.net/blog/2014/safe-public-construction/).
---
a That sounds complicated, but what I mean is that you can assign the reference at construction time - either at the declaration point or in the constructor (member fields) or static initializer (static fields).
b Optionally, you can use a `synchronized` method to get/set, or an `AtomicReference` or something, but we're talking about the minimum work you can do.
c Some architectures with very weak memory models (I'm looking at *you*, Alpha) may require some type of read barrier before a `final` read - but these are very rare today.
|
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 might surprise you - Java has a relatively complicated set of rules to determine immutability.
For more info on the topic, read Jeremy's blog posts:
Part 1 on Immutability in Java:
<http://jeremymanson.blogspot.com/2008/04/immutability-in-java.html>
Part 2 on Immutability in Java:
<http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html>
Part 3 on Immutability in Java:
<http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-3.html>
|
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 great.
Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads.
The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?
|
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.
Nothing.
And you could put something in before the return false bit...
...and the onunload handler would still not get called... -->
<a href="http://www.google.com/" onclick="return false;">blah1</a>
<!-- this should also do nothing, but IE will trigger the onbeforeunload
handler -->
<a href="javascript:void(0)">blah2</a>
```
|
**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. Then, I attach events to the image's onmouseover and onmouseout events and write functions that will set this value. Finally, I just code in the function that handles onbeforeunload that will check this value before setting event.returnValue.
Probably not a flawless workaround but it will work for now.
|
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 Person()
{
GroupsOwned = new List<Groups>();
}
public virtual IList<Groups> GroupsOwned { get; set; }
}
public class Groups
{
public Groups()
{
Admins= new List<Person>();
}
public virtual IList<Person> Admins{ get; set; }
}
```
With the mapping looking like this
Person: ...
```
HasManyToMany<Groups>(x => x.GroupsOwned)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("PersonID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
```
Groups: ...
```
HasManyToMany<Person>(x => x.Admins)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("GroupID")
.WithChildKeyColumn("PersonID")
.Cascade.SaveUpdate();
```
When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it.
Thanks for any advice you may have.
|
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 object). The inverse attribute is specifically for avoiding this.
I'm not sure about how to add it in mapping in code, but the link shows how to do it in XML.
|
@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 violations you can use something like this:
```
begin tran
if exists (select * from table with (updlock,serializable) where key = @key)
begin
update table set ...
where key = @key
end
else
begin
insert into table (key, ...)
values (@key, ...)
end
commit tran
```
or
```
begin tran
update table with (serializable) set ...
where key = @key
if @@rowcount = 0
begin
insert into table (key, ...) values (@key,..)
end
commit tran
```
|
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). The only problem is that for inserts it's still two IO operations.
MS Sql2008 introduces `merge` from the SQL:2003 standard:
```
merge tablename with(HOLDLOCK) as target
using (values ('new value', 'different value'))
as source (field1, field2)
on target.idfield = 7
when matched then
update
set field1 = source.field1,
field2 = source.field2,
...
when not matched then
insert ( idfield, field1, field2, ... )
values ( 7, source.field1, source.field2, ... )
```
Now it's really just one IO operation, but awful code :-(
|
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 Service
ServiceInstaller si = new ServiceInstaller();
si.ServiceName = Facade.GetServiceName();
si.Description = "Processes ...";
si.DisplayName = "Auto Checkout";
si.StartType = ServiceStartMode.Automatic;
// Remove Event Source if already there
if (EventLog.SourceExists("AutoCheckout"))
EventLog.DeleteEventSource("AutoCheckout");
// Create Event Source and Event Log
EventLogInstaller log = new EventLogInstaller();
log.Source = "AutoCheckout";
log.Log = "AutoCheckoutLog";
Installers.AddRange(new Installer[] { spi, si, log });
```
The facade methods referenced just return the strings for the name of the log, service, etc.
This code works most of the time, but recently after installing I started getting my log entries showing up in the Application Log instead of the custom log. And the following errors are in the log as well:
> The description for Event ID ( 0 ) in Source ( AutoCheckout ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.
For some reason it either isn't properly removing the source during the uninstall or it isn't creating it during the install.
Any help with best practices here is appreciated.
Thanks!
In addition, here is a sample of how I am writing exceptions to the log:
```
// Write to Log
EventLog.WriteEntry(Facade.GetEventLogSource(), errorDetails, EventLogEntryType.Error, 99);
```
**Regarding stephbu's answer:** The recommended path is an installer script and installutil, or a Windows Setup routine.
I am using a Setup Project, which performs the installation of the service and sets up the log. Whether I use the installutil.exe or the windows setup project I believe they both call the same ProjectInstaller class I show above.
I see how the state of my test machine could be causing the error if the log isn't truly removed until rebooting. I will experiment more to see if that solves the issue.
**Edit:**
I'm interested in a sure fire way to register the source and the log name during the installation of the service. So if the service had previously been installed, it would remove the source, or reuse the source during subsequent installations.
I haven't yet had an opportunity to learn WiX to try that route.
|
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;
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
// serviceInstaller
ServiceInstaller serviceInstaller = new ServiceInstaller();
serviceInstaller.ServiceName = "MyService";
serviceInstaller.DisplayName = "My Service";
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.Description = "My Service Description";
// kill the default event log installer
serviceInstaller.Installers.Clear();
// Create Event Source and Event Log
EventLogInstaller logInstaller = new EventLogInstaller();
logInstaller.Source = "MyService"; // use same as ServiceName
logInstaller.Log = "MyLog";
// Add all installers
this.Installers.AddRange(new Installer[] {
serviceProcessInstaller, serviceInstaller, logInstaller
});
```
|
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 other hand preserves the file exactly as it was intended.
I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have `_RETURNTRANSFER` return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible.
Here is the code I am using. The data in question is a CSV file with \r\n line endings.
```
function update_roster() {
$url = "http://example.com/";
$userID = "xx";
$apikey = "xxx";
$passfields = "userID=$userID&apikey=$apikey";
$file = fopen("roster.csv","w+");
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file);
$variable_in_question = curl_exec ($ch);
curl_close ($ch);
fclose($file);
return $variable_in_question;
}
```
---
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 = split("\r\n", $cresult);`
This does not: `$cresult = split('\r\n', $cresult);`
|
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 = split("\r\n", $cresult);`
This does not: `$cresult = split('\r\n', $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 “foo” to the screen
```
It is true for variables and escaped characters.
|
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 doing this?
**Update:**
MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.
|
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 uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));
}
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
```
Then use like:
```
ulong installedMemory;
MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if( GlobalMemoryStatusEx( memStatus))
{
installedMemory = memStatus.ullTotalPhys;
}
```
Or you can use WMI (managed but slower) to query `TotalPhysicalMemory` in the `Win32_ComputerSystem` class.
|
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, mod\_c ... mod\_xyzzy where section\_id=value"... or even worse, using a separate query for each module.
|
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.[name] AS TABLE_NAME
FROM TABLE_OF_TABLES_TO_SEACRH t
START LOOP
IF @sql <> '' SET @sql = @sql + 'UNION ALL '
SET @sql = 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '
END LOOP
EXEC(@sql)
```
I've used this technique occasionally, when there just isn't any obvious way to make it future-proof without dynamic SQL.
Note: In your loop, you can use the COALESCE/NULL propagation trick and leave the string as NULL before the loop, but it's not as clear if you are unfamiliar with the idiom:
```
SET @sql = COALESCE(@sql + ' UNION ALL ', '')
+ 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '
```
|
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 different, you might still be able to consolidate all the common information into one table, and keep smaller module-specific tables with those differences. Then you would just need to do a join on them.
This suggestion assumes that your query on the column section\_id you mention is super-critical to look up quickly. With one query you get all the common information, and with a second you would get any specific information if you needed it. (And you might not -- for instance if you were trying to validate the existense of the section, then finding it in the common table would be enough)
2. Alternatively you can add another table that maps section\_id's to the modules that they are in.
```
section_id | module
-----------+-------
1 | A
2 | B
3 | A
... | ...
```
This does mean though that you have to run two queries, one against this mapping table, and another against the module table to pull out any useful data.
You can extend this table with other columns and indices on those columns if you need to look up other columns that are common to all modules.
This method has the definite disadvanage that the data is duplicated.
|
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 the stored procedure `sp_help`
```
exec sp_help 'tablename'
```
|
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'
```
This solution returns several result sets within which is the information you desire, where as the former gives you exactly what you want.
Also just for completeness you can query the sys tables directly. This is not recommended as the schema can change between versions of SQL Server and INFORMATION\_SCHEMA is a layer of abstraction above these tables. But here it is anyway for SQL Server 2000
```
select [name] from dbo.syscolumns where id = object_id(N'[dbo].[myTable]')
```
|
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 example searching for two separate words will highlight both code fragments in the results.
However, it doesn't act well with more complicated queries. In the simplest case, phrase queries such as "Stack Overflow" will match all occurrences of Stack or Overflow in the highlighting, which gives the impression to the user that it isn't working very well.
I tried applying the fix [here](http://www.gossamer-threads.com/lists/lucene/java-user/15528) but that came with a lot of performance caveats, and at the end of the day was just plain unusable. The performance is especially an issue on wildcard queries. This is due to the way that the highlighting works; instead of just working on the querystring and the text it parses it as Lucene would and then looks for all the matches that Lucene has made; unfortunately this means that for certain wildcard queries it can be looking for matches to 2000+ clauses on large documents, and it's simply not fast enough.
Is there any faster implementation of an accurate highlighter?
|
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#action_12688408) to this question
|
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 decimalToHexString(number)
{
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}
return number.toString(16).toUpperCase();
}
console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));
```
|
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 xmlns="urn:nhibernate-mapping-2.2">
<class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true">
<id name="ID" column="ID" unsaved-value="0">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="NumberOfBuckets" column="NumberOfBuckets" />
<property name="SearchCriteriaOne" column="SearchCriteriaOne" />
<bag name="_Businesses" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Business, HQData"/>
</bag>
<bag name="_Buckets" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Bucket, HQData"/>
</bag>
</class>
</hibernate-mapping>
```
Has anyone run to this issue before?
Here is the full error message:
> ```
> MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id)
> in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory()
> in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e)
> in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
> ```
**Update**, here's what the solution for *my* scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime.
|
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 -->
</session-factory>
.
.
```
|
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 startup during NHibernate's configuration phase.
|
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 are at least two ways of doing it:
```
class T ;
class MethodA
{
public :
const T & get() const ;
T & get() ;
// etc.
} ;
class MethodB
{
public :
const T & getAsConst() const ;
T & get() ;
// etc.
} ;
```
What would be the pros and the cons of each method?
I am interested more by C++ technical/semantic reasons, but style reasons are welcome, too.
Note that `MethodB` has one major technical drawback (hint: in generic code).
|
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 puts an undue burden on the developer using the interface. Instead of just calling "get" and knowing he's getting what he needs, now he has to ascertain whether or not he's currently using a const variable, and if the new object he's grabbing needs to be const. And later, if both objects become non-const due to some refactoring, he's got to switch out his call.
|
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 guess this is a stylistic thing - technically they both works, but MethodA makes the compiler to work a bit harder. To me, it's a good thing.
|
"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 %&gt;` so I need to capture `<% or &lt;% and %> or %&gt;` respectively.
If I put in a second set of parens, it makes preg\_split function differently (because as you can see from the flag, I'm trying to capture what's inside the parens.
Preferably, it would only match `&lt; to &gt; and < to >` as well, but that's not completely necessary
EDIT: The SUBJECT may contain multiple matches, and I need all of them
|
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 tool to debug PHP regexp, it's so useful !
<http://regex.larsolavtorvik.com/>
EDIT : I hacked the regexp a bit so it's faster. Tested it, it works :-)
Now let's explain all that stuff :
* preg\_match will store everything he captures in the var passed as third param (here $out)
* if preg\_match matches something, it will be store in $out[0]
* anything that is inside () but not (?:) in the pattern will be stored in $out
The patten in details :
```
#((?:<|<)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|>))#i can be viewed as ((?:<|<)%) + ([\s]*(?:[^ø]*)[\s]*?) + (%(?:>|>)).
((?:<|<)%) is capturing < or < then %
(%(?:>|>)) is capturing % then < or >
([\s]*(?:[^ø]*)[\s]*?) means 0 or more spaces, then 0 or more times anything that is not the ø symbol, the 0 or more spaces.
```
Why do we use [^ø] instead of . ? It's because . is very time consuming, the regexp engine will check among all the existing characters. [^ø] just check if the char is not ø. Nobody uses ø, it's an international money symbol, but if you care, you can replace it by chr(7) wich is the shell bell char that's obviously will never be typed in a web page.
EDIT2 : I just read your edit about capturing all the matches. In that case, you´ll use preg\_match\_all the same way.
|
```
<?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 of the .NET 3.5 pieces are not there but definitely works for .NET 2.0 and earlier.
Monodevelop is coming along nicely and I believe the debugger is working well too.
|
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 powerful as Mobile Safari. I hear good things about [Opera Mini](http://www.operamini.com/) as well.
|
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 the classes that begin with "bg", how do I do that? Something like this, but that actually works:
```
$("#a").removeClass("bg*");
```
|
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(prefix) {
this.each(function(i, el) {
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = $.trim(classes.join(" "));
});
return this;
};
```
2018 ES6 Update:
```
const prefix = "prefix";
const classes = el.className.split(" ").filter(c => !c.startsWith(prefix));
el.className = classes.join(" ").trim();
```
|
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 process, rather than a top-level process with the console window we're familiar with.
Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.
|
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 class files built in your project.
In this example, the Eclipse project structure looks like this:
```
workspace\project\
\.classpath
\.project
\debug.bat
\bin\Main.class
\src\Main.java
```
**1. Start the JVM Console in Debug Mode**
**debug.bat** is a Windows batch file that should be run externally from a **cmd.exe** console.
```
@ECHO OFF
SET A_PORT=8787
SET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=y
java.exe %A_DBG% -cp .\bin Main
```
In the arguments, the debug port has been set to *8787*. The *suspend=y* argument tells the JVM to wait until the debugger attaches.
**2. Create a Debug Launch Configuration**
In Eclipse, open the Debug dialog (Run > Open Debug Dialog...) and create a new **Remote Java Application** configuration with the following settings:
* *Project:* your project name
* *Connection Type:* Standard (Socket Attach)
* *Host:* localhost
* *Port:* 8787
**3. Debugging**
So, all you have to do any time you want to debug the app is:
* set a break point
* launch the batch file in a console
* launch the debug configuration
---
You can track this issue in [bug 122429](https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429). You can work round this issue in your application by using an abstraction layer as described [here](http://illegalargumentexception.blogspot.com/2010/09/java-systemconsole-ides-and-testing.html).
|
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, etc.
|
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 [@broofa's answer](https://stackoverflow.com/a/2117523/109538), below) there are several common pitfalls:
* Invalid id format (UUIDs must be of the form "`xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`", where x is one of [0-9, a-f] *M* is one of [1-5], and *N* is [8, 9, a, or b]
* Use of a low-quality source of randomness (such as `Math.random`)
Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the [uuid](https://github.com/uuidjs/uuid) module.
|
*[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://blog.mozilla.org/security/2018/01/15/secure-contexts-everywhere/), this method is only available to pages served locally (`localhost` or `127.0.0.1`) or over HTTPS.
For readers interested in other UUID versions, generating UUIDs on legacy platforms or in non-secure contexts, there is [the `uuid` module](https://www.npmjs.com/package/uuid). It is well-tested and supported.
Failing the above, there is this method (based on the original answer to this question):
```
function uuidv4() {
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
(+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
);
}
console.log(uuidv4());
```
Note: **The use of *any* UUID generator that relies on `Math.random()` is strongly discouraged** (including snippets featured in previous versions of this answer) for [reasons best explained here](https://bocoup.com/blog/random-numbers). *TL;DR:* solutions based on `Math.random()` do not provide good uniqueness guarantees.
|
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();
inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
inputBox.ClientSize = size;
inputBox.Text = "Name";
System.Windows.Forms.TextBox textBox = new TextBox();
textBox.Size = new System.Drawing.Size(size.Width - 10, 23);
textBox.Location = new System.Drawing.Point(5, 5);
textBox.Text = input;
inputBox.Controls.Add(textBox);
Button okButton = new Button();
okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
okButton.Name = "okButton";
okButton.Size = new System.Drawing.Size(75, 23);
okButton.Text = "&OK";
okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39);
inputBox.Controls.Add(okButton);
Button cancelButton = new Button();
cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
cancelButton.Name = "cancelButton";
cancelButton.Size = new System.Drawing.Size(75, 23);
cancelButton.Text = "&Cancel";
cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39);
inputBox.Controls.Add(cancelButton);
inputBox.AcceptButton = okButton;
inputBox.CancelButton = cancelButton;
DialogResult result = inputBox.ShowDialog();
input = textBox.Text;
return result;
}
```
usage
```
string input="hede";
ShowInputDialog(ref input);
```
|
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 viewElement = new Element("div").update("text");
var editElement = new Element("input", {"type":"text"});
root.update(viewElement);
// pseudo shortcut for the sake of information:
viewElementOnClick = function(event) {
root.update(editElement);
editElement.focus();
}
```
The above example is a shortened version of the actual code, the actual code works fine except the focus bit in IE.
Are there limitations on the focus function in IE? Do I need to place the input in a form?
|
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 would be to have both items present in the DOM at all times and just swap the style.display on them depending on what you need hidden/shown at a given time.
|
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 application, but at the same level. (users will checkout both folders from SVN, no installation available for the xul app)
It opened the files just fine if I set a full path like "file:///c:\temp\processing-sample\index.html"
what i want to do is to open the file relative to my xul application.
I found i can open the user's profile path:
```
var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties");
var path = (new DIR_SERVICE()).get("UChrm", Components.interfaces.nsIFile).path;
var appletPath;
// find directory separator type
if (path.search(/\\/) != -1)
{
appletPath = path + "\\myApp\\content\\applet.html"
}
else
{
appletPath = path + "/myApp/content/applet.html"
}
// Cargar el applet en el iframe
var appletFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
appletFile.initWithPath(appletPath);
var appletURL = Components.classes["@mozilla.org/network/protocol;1?name=file"].createInstance(Components.interfaces.nsIFileProtocolHandler).getURLSpecFromFile(appletFile);
var appletFrame = document.getElementById("appletFrame");
appletFrame.setAttribute("src", appletURL);
```
**is there any way to find the current directory full path of a xul application?**
|
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 path = (new DIR_SERVICE()).get(resource:app, Components.interfaces.nsIFile).path;
var appletPath;
```
|
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 anything else either :/
|
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 the regular ephemeral binding behavior doesn't suit your needs, you'll probably have to write your own using Socket.bind().
|
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 == NaN); // false
console.log(isNaN("text")); // true
console.log(NaN == "text"); // false
```
So, the problem seems not to be an exact comparison with NaN?
***Edit:** Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don't blame their authors. Among the things I changed was:*
* Removed a note saying that I had screwed up the headline in the first place by reverting its meaning
* Earlier answers showed that I didn't state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison.
|
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) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations.
In most cases we think the answer to "is null numeric?" should be no. However, `isNaN(null) == false` is semantically correct, because `null` is not `NaN`.
Here's the algorithmic explanation:
The function `isNaN(x)` attempts to convert the passed parameter to a number[1](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN) (equivalent to `Number(x)`) and then tests if the value is `NaN`. If the parameter can't be converted to a number, `Number(x)` will return `NaN`[2](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number). Therefore, if the conversion of parameter `x` to a number results in `NaN`, it returns true; otherwise, it returns false.
So in the specific case `x = null`, `null` is converted to the number 0, (try evaluating `Number(null)` and see that it returns 0,) and `isNaN(0)` returns false. A string that is only digits can be converted to a number and isNaN also returns false. A string (e.g. `'abcd'`) that cannot be converted to a number will cause `isNaN('abcd')` to return true, specifically because `Number('abcd')` returns `NaN`.
In addition to these apparent edge cases are the standard numerical reasons for returning NaN like 0/0.
As for the seemingly inconsistent tests for equality shown in the question, the behavior of `NaN` is specified such that any comparison `x == NaN` is false, regardless of the other operand, including `NaN` itself[1](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN).
|
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, true, true, true, false, false, false, true, true, false]
```
( I aligned the result according to the input, hope it makes it easier to read. )
This seems better to me.
|
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 TRIGGER [dandb_raw_searchNames]
ON [dandb_raw]
FOR INSERT, UPDATE
AS
SET NOCOUNT ON
select dunsId, name into #magic from inserted
UPDATE dandb
SET dandb.searchName = company_generateSearchName(dandb.name)
FROM (select dunsId, name from #magic) i
INNER JOIN dandb_raw dandb
on i.dunsId = dandb.dunsId
--Add new search matches
SELECT c.companyId, dandb.dunsId
INTO #newMatches
FROM dandb_raw dandb
INNER JOIN (select dunsId, name from #magic) a
on a.dunsId = dandb.dunsId
INNER JOIN companies c
ON dandb.searchName = c.searchBrand
--avoid url matches that are potentially wrong
AND (lower(dandb.url) = lower(c.url)
OR dandb.url = ''
OR c.url = ''
OR c.url is null)
INSERT INTO #newMatches (companyId, dunsId)
SELECT c.companyId, max(dandb.dunsId) dunsId
FROM dandb_raw dandb
INNER JOIN
(
select
case when charindex('/',url) <> 0 then left(url, charindex('/',url)-1)
else url
end urlMatch, * from companies
) c
ON dandb.url = c.urlMatch
where subsidiaryOf = 1 and isReported = 1 and dandb.url <> ''
and c.companyId not in (select companyId from #newMatches)
group by companyId
having count(dandb.dunsId) = 1
UPDATE cd
SET cd.dunsId = nm.dunsId
FROM companies_dandb cd
INNER JOIN #newMatches nm
ON cd.companyId = nm.companyId
GO
```
The trigger causes inserts to fail:
```
insert into [dandb_raw](dunsId, name)
select 3442355, 'harper'
union all
select 34425355, 'har 466per'
update [dandb_raw] set name ='grap6767e'
```
With this error:
```
Msg 213, Level 16, State 1, Procedure companies_contactInfo_updateTerritories, Line 20
Insert Error: Column name or number of supplied values does not match table definition.
```
The most curious thing about this is that each of the individual statements in the trigger works on its own. It's almost as though inserted is a one-off table that infects temporary tables if you try to move inserted into one of them.
So what causes the trigger to fail? How can it be stopped?
|
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 to, find the table already existed with a different schema, die, and produce the message above. One piece of evidence that would be in favor: Does inserted use a stack style scope (nested triggers have their own inserteds?)
Still speculating though - at least things seem to be working now!
|
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 everything and it worked but now it doesn't work, then something must be different. One thing to consider is security. I noticed that you just call the table [dandb\_raw] and not [dbo].[dandb\_raw]. So if the user had a table of the same name [user].[dandb\_raw], that table would be used to check the definitions instead of your table. Also, the trigger creates temp tables. But if some of the temp tables already existed for whatever reason but with different definitions, this may also be a problem.
|
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 write back to disk using streams.
I know some people prefer base 64 strings instead of the byte[]. not sure if it matters.
|
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) IMyObject* CreateMyObject(void)
{
//this class references c# in the constructor
return new CMyWrapper( );
}
extern "C" __declspec(dllexport) void DeleteMyObject(IMyObject* pConfigFile)
{
delete pConfigFile;
}
extern "C" __declspec(dllexport) void TestFunction(void)
{
::MessageBox(NULL, _T("My Message Box"), _T("Test"), MB_OK);
}
```
Test Code (this is an EXE):
```
typedef void* (*CreateObjectPtr)();
typedef void (*TestFunctionPtr)();
int _tmain testwrapper(int argc, TCHAR* argv[], TCHAR* envp[])
{
HMODULE hModule = ::LoadLibrary(_T("MyWrapper"));
_ASSERT(hModule != NULL);
PVOID pFunc1 = ::GetProcAddress(hModule, "TestFunction");
_ASSERT(pFunc1 != NULL);
TestFunctionPtr pTest = (TestFunctionPtr)pFunc1;
PVOID pFunc2 = ::GetProcAddress(hModule, "CreateMyObject");
_ASSERT(pFunc2 != NULL);
CreateObjectPtr pCreateObjectFunc = (CreateObjectPtr)pFunc2;
(*pTest)(); //this successfully pops up a message box
(*pCreateObjectFunc)(); //this tosses an EEFileLoadException
return 0;
}
```
For what it's worth, the Event Log reports the following:
.NET Runtime version 2.0.50727.143 -
Fatal Execution Engine Error (79F97075) (80131506)
Unfortunately, Microsoft has no information on that error.
|
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. (or in the GAC).
For reasons not worth going into, this is the structure I need, which meant that I needed to give the CLR a hand in located the managed dll. See code below:
AssemblyResolver.h:
```
/// <summary>
/// Summary for AssemblyResolver
/// </summary>
public ref class AssemblyResolver
{
public:
static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
{
Console::WriteLine( "Resolving..." );
Assembly^ thisAssembly = Assembly::GetExecutingAssembly();
String^ thisPath = thisAssembly->Location;
String^ directory = Path::GetDirectoryName(thisPath);
String^ pathToManagedAssembly = Path::Combine(directory, "managed.dll");
Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly);
return newAssembly;
}
};
```
Wrapper.cpp:
```
#include "AssemblyResolver.h"
extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
try
{
AppDomain^ currentDomain = AppDomain::CurrentDomain;
currentDomain->AssemblyResolve += gcnew ResolveEventHandler( AssemblyResolver::MyResolveEventHandler );
return new CMyWrapper( );
}
catch(System::Exception^ e)
{
System::Console::WriteLine(e->Message);
return NULL;
}
}
```
|
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://msdn.microsoft.com/en-us/library/bb250448.aspx>
|
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 application based on the arguments passed.
|
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.
However, note that many "hybrid" apps actually ship two different executables (look at visual studio- devenv.exe is the gui, devenv.com is the console). Using a "hybrid" approach can sometimes lead to hard to track down issues.
|
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 `RuntimeException` somewhere down the road.
TestClass.java:
```
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface Author { String name(); }
@Author( name = "foo" )
public abstract class TestClass
{
public static String getInfo( Class<? extends TestClass> c )
{
return c.getAnnotation( Author.class ).name();
}
public static void main( String[] args )
{
System.out.println( "The test class was written by "
+ getInfo( TestClass.class ) );
System.out.println( "The test subclass was written by "
+ getInfo( TestSubClass.class ) );
}
}
```
TestSubClass.java:
```
@Author( name = "bar" )
public abstract class TestSubClass extends TestClass {}
```
I know I can enumerate all annotations at runtime and check for the missing `@Author`, but I'd really like to do this at compile time, if possible.
|
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/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html>
|
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 implement a custom rule in a static analyzer. There are many options here, too.
(I put unit in scare-quotes, since this is really a test of conventions, rather than of a specific unit. But it should run together with your unit-tests).
|
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 public default constructor we can create an object in this way.
```
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
```
**C**. Using `clone()`
The clone() can be used to create a copy of an existing object.
```
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();
```
**D**. Using `object deserialization`
Object deserialization is nothing but creating an object from its serialized form.
```
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
```
You can read them from [here](http://javabeanz.wordpress.com/2007/09/13/different-ways-to-create-objects/).
|
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 other method that calls a `new` for you.
* I guess you could describe class loading as creating new objects (such as interned `String`s).
* A literal array as part of the initialisation in a declaration (no constructor for arrays).
* The array in a "varargs" (`...`) method call (no constructor for arrays).
* Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).
* Causing an exception to be created and thrown by the runtime. For instance `throw null;` or `"".toCharArray()[0]`.
* Oh, and boxing of primitives (unless cached), of course.
* JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
* For completeness (and Paŭlo Ebermann), there's some syntax with the `new` keyword as well.
|
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 or have been involved in a project which uses continuous integration. Which software do/did you use and do you think it has payed off? Which software would you recommend for continuous integration of a Java web project?
|
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 to setup:
3 Build Agents at no additional cost
20 User Accounts
20 Build Configurations
|
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, ARRAYSIZE would be a better name but this is legacy code (no idea where it came from, it's at least 15 years old) so I pasted it 'as is'.
|
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_t array_size(const T (&array)[SIZE])
{
return SIZE;
}
```
The above is similar to [xtofl's](https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#95664), except it guards against passing a pointer to it (that says point to a dynamically allocated array) and getting the wrong answer by mistake.
**EDIT**: Simplified as per [JohnMcG](https://stackoverflow.com/users/1674/johnmcg).
**EDIT**: inline.
Unfortunately, the above does not provide a compile time answer (even if the compiler does inline & optimize it to be a constant under the hood), so cannot be used as a compile time constant expression. i.e. It cannot be used as size to declare a static array. Under C++0x, this problem go away if one replaces the keyword *inline* by *constexpr* (constexpr is inline implicitly).
```
constexpr size_t array_size(const T (&array)[SIZE])
```
[jwfearn's](https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#97523) solution work for compile time, but involve having a typedef which effectively "saved" the array size in the declaration of a new name. The array size is then worked out by initialising a constant via that new name. In such case, one may as well simply save the array size into a constant from the start.
[Martin York's](https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#98059) posted solution also work under compile time, but involve using the non-standard *typeof()* operator. The work around to that is either wait for C++0x and use *decltype* (by which time one wouldn't actually need it for this problem as we'll have *constexpr*). Another alternative is to use Boost.Typeof, in which case we'll end up with
```
#include <boost/typeof/typeof.hpp>
template<typename T>
struct ArraySize
{
private: static T x;
public: enum { size = sizeof(T)/sizeof(*x)};
};
template<typename T>
struct ArraySize<T*> {};
```
and is used by writing
```
ArraySize<BOOST_TYPEOF(foo)>::size
```
where *foo* is the name of an array.
|
[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.com/users/1343/bcs) was on the right track but that solution is incorrect.
Here's my solution:
```
// asize.hpp
template < typename T >
struct asize; // no implementation for all types...
template < typename T, size_t N >
struct asize< T[N] > { // ...except arrays
static const size_t val = N;
};
template< size_t N >
struct count_type { char val[N]; };
template< typename T, size_t N >
count_type< N > count( const T (&)[N] ) {}
#define ASIZE( a ) ( sizeof( count( a ).val ) )
#define ASIZET( A ) ( asize< A >::val )
```
with test code (using [Boost.StaticAssert](http://www.boost.org/doc/libs/1_36_0/doc/html/boost_staticassert.html) to demonstrate compile-time-only usage):
```
// asize_test.cpp
#include <boost/static_assert.hpp>
#include "asize.hpp"
#define OLD_ASIZE( a ) ( sizeof( a ) / sizeof( *a ) )
typedef char C;
typedef struct { int i; double d; } S;
typedef C A[42];
typedef S B[42];
typedef C * PA;
typedef S * PB;
int main() {
A a; B b; PA pa; PB pb;
BOOST_STATIC_ASSERT( ASIZET( A ) == 42 );
BOOST_STATIC_ASSERT( ASIZET( B ) == 42 );
BOOST_STATIC_ASSERT( ASIZET( A ) == OLD_ASIZE( a ) );
BOOST_STATIC_ASSERT( ASIZET( B ) == OLD_ASIZE( b ) );
BOOST_STATIC_ASSERT( ASIZE( a ) == OLD_ASIZE( a ) );
BOOST_STATIC_ASSERT( ASIZE( b ) == OLD_ASIZE( b ) );
BOOST_STATIC_ASSERT( OLD_ASIZE( pa ) != 42 ); // logic error: pointer accepted
BOOST_STATIC_ASSERT( OLD_ASIZE( pb ) != 42 ); // logic error: pointer accepted
// BOOST_STATIC_ASSERT( ASIZE( pa ) != 42 ); // compile error: pointer rejected
// BOOST_STATIC_ASSERT( ASIZE( pb ) != 42 ); // compile error: pointer rejected
return 0;
}
```
This solution rejects non-array types at compile time so it will not get confused by pointers as the macro version does.
|
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 do so if my layers are in separate projects and only the public interfaces have try/catch in them?
Why? Why not? Is there a different approach I could use?
|
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; obviously if you are trapping for a specific error you would check for it there)
2. Only log in the UI layer right before suppressing the error and redirecting to an error page/form.
|
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 sense to do something like the following?
```
def main():
# TODO: main application entry point
pass
def cleanup():
# TODO: release system resources here
pass
if __name__ == "__main__":
try:
main()
except:
cleanup()
raise
```
Is this something that is typically done? Is there a better way? Perhaps the destructor in a singleton class?
|
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-level handlers will catch those bizarre exceptions you didn't plan on and let you correct them in the future, otherwise, you may never know about them at all.
Just be careful that your top-level handler doesn't throw exceptions!
|
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 machine reboots. (Of course, the last item isn't an issue in your case.) If your process is crash-prone (it uses fickle third-party extension modules, for instance) you may want to do the cleanup in a simple parent process for more isolation.
If you aren't really worried, use the atexit module.
|
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."
```
Any ideas? My understanding was that this style of property was valid as of .NET 3.0.
Thanks!
---
The problem turned out to be in my .sln file itself. Although I was changing the target version in my build options, in the .sln file, I found this:
```
TargetFramework = "3.0"
```
Changing that to "3.5" solved it. Thanks, guys!
|
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" />
<providerOption name="WarnAsError" value="false" />
</compiler>
</compilers>
</system.codedom>
```
|
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 notice that throughout Stack Overflow, it doesn't seem to rate a mention when [symfony](http://www.symfony-project.org/) or [CakePHP](http://cakephp.org/) are being talked about as potential candidates for a framework.
Is anybody using Stack Overflow using PRADO now? If so, how do you find it? Has anyone used it in the past but left it behind, and if so, why? Can anybody appraise its strengths and weaknesses against Cake or symfony?
|
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 perfect and development was fast. But as soon as the customer wanted an out-of-the-box thing, we literaly spent 2 to 3 times the amount of time we would have done it with another framework. And I'm not talking about big customizations. The PRADO framework forces the application to have a particular structure and workflow. If that logic is not working for you, then check out another framework.
|
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 get IE to run an onclick on a dynamically generated element, we can't use setAttribute. Instead, we need to set the onclick property on the object with an anonymous function wrapping the code we want to run.
```
execBtn.onclick = function() { runCommand() };
```
**BAD IDEAS:**
You can do
```
execBtn.setAttribute("onclick", function() { runCommand() });
```
but it will break in IE in non-standards mode according to @scunliffe.
You can't do this at all
```
execBtn.setAttribute("onclick", runCommand() );
```
because it executes immediately, and sets the result of runCommand() to be the onClick attribute value, nor can you do
```
execBtn.setAttribute("onclick", runCommand);
```
|
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).
**UPDATE**:
This is to demonstrate that sometimes it *is* necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:
```
// get old onclick attribute
var onclick = button_element.getAttribute("onclick");
// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") {
button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome
// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
button_element.onclick = function() {
doSomething();
onclick();
}; // for IE7
}
```
|
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.getElementById(ID).type='password';
* Has anyone checked the "AddEventListener" approach with different engines?
|
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 AWTExceptionHandler {
public void handle(Throwable t) {
try {
// insert your exception handling code here
// or do nothing to make it go away
} catch (Throwable t) {
// don't let the exception get thrown out, will cause infinite looping!
}
}
public static void registerExceptionHandler() {
System.setProperty('sun.awt.exception.handler', AWTExceptionHandler.class.getName())
}
}
```
|
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.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
// EDT Exception
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
// We are in the event dispatching thread
Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());
}
});
```
|
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 the rows from the CSV file with the command:
```
select * from Data.csv
```
When I open an OleDbDataReader and examine the data types of the columns it returns, I find that something in the stack has tried to guess at the data types based on the first row of data in the file. For example, suppose the CSV file contains:
```
House,Street,Town
123,Fake Street,Springfield
12a,Evergreen Terrace,Springfield
```
Calling the OleDbDataReader.GetDataTypeName method for the House column will reveal that the column has been given the data type "DBTYPE\_I4", so all values read from it are interpreted as integers. My problem is that House should be a string - when I try to read the House value from the second row, the OleDbDataReader returns null.
How can I tell either the Jet database provider or the OleDbDataReader to interpret a column as strings instead of numbers?
|
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)
Or the most recent [MS Documentation](https://learn.microsoft.com/en-us/sql/odbc/microsoft/schema-ini-file-text-file-driver?view=sql-server-2017)
|
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 question work, the Schema file should look like this:
```
[Data.csv]
ColNameHeader=True
Col1=House Text
Col2=Street Text
Col3=Town Text
```
I could also try this to make the data provider examine all the rows in the file before it tries to guess the data types:
```
[Data.csv]
ColNameHeader=true
MaxScanRows=0
```
In real life, my application imports data from files with dynamic names, so I have to create a Schema.ini file on the fly and write it to the same directory as the CSV file before I open my connection.
Further details can be found here - <http://msdn.microsoft.com/en-us/library/ms709353(VS.85).aspx> - or by searching the MSDN Library for "Schema.ini file".
|
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 types, and as
> local variables) floating-point
> numbers are represented using an
> internal floating-point type. In each
> such instance, the nominal type of the
> variable or expression is either R4 or
> R8, but its value can be represented
> internally with additional range
> and/or precision. The size of the
> internal floating-point representation
> is implementation-dependent, can vary,
> and shall have precision at least as
> great as that of the variable or
> expression being represented. An
> implicit widening conversion to the
> internal representation from float32
> or float64 is performed when those
> types are loaded from storage. The
> internal representation is typically
> the native size for the hardware, or
> as required for efficient
> implementation of an operation.
What this basically means is that the following comparison may or may not be equal:
```
class Foo
{
double _v = ...;
void Bar()
{
double v = _v;
if( v == _v )
{
// Code may or may not execute here.
// _v is 64-bit.
// v could be either 64-bit (debug) or 80-bit (release) or something else (future?).
}
}
}
```
Take-home message: never check floating values for equality.
|
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 2005 and .Net 2. I compiled as both debug and release and examined the output of the compiler:
```
Release Debug
static void Main (string [] args) static void Main (string [] args)
{ {
00000000 push ebp
00000001 mov ebp,esp
00000003 push edi
00000004 push esi
00000005 push ebx
00000006 sub esp,3Ch
00000009 xor eax,eax
0000000b mov dword ptr [ebp-10h],eax
0000000e xor eax,eax
00000010 mov dword ptr [ebp-1Ch],eax
00000013 mov dword ptr [ebp-3Ch],ecx
00000016 cmp dword ptr ds:[00A2853Ch],0
0000001d je 00000024
0000001f call 793B716F
00000024 fldz
00000026 fstp dword ptr [ebp-40h]
00000029 fldz
0000002b fstp dword ptr [ebp-44h]
0000002e xor esi,esi
00000030 nop
float float
a = float.MaxValue / 3.0f, a = float.MaxValue / 3.0f,
00000000 sub esp,0Ch 00000031 mov dword ptr [ebp-40h],7EAAAAAAh
00000003 mov dword ptr [esp],ecx
00000006 cmp dword ptr ds:[00A2853Ch],0
0000000d je 00000014
0000000f call 793B716F
00000014 fldz
00000016 fstp dword ptr [esp+4]
0000001a fldz
0000001c fstp dword ptr [esp+8]
00000020 mov dword ptr [esp+4],7EAAAAAAh
b = a * a; b = a * a;
00000028 fld dword ptr [esp+4] 00000038 fld dword ptr [ebp-40h]
0000002c fmul st,st(0) 0000003b fmul st,st(0)
0000002e fstp dword ptr [esp+8] 0000003d fstp dword ptr [ebp-44h]
if (a * a < b) if (a * a < b)
00000032 fld dword ptr [esp+4] 00000040 fld dword ptr [ebp-40h]
00000036 fmul st,st(0) 00000043 fmul st,st(0)
00000038 fld dword ptr [esp+8] 00000045 fld dword ptr [ebp-44h]
0000003c fcomip st,st(1) 00000048 fcomip st,st(1)
0000003e fstp st(0) 0000004a fstp st(0)
00000040 jp 00000054 0000004c jp 00000052
00000042 jbe 00000054 0000004e ja 00000056
00000050 jmp 00000052
00000052 xor eax,eax
00000054 jmp 0000005B
00000056 mov eax,1
0000005b test eax,eax
0000005d sete al
00000060 movzx eax,al
00000063 mov esi,eax
00000065 test esi,esi
00000067 jne 0000007A
{ {
Console.WriteLine ("Less"); 00000069 nop
00000044 mov ecx,dword ptr ds:[0239307Ch] Console.WriteLine ("Less");
0000004a call 78678B7C 0000006a mov ecx,dword ptr ds:[0239307Ch]
0000004f nop 00000070 call 78678B7C
00000050 add esp,0Ch 00000075 nop
00000053 ret }
} 00000076 nop
else 00000077 nop
{ 00000078 jmp 00000088
Console.WriteLine ("GreaterEqual"); else
00000054 mov ecx,dword ptr ds:[02393080h] {
0000005a call 78678B7C 0000007a nop
} Console.WriteLine ("GreaterEqual");
} 0000007b mov ecx,dword ptr ds:[02393080h]
00000081 call 78678B7C
00000086 nop
}
```
What the above shows is that the floating point code is the same for both debug and release, the compiler is choosing consistency over optimisation. Although the program produces the wrong result (a \* a is not less than b) it is the same regardless of the debug/release mode.
Now, the Intel IA32 FPU has eight floating point registers, you would think that the compiler would use the registers to store values when optimising rather than writing to memory, thus improving the performance, something along the lines of:
```
fld dword ptr [a] ; precomputed value stored in ram == float.MaxValue / 3.0f
fmul st,st(0) ; b = a * a
; no store to ram, keep b in FPU
fld dword ptr [a]
fmul st,st(0)
fcomi st,st(0) ; a*a compared to b
```
but this would execute differently to the debug version (in this case, display the correct result). However, changing the behaviour of the program depending on the build options is a very bad thing.
FPU code is one area where hand crafting the code can significantly out-perform the compiler, but you do need to get your head around the way the FPU works.
|
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 and will email clients run the any script injected into the email?
|
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 there a methodology I can use in C# that has the same ends?
I'm aware of immutability, but that doesn't really carry over to container objects to name but one example.
|
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:
```
public interface IReadOnlyCustomer
{
String Name { get; }
int Age { get; }
}
public class Customer : IReadOnlyCustomer
{
private string m_name;
private int m_age;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public int Age
{
get { return m_age; }
set { m_age = value; }
}
}
```
|
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 easily in multi-tasking environments.
|
"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();
}
}
class B
{
public void DoSomething()
{
SomeOtherClass.ExecuteMethod();
}
}
public class SomeOtherClass
{
public static void ExecuteMethod()
{
// Returns an instance of A if called from class A
// or an instance of B if called from class B.
object caller = getCallingInstance();
}
}
```
I can get the type using [System.Diagnostics.StackTrace.GetFrames](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframes.aspx), but is there a way to get a reference to the actual instance?
I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason of this question is I was curious if it was doable; we are currently passing the instance in.
```
ExecuteMethod(instance)
```
And I just wondered if this was possible and still being able to access the instance.
```
ExecuteMethod()
```
---
@Steve Cooper:
I hadn't considered extension methods. Some variation of that might work.
|
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 before calling ExecuteMethod that you can retrieve within it or just pass the instance.
|
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, you watch out for static methods, which won't have one, and anonymous methods, which will have instances of auto-generated classes, which will be a little odd.
I do wonder whether you should just pass the invoking object in as a proper parameter. After all, a `static` is a hint that this method doesn't depend on anything other than its input parameters. Also note that this method may be a bitch to test, as any test code you write will not have the same invoking object as the running system.
|
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();
}
```
Using the [typeof](http://www.javascriptkit.com/javatutors/determinevar2.shtml) function is also an option as it returns the type of the object provided. However, it will return [null or undefined](http://www.javascriptkit.com/javatutors/determinevar2.shtml) if the object has not been loaded so it might boil down a bit to personal preference in regards to readability.
|
```
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 into memory I run out of memory.
Any ideas that don't involve running the query in the jsp?
|
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 Hibernate pagination I've seen...
|
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.PaginatedList` interface. There is a [tutorial](http://displaytag.sourceforge.net/11/tut_externalSortAndPage.html) on the Display Tag web site. There isn't very much to the tutorial but then again implementing the interface is pretty easy.
|
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 item given a Batch Reference. So if I do a
```
Select * from HistoryTable where BatchRef = @BatchRef
```
It will return all the steps for all the items in the batch - eg
```
Id Status BatchRef ItemCount
1 1 Batch001 100
1 2 Batch001 110
2 1 Batch001 60
2 2 Batch001 100
```
But what I really want is:
```
Id Status BatchRef ItemCount
1 2 Batch001 110
2 2 Batch001 100
```
Edit: Appologies - can't seem to get the TABLE tags to work with Markdown - followed the help to the letter, and looks fine in the preview
|
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 be your unique column.
Then, join back to the table to get all columns. Something like:
```
SELECT *
FROM HistoryTable
JOIN (
SELECT
MAX(Id) as Id.
BatchRef,
ItemCount
FROM HsitoryTable
WHERE
BacthRef = @batchRef
GROUP BY
BatchRef,
ItemCount
) as Latest ON
HistoryTable.Id = Latest.Id
```
|
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 value of a source on a person. It increments `Source.Person_Count`. Cool.
But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried `updateCacheControl()` in `afterSave`, but that didn't do anything.
So then I wrote some code in my model for `afterSave` that would subtract the source source\_id, but it always did this even when I wasn't even changing the `source_id`. (So the count went negative).
My question: Is there a way to tell if a field was changed in the model in `CakePHP`?
|
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->alias] as $key =>$value) {
if ($this->old[$this->alias][$key] != $value) {
$changed_fields[] = $key;
}
}
}
// $changed_fields is an array of fields that changed
return true;
}
```
|
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 it attemps to load the whole 1MB in memory before doing any treatment to the image (in this case, simply determining its size and type).
Are there any solutions to speed up this process of determining which file type and which dimensions an arbitrary image file has? I can live with it only supporting JPEG and PNG. It's important to me that the file type is determined by looking at the file's headers and not simply the extension.
**Edit: The solution can be a command-line tool UNIX called by PHP, much like the way I'm using ImageMagick at the moment**
|
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 method. I only tested on jpg and not on png.
the test is just
```
$files = array('2819547919_db7466149b_o_d.jpg', 'GP1-green2.jpg', 'aegeri-lake-switzerland.JPG');
foreach($files as $file){
$size2 = array();
$size3 = array();
$time1 = microtime();
$size = getimagesize($file);
$time1 = microtime() - $time1;
print "$time1 \n";
$time2 = microtime();
exec("identify -ping $file", $size2);
$time2 = microtime() - $time2;
print $time2/$time1 . "\n";
$time2 = microtime();
exec("identify $file", $size3);
$time2 = microtime() - $time2;
print $time2/$time1 . "\n";
print_r($size);
print_r($size2);
print_r($size3);
}
```
|
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 properties where I have looked for an attribute, but never a private member field.
What are the binding flags that I need to set to get the private fields?
|
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. I am completely comfortable with compiling it from source with one caveat. How do I match the way that the default install is laid out? Especially, with regards to site-packages being in `/Library/Python/2.5/` and not the one in buried at the top of the framework once I compile it.
|
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 second python installation, but that also causes more problems than it's worth IMO.
So I suppose the best question to start out with would be why exactly do you want to use the 64 bit version of python?
|
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 its software separately. By default, for example, everything is installed in /opt/local
Another method is to simply download the source and compile with a specified prefix. Note that this method doesn't modify your PATH environment variable, so you'll need to do that yourself if you want to avoid typing the fully qualified path to the python executable each time
```
./configure --prefix=/usr/local/python64
make
sudo make install
```
Then you can simply point your Apache install at the new version using mod\_python's [PythonInterpreter](http://www.modpython.org/live/current/doc-html/dir-other-pi.html) directive
|
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 ability turned on, BUT the gridview chooses to ALPHA sort rather than sorting numerically because I add in those commas.
So I need help. Anyone willing to give this one a shot? I need to change some of my columns in the gridview to numerical sort rather than the alpha sort it is using.
|
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 a pretty good implementation in C# here:
<http://www.codeproject.com/KB/string/NaturalSortComparer.aspx>
|
.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 have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while.
Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate?
Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing.
One more thing: maybe some of you will ask "Why settle on one language?". To answer this: I would like to choose only one language, in order to try to master it.
|
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/ruby-lorcon/) bindings for raw 802.11 work.
* Metasploit's KARMA bindings for 802.11 clientside redirection.
* [Libcurl](http://curl.haxx.se/libcurl/ruby/) and net/http for web tool writing.
* [EventMachine](http://rubyforge.org/projects/eventmachine) for web proxy and fuzzing work (or RFuzz, which extends the well-known Mongrel webserver).
* [Metasm](http://metasm.cr0.org/) for shellcode generation.
* [Distorm](http://www.ragestorm.net/distorm/) for x86 disassembly.
* [BinData](http://blogfranz.blogspot.com/2008/01/bindata-for-ruby-fuzzers.html) for binary file format fuzzing.
Second place here goes to Python. There are more pentesting libraries available in Python than in Ruby (but not enough to offset Metasploit). Commercial tools tend to support Python as well --- if you're an Immunity CANVAS or CORE Impact customer, you want Python. Python gives you:
* [Twisted](http://twistedmatrix.com/trac/) for network access.
* [PaiMei](http://www.openrce.org/downloads/details/208/PaiMei) for program tracing and programmable debugging.
* CANVAS and Impact support.
* [Dornseif's](http://www.matasano.com/log/695/windows-remote-memory-access-though-firewire/) firewire libraries for remote debugging.
* [Ready integration with WinDbg](http://pydbgeng.sourceforge.net/) for remote Windows kernel debugging (there's still no good answer in Ruby for kernel debugging, which is why I still occasionally use Python).
* [Peach Fuzzer](http://peachfuzzer.com/) and Sully for fuzzing.
* SpikeProxy for web penetration testing (also, [OWASP Pantera](http://www.owasp.org/index.php/Category:OWASP_Pantera_Web_Assessment_Studio_Project)).
Unsurprisingly, a lot of web work uses Java tools. The de facto standard web pentest tool is Burp Suite, which is a Java swing app. Both Ruby and Python have Java variants you can use to get access to tools like that. Also, both Ruby and Python offer:
* Direct integration with libpcap for raw packet work.
* OpenSSL bindings for crypto.
* IDA Pro extensions.
* Mature (or at least reasonable) C foreign function interfaces for API access.
* WxWindows for UI work, and decent web stacks for web UIs.
You're not going to go wrong with either language, though for mainstream pentest work, Metasploit probably edges out all the Python benefits, and at present, for x86 reversing work, Python's superior debugging interfaces edge out all the Ruby benefits.
Also: it's 2008. They're not "scripting languages". They're programming languages. ;)
|
[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 a mainly-OO background (particularly the Java school of OOP). For that reason, though, it’s incredibly widely installed on machines with any kind of Unixoid OS, and many vendor system utilities are written in it. Also for the same reason, servers that have neither Python nor Ruby installed are still likely to have Perl on them, again making it important to have some familiarity with. So if your CEH activity includes extensive activity on Unix, you will have to have some amount of familiarity with Perl anyway, and you might as well focus on it.
That said, it is largely a matter of preference. There is not much to differentiate the languages; their expressive power is virtually identical. Some things are a little easier in one of the languages, some a little easier in another.
In terms of libraries I do not know how Ruby and Python compare against each other – I do know that Perl has them beat by a margin. Then again, sometimes (particularly when you’re looking for libraries for common needs) the only effect of that is that you get deluged with choices. And if you are only looking to do things in some particular area which is well covered by libraries for Python or Ruby, the mass of *other* stuff on CPAN isn’t necessarily an advantage. In niche areas, however, it matters, and you never know what unforeseen need you will eventually have (err, by definition).
For one-liner use on the command line, Python is kind of a non-starter.
In terms of interactive interpreter environment, Perl… uhm… well, you can use the debugger, which is not that great, or you can install one from CPAN, but Perl doesn’t ship a good one itself.
So I think Perl does have a very slight edge for your needs in particular, but only just. If you pick Ruby you’ll probably not be much worse off at all. Python might inconvenience you a little more noticeably, but it too is hardly a *bad* choice.
|
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, 97, 50,
^
```
The code line in question is:
```
public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50,
0, 50, 0, -9, 0, 0, -1, -1, -1, -24, -72, -72, -24, -64, -64,
-8, -16, -24, -8, -24, -24, -16, -24, -32, -1, -8, -8, 48, 72,
-72, -24, -80, -80, 72, 96, -40, -24, -24, -8, 56, 88, -56,
-24, -40, -48, -24, -48, -64, 56, 80, -64, 64, 88, -48, -56,
-64, -64, -16, -24, -24, -32, -40, -40, -32, -88, -96, -72,
-72, -72, -48, -56, -56, -24, -32, -32, -8, -8, -1, -24, -40,
-56, -64, -72, -72, -16, -32, -40, 48, 80, -72, -40, -96, -104,
-40, -96, -96, -56, -104, -104, 120, 88, -104, -40, -64, -80,
-32, -88, -88, -32, -56, -72, -72, -80, -80, -32, -80, -88,
104, -96, -1, -40, -40, -40, -64, -104, -104, -32, -56, -64,
-112, 104, 112, -48, -104, -112, -128, -112, -24, -72, -80,
-88, -8, -8, -8, -64, -112, -120, 72, 104, -40, 120, 96, -96,
-112, -96, -24, -112, -120, -72, -40, -88, -88, -48, -64, -72,
-32, -72, -80, -48, -72, -88, -88, -72, -24, 64, 88, -56, -120,
96, 104, 88, -128, -72, 48, 56, 56, 104, 104, 120, 112, -120,
-16, -128, 104, -88, -40, -48, -48, 88, -120, -24, 104, 88,
-104, -40, -56, -72, -128, 112, -88, -128, 96, -88, -104, -88,
-24, -96, -120, 120, -88, -128, -80, -56, -56, -64, 96, 120,
-8, -96, -128, -88, -80, -96, -104, -32, -72, -72, 96, 104,
112, 96, -104, -8, -72, -112, -112, -64, -72, -80, 64, 64, 72,
-128, -120, -96, -128, 88, 88, -56, -72, -80, 88, 96, 120, -72,
-128, 112, 72, 112, -40, 96, 120, -56, 88, -112, -16, 64, 104,
-48, -64, -80, -88, -88, -120, -80, 88, 88, 96, -56, -96, -120,
-40, -56, -64, 96, 104, 120, -120, -80, -24, -104, -88, -40,
-48, -72, -80, -64, -56, -16, -88, -112, -128, -32, -48, -56,
-24, -16, -8, -64, -120, 120, -96, -96, -88, 80, -128, -24,
-56, -72, -88, -96, 120, 88, -72, -112, 120, -64, -104, 120,
-48, -56, -64, -120, -104, -32, -104, 120, -80, -96, -112,
-120, 56, 88, -64, -128, 96, 64, 88, 120, -40, -80, -104, -120,
-104, -128, 104, 96, -104, -24, -72, -120, -128, 56, 96, -56,
-128, 112, 104, -48, -88, -112, 96, 96, 104, -104, -88, -72,
-40, -88, -96, -72, -88, -96, -120, 120, 104, -80, -88, -96,
72, 72, 80, -120, 88, 96, 120, -120, -24, 96, -104, -16, 104,
80, 48, -56, -80, -96, -56, -88, -104, -104, 120, -88, -88,
120, 104, -72, -120, -120, -24, -32, -40, 112, 88, -104, 120,
96, -104, -32, -32, -32, -96, 96, 96, 80, 80, 88, 64, 88, 120,
72, 120, -40, 72, 88, 112, -88, -96, -104, -56, -80, -88, -72,
-88, -104, -56, -64, -72, -80, -120, 104, -80, -120, -80, -112,
112, -88, 120, 112, 112, 112, -96, -24, -120, -120, -64, -120,
120, -80, 64, 96, -128, 96, 64, 64, 96, -128, -32, 80, 112,
-24, 112, -120, -24, 104, -96, -8, 96, 120, -16, -88, 120, 120,
-72, -56, -16, -128, -128, -128, -104, -120, -72, -64, -96,
-120, -32, -64, -64, -40, -48, -56, -64, -88, -96, -64, -104,
-72, -96, -88, -24, -104, -96, -40, -96, -128, 96, -128, -128,
-96, 104, 88, 80, 112, -88, -8, -64, -104, -80, -96, -120, 112,
96, 120, -32, 56, 80, -72, -104, -88, -32, 104, -128, -24, -56,
-88, -120, -80, -72, -8, -96, -128, -128, -64, -128, 96, -72,
-96, -120, 72, 104, -32, -96, 96, 64, -72, -96, -112, -32, -40,
-48, -64, -88, -112, -88, -128, 96, -88, -128, -88, -64, -64,
-32, -128, -96, -32, -88, -104, -112, 32, 32, 64, -120, 104,
-88, 120, -120, -16, -104, 120, -72, -24, -48, -56, -96, -96,
-96, -64, 96, 96, 96, 64, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 0, 0, 0,
50, 0, 50, 0, 0, 8, -1, 0, 1, 8, 28, 72, -80, -96, -63, -125,
8, 19, 42, 92, -120, 112, 0, 3, 6, 12, 23, 6, -104, 72, -79,
-94, -59, -117, 19, 39, -124, 64, -128, -128, 3, -121, 9, 19,
48, -118, -92, 24, 81, 33, -118, 8, 40, 7, -88, 84, -55, -64,
12, 6, 6, 45, 74, -54, 52, 8, 73, -60, 24, 22, 25, 92, 73, 40,
64, -96, -64, 74, -121, 24, 94, -58, -100, 25, -79, -59, 47,
17, 3, 52, -120, 88, -125, 105, 73, 6, 42, -102, -68, 96, -16,
-71, 18, 3, -118, 6, 13, 14, -114, -36, 26, -64, 69, 7, 18, 28,
-61, -110, -32, -32, -62, -54, -94, 72, -61, -48, -88, -40, 72,
34, -60, 4, 21, 23, -119, 14, -92, 80, -58, 6, -108, 10, 18,
44, 68, -8, 57, -96, -128, 16, 98, 70, -24, -48, 97, -45, 6, 4,
6, 16, 67, -27, 18, 52, -79, -52, -89, -46, 49, -105, -74, -32,
109, -45, -85, -63, -49, 2, 13, 88, -51, -62, 5, 40, 80, 31,
91, 103, 20, 11, -116, 32, -124, -81, -54, 2, 40, -58, -40,
-103, -59, -122, 13, 43, 51, 12, 122, 106, 96, -48, 0, -105,
40, 29, 106, 32, 17, 20, -64, -69, -73, -17, -33, -68, 25, 113,
13, 80, -125, 44, -102, 72, 108, -84, -88, 80, 49, -127, -61,
-94, 28, -97, -108, -4, -98, -103, 102, 9, -127, -21, -40, -81,
23, -32, 35, -126, 39, -10, 2, 32, -116, 29, -1, 27, -74, 37,
-40, 29, 60, 90, -60, -120, -90, 0, -122, -118, -23, -107, 54,
-36, -72, -15, 2, 66, -61, -23, -39, 24, -8, -36, -7, -108,
-27, -128, 44, -59, -112, -16, -64, 67, 3, -39, 21, 72, 0, 6,
34, 120, -31, -123, 124, 124, 52, 16, 84, 3, -119, -88, 82,
-62, 28, -2, 21, 4, -36, -123, -83, -92, -96, 97, 13, 20, 117,
112, 2, -121, 24, 77, -128, 6, 48, -64, 72, -93, -62, 31, 104,
-56, 48, 68, 16, 65, 112, 49, 29, 67, 82, 8, 24, 72, 118, 18,
84, 48, 66, 6, 63, 72, 96, 96, 1, 26, -128, 64, -97, 8, 50, 24,
114, -64, -112, -22, -51, -28, 7, 24, 77, 116, -15, 75, 1, 123,
53, 2, -63, 15, 22, 88, 0, 1, 5, 44, 72, 32, -127, 74, -78,
-47, -122, -62, 27, -90, -24, 49, -28, 1, 69, -106, -108, 76,
21, -99, 8, -127, -119, 29, -81, 60, 41, -63, 15, 16, -116, 80,
65, -114, 22, -44, 40, 72, 6, 111, 60, 4, 77, 3, 34, -124, 1,
-60, -105, 7, 40, 96, -31, -123, -68, 49, -111, 66, 30, 32,
102, -92, 66, 30, 86, 60, -47, -63, 12, 30, 42, 58, 67, 13, 51,
120, -32, 1, 35, 30, 112, 112, -62, 39, -114, -80, 24, -124,
116, 47, 30, 116, 6, 15, -120, 24, -104, 93, 3, -105, 44, -79,
12, 11, -103, -116, 112, 35, 20, 52, -96, 64, 3, 32, 91, -40,
-1, 114, 5, -97, 126, -106, 36, 5, 24, -106, -67, 103, 26, 3,
32, -68, -14, 10, 20, 44, 88, -78, -124, 37, 91, -124, -47,
-33, -105, 112, -56, -28, 7, -103, -70, -86, 116, -57, 29, 52,
80, 37, -101, 8, 54, 24, 99, -121, 17, 82, -108, -80, 0, -83,
7, 93, 56, 70, 14, 41, -96, -78, -107, 11, -117, -48, 97, -42,
12, 127, 32, 64, 66, 91, 19, -96, -88, -94, 35, -16, 110, 10,
-88, 65, 103, 76, -62, 67, 19, 114, -120, -102, 93, 49, 107,
-108, 65, -121, 29, -121, -36, 65, -116, 16, 24, -32, 121,
-125, 33, -70, 108, -96, 112, -97, 37, 5, -127, 100, 23, -128,
-4, 68, 65, 5, 123, -103, 102, -63, 24, 101, -20, 49, -51, 33,
-121, -40, 80, 65, 9, 122, 40, -84, 112, -78, 17, 73, 81, 69,
-110, -110, -28, -38, -105, 9, 84, -30, 69, 21, -106, 60, 106,
32, 68, 25, -127, -96, -96, -25, 6, 14, 56, -96, 112, -83, 90,
81, 116, 2, -72, 57, 16, 66, 8, 88, 28, 49, 26, 66, 8, 51, 60,
-15, -60, 9, 51, -128, -75, -82, 91, 19, 116, 96, -87, 12, 31,
84, 93, -75, 18, 91, 13, 100, -126, -67, 125, 72, 50, 72, 45,
63, 89, -112, 1, 5, 20, -104, 96, 65, 1, 38, -4, 48, 49, 4,
-82, 60, 84, 48, 13, -90, 92, -111, -13, -36, 60, 39, -44, 66,
40, 96, -12, -47, -59, 32, 81, -20, -1, -15, 19, 4, 18, 68, 80,
64, 5, 72, -80, 0, -127, 9, 17, 72, -112, 9, 20, -106, -48,
-48, -86, -79, 56, -49, 77, -14, 66, -76, -100, -68, 119, 20,
59, 44, -15, 19, -53, 20, 0, 30, 103, -101, 110, -66, 97, -122,
25, 52, 44, 33, -125, -74, 11, -92, -98, 115, -35, 90, -55, 1,
52, 33, 83, 76, 33, -118, 10, 97, 73, -70, 81, 7, 29, 44, -35,
1, -46, 29, 76, -22, 2, 7, 30, -84, 50, -60, 7, 48, 60, 114,
-11, 112, 0, -124, -95, 67, 21, -110, 96, -66, -61, 14, 12,
-84, 36, -27, 8, -99, -101, 80, -128, 5, 72, -36, -104, -55,
23, -92, 83, -95, -116, 19, 14, -92, 46, 62, -21, 8, 21, 1, 68,
9, -93, -124, -78, 3, 51, 59, -68, -84, 82, -30, 72, 84, 64, 1,
18, 121, 85, 0, -123, 32, -126, -80, -112, 6, -56, 11, -32, 32,
-2, -28, 10, -71, -64, 5, -80, 48, 7, 74, 56, -63, 16, 58, -40,
65, 45, -28, -16, 5, -108, 56, 16, 37, -112, -80, 17, 5, 70,
-16, 6, 87, 124, -127, 5, -98, 0, -126, 3, 30, -128, -125, 14,
-30, 64, 1, 2, 12, -95, 8, 67, 8, 0, -118, 108, -126, 8, 31,
-16, 1, 40, 100, -96, -120, 20, 76, 33, 18, 121, -104, 64, 88,
102, 24, 2, -78, 48, 66, 5, -101, -96, 26, 12, 118, -72, 67,
100, 12, 103, 34, 4, 89, 65, 18, -1, 72, -127, -125, 2, 30, 80,
7, -107, -24, -37, 22, 26, -15, -66, 2, 20, -96, 17, 12, 64,
65, 52, -30, -74, -128, 7, 88, -47, -118, -28, 99, -120, 2,
122, -112, -124, 36, -100, 34, 1, 14, -48, -126, 26, 74, -128,
-121, 80, 68, 33, 10, -127, -80, -127, 6, 98, -122, 1, 42, 120,
34, 11, 27, -72, -94, 21, 1, 56, 19, 50, 116, -47, -117, -89,
32, -59, 3, 28, 112, 5, 39, -108, 0, -119, 81, 16, -123, 17,
108, 96, 6, 42, -8, 65, 91, 15, 72, -128, 28, -77, -120, 16,
-116, -64, -30, 25, 113, -120, 100, 36, -101, -15, 8, 24, -84,
80, 6, 46, -116, 93, 36, -124, -9, 1, 34, 120, -46, -109, 71,
-8, 33, 73, 16, 66, -122, 21, -12, -32, -108, 61, 40, 5, 47,
18, 48, -121, 62, -2, 113, 18, 58, 112, -62, 6, 18, 64, -53,
90, 50, 82, 49, 10, 40, -62, 41, 11, -63, 75, 94, -68, 32, 117,
106, -16, -93, 30, 18, 89, -53, 4, -60, 64, 52, 10, 81, -128,
47, 86, -64, 76, 102, -106, 34, 23, 47, -48, -126, 22, 28, 80,
76, 90, -34, 82, 32, 6, -56, -90, 54, 69, 25, 0, 38, -64, -126,
11, 71, 8, -89, 56, -107, -96, 8, 31, -104, -45, 7, 68, -32, 2,
55, -127, 72, -108, 11, -112, -95, 8, 49, -120, -89, 60, 71,
-15, -126, 122, 38, -32, -102, -56, 60, -120, 2, 110, 80, 51,
-124, 126, -58, -94, 8, -62, -88, -25, 49, -13, 41, 23, 5,
-112, -31, 6, 8, 93, 65, 64, -15, -39, -56, 117, 98, -124, 9,
51, -72, -59, 45, 56, -95, 78, -121, 6, -128, -96, 5, -39, 39,
67, 49, -54, -47, -114, 122, -44, 32, 1, 1, 0, 59 };
```
|
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 up producing code that basically looks like the following.
```
class MyClass
{
private String[] s;
private void FunnyName$Method()
{
s[0] = "a";
s[1] = "b";
s[2] = "c";
}
public MyClass()
{
FunnyName$Method();
}
```
And as noted java limits all methods to 64k, even the ones the compiler creates.
It may be that Eclipse is doing something sneaky to get around this, but I assure you this is still possible in Eclipse because I have seen the same error message. A better solution is to just read from a static file, like this:
```
public class Icons
{
public static final byte[] compileIcon;
static
{
compileIcon = readFileToBytes("compileIcon.gif");
}
//... (I assume there are several other icons)
private static byte[] readFileToBytes(String filename)
{
try {
File file = new File(filename);
byte[] bytes = new byte[(int)file.length()];
FileInputStream fin = new FileInputStream(file);
fin.read(bytes);
fin.close();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
```
|
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 want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">
```
The javascript confirm is firing so I know the javascript is working, it's specirically the \_\_doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.
I enable the control on the page load event.
Any ideas?
---
I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"
Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.
Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me.
|
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&forumId=1>:
> To reset your user agent string type about:config into the location bar and press enter. This brings up a list of preferences. Enter general.useragent into the filter box, this should show a few preferences (probably 4 of them). If any have the status user set, right-click on the preference and choose Reset
|
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 method that calls \_\_doPostBack, the form ***will not*** post in Firefox. It ***will*** PostBack in IE and Chrome. To solve the problem, make sure your HTML is:
```
<input type="submit" id="yourButton" ...
```
The key is the **type** attribute. It must be "**submit**" in Firefox for \_\_doPostBack to work. Other browsers don't seem to care. Hope this helps anyone else who hits this problem.
|
__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 movement, saving/opening, ...
|
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 aware of that I should look into and learn about?
|
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 indicating when and by whom a given transaction has been undone.
You likely only want to write to a file if very high performance is an issue, or if you have very unstructured or large amounts of data per record that might be unweidly to store in a database. Note that Unless your application has a very large number of transactions database speed is unlikely to be an issue. Also note that if you are working with a file you'll need to handle concurrent access (read / write / locking) very carefully which is likely not something you want to have to deal with.
|
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 DELAYED, you won't slow down your app to much because of the logging. The database is free to write the INSERTs to disk at any time, so it can bundle a bunch of inserts together.
You need to watch out for using MySQL's built in timestamp function (like CURRENT\_TIMESTAMP or CUR\_DATE()), because they will be called whenever the query is actually executed. So you should make sure that any time data is generated in your programming language, and not by the database. (This paragraph might be MySQL-specific)
|
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 result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
```
Now the [Django documention](http://www.djangoproject.com/documentation/0.96/templates/#variables) states that when it sees a **.** in variables
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...
|
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 contains this little piece of code
```
from google.appengine.ext import webapp
register = webapp.template.create_template_register()
def hash(h,key):
if key in h:
return h[key]
else:
return None
register.filter(hash)
```
Now that we have this file, all we need to do is tell the app-engine to use it...
we do that by adding this little line to your main file
```
webapp.template.register_template_library('django_hack')
```
and in your template view add this template instead of the usual code
```
{{ user|hash:item }}
```
And its should work perfectly =)
|
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 variable called `name`.
I think you will need to do some preprocessing of the data in your view before you render it in your template.
|
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.ddj.com/cpp/184406207) should do the job, but before I tried to use `std::tr1::unordered_map` thinking that it was working in that way I described, but it wasn't. So could someone explain me the meaning and behavior of `unordered_map`?
---
@wesc: I'm sure std::map is implemented by STL, while I'm sure std::hash\_map is NOT in the STL (I think older version of Visual Studio put it in a namespace called stdext).
@cristopher: so, if I get it right, the difference is in the implementation (and thus performances), not in the way it behaves externally.
|
[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 used.
See hashing for a description of how that works.
|
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 to avoid it?
|
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 = MyHibernateUtils.listAndCast(q);
...
public static <T> List<T> listAndCast(Query q) {
@SuppressWarnings("unchecked")
List list = q.list();
return list;
}
```
**Prevent Eclipse from generating warnings for unavoidable problems**
In Eclipse, go to Window>Preferences>Java>Compiler>Errors/Warnings and under Generic type, select the checkbox
`Ignore unavoidable generic type problems due to raw APIs`
This will turn off unnecessary warnings for similar problems like the one described above which are unavoidable.
Some comments:
* I chose to pass in the `Query` instead of the result of `q.list()` because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating any `List` in general.
* You could add similar methods for `.iterate()` etc.
|
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 have been added there since `Java Persistence 2.0`. One of them is `createQuery(String, Class<T>)` which returns `TypedQuery<T>`. You can use `TypedQuery` just as you did it with `Query` with that small difference that all operations are type safe now.
So, just change your code to smth like this:
```
Query q = sess.createQuery("from Cat cat", Cat.class);
List<Cat> cats = q.list();
```
And you are all set.
|
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 regions, for all c# code files.
|
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 when a file is opened
* Optionally prevent regions from being collapsed (but still be able to collapse other code)
* Give the #region / #end region lines a smaller, lighter background so they are less noticeable (also an option)
* Works in C# and VB (but only in VS 2010/2012, not supported for 2008)

|
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.