Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
> **Possible Duplicate:**
> [Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?](https://stackoverflow.com/questions/5938802/are-function-and-function-functionally-equal-i)
This is something I haven't quite figured out yet, but I have been using function(){}() just because my VIM syntax highlight screws up if I add the parenthesis, although I've seen (function(){})() around many times, maybe its an IE thing?
**edit:**
```
var singleton = function() {
// code
}();
var singleton = (function() {
// code
})();
``` | Peter Michaux discusses the difference in [An Important Pair of Parens](http://peter.michaux.ca/articles/an-important-pair-of-parens).
Basically the parentheses are a convention to denote that an immediately invoked function expression is following, not a plain function. Especially if the function body is lengthy, this reduces surprises, | The extra set of parentheses makes it clearer that you are constructing a function and then calling it. It's a coding style thing, not a functionality thing. | Difference between (function(){})(); and function(){}(); | [
"",
"javascript",
"syntax",
""
] |
I'm not getting any errors as such just a minor performance issue.
```
EXPLAIN
SELECT
a.nid,
a.title,
a.uid,
b.parent,
b.weight,
c.name,
d.value
FROM table1 AS a INNER JOIN table2 AS b ON a.vid = b.vid AND a.status = 1
INNER JOIN table3 AS c ON c.uid = a.uid
INNER JOIN table4 AS d ON d.content_id = a.nid AND d.value_type = 'percent' AND d.function = 'average'
```
When I look at which tables are being referenced, everything is fine, but from table4 where it should only be selecting the "value" field, I'm getting an ALL being called...
```
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE a ref PRIMARY,vid,status,uid,node_status_type,nid status 4 const 1
1 SIMPLE b eq_ref PRIMARY PRIMARY 4 databasename.a.vid 1
1 SIMPLE c eq_ref PRIMARY PRIMARY 4 databasename.a.uid 1 Using where
1 SIMPLE d ALL NULL NULL NULL NULL 2 Using where
```
As you can see, it's selecting \* from the final table (d). Why is it doing this when I only need ONE field selected from it? Can anyone help me out? | `ALL` means all rows, not all columns. Since it says there are no possible keys, I'd guess that you don't have an index on d.content\_id or d.value\_type or d.function.
If you wanted to be fancy, you could put an index across all 3 of those columns. | Are d.value\_type and d.function indexed fields? That would be initial instinct as to the cause. | What's wrong with my MySQL query? | [
"",
"php",
"mysql",
"inner-join",
""
] |
According to the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html):
> If there are any enclosing try statements whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that **abrupt completion of a finally clause** can disrupt the transfer of control initiated by a throw statement.
Other than returning inside a finally block, what other ways are there? | Throwing an exception from a finally block will also clobber the original exception (if any).
EDIT: Found a reference explaining "abrupt completion".
From [§14.1: Normal and Abrupt Completion of Statements](http://java.sun.com/docs/books/jls/third_edition/html/statements.html#5894):
> An abrupt completion always has an
> associated reason, which is one of the
> following:
>
> * A break with no label
> * A break with a given label
> * A continue with no label
> * A continue with a given label
> * A return with no value
> * A return with a given value
> * A throw with a given value, including exceptions thrown by
> the Java virtual machine
The last three are the only ones possible in a `finally` clause, unless it is inside a loop. | `Sys.exit()` or forcing an abort. GUI programs in particular are notorious for calling `Sys.exit()` on an exception, partly because of a bug that survived until JVM 1.5 --- an exception thrown from the GUI thread didn't make it over to the Main thread.
Update: especially to whomever downvoted this. Sorry, but Sys.exit() does exactly what is meant by abrupt termination including causing the stack not to be unwound; I'll be filing a bug against the documentation tomorrow. I can speak of this with some authority having been a Senior Java Architect at Sun for some years. | What exactly is "Abrupt completion of a finally clause"? | [
"",
"java",
"try-catch",
""
] |
I found some code in a project which looks like that :
```
int main(int argc, char *argv[])
{
// some stuff
try {
theApp.Run();
} catch (std::exception& exc) {
cerr << exc.what() << std::endl;
exit(EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
```
I don't understand why the exceptions are being catched. If they weren't, the application would simply exit and the exception would be printed.
Do you see any good reason to catch exceptions here ?
---
EDIT : I agree that it is good to print the exception error. However, wouldn't it be better to rethrow the exception ? I have the feeling that we are swallowing it here... | If an exception is uncaught, then the standard does not define whether the stack is unwound. So on some platforms destructors will be called, and on others the program will terminate immediately. Catching at the top level ensures that destructors are always called.
So, if you aren't running under the debugger, it's probably wise to catch everything: (...) as well as std::exception. Then your application code can clean up with RAII even on a fatal exception. In many such cases you don't actually need to clean up, since the OS will do it for you. But for instance you might prefer to disconnect cleanly from remote services where possible, and there might be resources external to the process, such as named pipes/mutexes, that you'd prefer to destroy rather than leaking.
Rethrowing the exception in main seems to me of limited use, since you've already lost the context in which it was originally thrown. I suppose that trapping an uncaught exception in the debugger is noisier than just logging the fault to std::cerr, so rethrowing would be the smart move if there's a chance of missing the logging.
If you want the debugger to trap unexpected conditions in debug mode, which in release mode throw an exception that eventually results in an exit, then there are other ways to do that than leaving the exception uncaught so that the debugger sees it. For example, you could use assert macros. Of course, that doesn't help with unexpected and unpredictable conditions, like hardware exceptions if you're using SEH on .NET. | Try-catch in the main function hides the exception from debugger. I would say, it isn't good.
On the other hand, customers are not expected to have debuggers, so catching exceptions is nice. So it is good.
Personally, I catch all exceptions in main function, when making a release build, and I don't do that, when building a debug configuration. | Does it make sense to catch exceptions in the main(...)? | [
"",
"c++",
"exception",
""
] |
I have a relatively simple form which asks a variety of questions. One of those questions is answered via a Select Box. What I would like to do is if the person selects a particular option, they are prompted for more information.
With the help of a few online tutorials, I've managed to get the Javascript to display a hidden div just fine. My problem is I can't seem to localise the event to the Option tag, only the Select tag which is no use really.
At the moment the code looks like (code simplified to aid clarity!):
```
<select id="transfer_reason" name="transfer_reason onChange="javascript:showDiv('otherdetail');">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
```
What I would like is if they choose "Other Reason" it then displays the div. Not sure how I achieve this if onChange can't be used with the Option tag!
Any assistance much appreciated :)
Note: Complete beginner when it comes to Javascript, I apologise if this is stupidly simple to achieve! | Setup the `onchange` event handler for the select box to look at the currently selected index. If the selected index is that of the 'Other Reason' option, then display the message; otherwise, hide the division.
```
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 2) {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
</head>
<body>
<select id="transfer_reason" name="transfer_reason">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</body>
</html>
```
Personally, I'd take it a step further and move the JavaScript into an external file and just include it in the header of the page; however, for all intents and purposes, this should help answer your question. | After reading Tom's great response, I realised that if I ever added other options to my form it would break. In my example this is quite likely, because the options can be added/deleted using a php admin panel.
I did a little reading and altered it ever so slightly so that rather than using **selectedIndex** it uses **value** instead.
```
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.value === "Other") {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
```
Hope this helps someone else in the future! | Javascript - onchange within <option> | [
"",
"javascript",
"html",
""
] |
When I run my tests in Visual Studio individually, they all pass without a problem. However, when I run all of them at once some pass and some fail. I tried putting in a pause of 1 second in between each test method with no success.
Any ideas? Thanks in advance for your help... | It's possible that you have some shared data. Check for static member variables in the classes in use that means one test sets a value that causes a subsequent test to fail.
You can also debug unit tests. Depending on the framework you're using, you should be able to run the framework tool as a debug start application passing the path to the compiled assembly as a parameter. | It's very possible that some modifications/instantiations done in one test affect the others. That indicates poor test design and lack of proper isolation. | Testing in Visual Studio Succeeds Individually, Fails in a Set | [
"",
"c#",
".net",
"visual-studio",
"unit-testing",
""
] |
I have a VB background and I'm converting to C# for my new job. I'm also trying to get better at .NET in general. I've seen the keyword "T" used a lot in samples people post. What does the "T" mean in C#? For example:
```
public class SomeBase<T> where T : SomeBase<T>, new()
```
What does `T` do? Why would I want to use it? | It's a symbol for a [generic type parameter](http://msdn.microsoft.com/en-us/library/512aeb7t.aspx). It could just as well be something else, for example:
```
public class SomeBase<GenericThingy> where GenericThingy : SomeBase<GenericThingy>, new()
```
Only T is the default one used and encouraged by Microsoft. | T is not a keyword per-se but a placeholder for a generic type. See Microsoft's [Introduction to Generics](http://msdn.microsoft.com/en-us/library/ms379564(vs.80).aspx)
The equivalent VB.Net syntax would be:
```
Public Class SomeBase(Of T As {Class, New}))
``` | What does "T" mean in C#? | [
"",
"c#",
".net",
"generics",
""
] |
I want my JTextPane to insert spaces whenever I press Tab. Currently it inserts the tab character (ASCII 9).
Is there anyway to customize the tab policy of JTextPane (other than catching "tab-key" events and inserting the spaces myself seems an)? | You can set a javax.swing.text.Document on your JTextPane. The following example will give you an idea of what I mean :)
```
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
public class Tester {
public static void main(String[] args) {
JTextPane textpane = new JTextPane();
textpane.setDocument(new TabDocument());
JFrame frame = new JFrame();
frame.getContentPane().add(textpane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(200, 200));
frame.setVisible(true);
}
static class TabDocument extends DefaultStyledDocument {
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
str = str.replaceAll("\t", " ");
super.insertString(offs, str, a);
}
}
}
```
Define a DefaultStyleDocument to do the work. Then set the Document to your JTextPane.
Cheers
Kai | As far as I know, you'd have to catch key events, as you say. Depending on usage, you might also get away with waiting until the input is submitted, and changing tabs to spaces at that time. | Setting the tab policy in Swing's JTextPane | [
"",
"java",
"swing",
"jtextpane",
""
] |
The company I work for sells a J2EE application that runs on Tomcat, WebSphere, or WebLogic. We have a customer that is trying to decide between Tomcat and WebSphere. They're leaning towards WebSphere because they're concerned that Tomcat has more security holes.
After searching around on the web, I've been unable to find any sites or studies that compare the robustness of the major J2EE application servers from a security standpoint.
Can any of you point me to information comparing app server security holes? | I'd say use tomcat over WebSphere if at all possible.
I think 99% of security is how you set it all up.
Are you also evaluating the security implications of Apache HTTP Server, IBM HTTP Server, and IIS?
Security involves so much more than just what application server you choose to run your webapp on.
[Tomcat security report](http://tomcat.apache.org/security-6.html)
[Websphere security report](http://www-01.ibm.com/support/docview.wss?rs=180&uid=swg27004980) (You have to dig into each update to see what was fixed) | It's interesting that your client is "concerned that Tomcat has more security holes." I wonder if they could list what those holes are? If they can't, it's hearsay and FUD.
I would say that all web servers/servlet engines suffer from the same issues. It's the applications that are deployed on them that represent the real security holes. Cross-site scripting, SQL injection, lack of input validation, exposure of sensitive data due to poor layering and practices - these are all *application* issues that will be problems regardless of which app server you choose.
My personal opinion is that WebLogic is the best Java EE app server on the market. I don't have first-hand experience with WebSphere, but people that I respect who have tell me that it's a horror show. I've only used Tomcat for local development. It's never failed me, but that's hardly production experience. I have no idea how it scales.
I'd think carefully about Spring's dm Server, based on Tomcat, Spring, and OSGi. I have a feeling that it represents a future direction that all its competitors will be taking. | Security of Tomcat versus WebSphere versus WebLogic | [
"",
"java",
"tomcat",
"jakarta-ee",
"websphere",
"weblogic",
""
] |
I want to write an Exception to an MS Message Queue. When I attempt it I get an exception. So I tried simplifying it by using the XmlSerializer which still raises an exception, but it gave me a bit more info:
> {"There was an error reflecting type
> 'System.Exception'."}
with InnerException:
> {"Cannot serialize member
> System.Exception.Data of type
> System.Collections.IDictionary,
> because it implements IDictionary."}
Sample Code:
```
Exception e = new Exception("Hello, world!");
MemoryStream stream = new MemoryStream();
XmlSerializer x = new XmlSerializer(e.GetType()); // Exception raised on this line
x.Serialize(stream, e);
stream.Close();
```
EDIT:
I tried to keep this a simple as possible, but I may have overdone it. I want the whole bit, stack trace, message, custom exception type, and custom exception properties. I may even want to throw the exception again. | I think you basically have two options:
1. Do your own manual serialization (probably do NOT want to do that). XML serialization will surely not work due to the exact message you get in the inner exception.
2. Create your own custom (serializable) exception class, inject data from the thrown Exception into your custom one and serialize that. | I was looking at Jason Jackson's answer, but it didn't make sense to me that I'm having problems with this even though System.Exception implements ISerializable. So I bypassed the XmlSerializer by wrapping the exception in a class that uses a BinaryFormatter instead. When the XmlSerialization of the MS Message Queuing objects kicks in all it will see is a class with a public byte array.
Here's what I came up with:
```
public class WrappedException {
public byte[] Data;
public WrappedException() {
}
public WrappedException(Exception e) {
SetException(e);
}
public Exception GetException() {
Exception result;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream(Data);
result = (Exception)bf.Deserialize(stream);
stream.Close();
return result;
}
public void SetException(Exception e) {
MemoryStream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, e);
Data = stream.ToArray();
stream.Close();
}
}
```
The first test worked perfectly, but I was still concerned about custom exceptions. So I tossed together my own custom exception. Then I just dropped a button on a blank form. Here's the code:
```
[Serializable]
public class MyException : Exception, ISerializable {
public int ErrorCode = 10;
public MyException(SerializationInfo info, StreamingContext context)
: base(info, context) {
ErrorCode = info.GetInt32("ErrorCode");
}
public MyException(string message)
: base(message) {
}
#region ISerializable Members
void ISerializable.GetObjectData(SerializationInfo info,
StreamingContext context) {
base.GetObjectData(info, context);
info.AddValue("ErrorCode", ErrorCode);
}
#endregion
}
private void button1_Click(object sender, EventArgs e) {
MyException ex = new MyException("Hello, world!");
ex.ErrorCode = 20;
WrappedException reply = new WrappedException(ex);
XmlSerializer x = new XmlSerializer(reply.GetType());
MemoryStream stream = new MemoryStream();
x.Serialize(stream, reply);
stream.Position = 0;
WrappedException reply2 = (WrappedException)x.Deserialize(stream);
MyException ex2 = (MyException)reply2.GetException();
stream.Close();
Text = ex2.ErrorCode.ToString(); // form shows 20
// throw ex2;
}
```
Although it seemed like all of other exception types that I looked up are marked with the SerializableAttribute, I'm going to have to be careful about custom exceptions that are not marked with the SerializableAttribute.
EDIT: Getting ahead of myself. I didn't realize that BinaryFormatter is not implemented on CF.
EDIT: Above code snippets were in a desktop project. In the CF version, the WrappedException will basically look the same I ***just*** need to implement my own BinaryFormater, but I'm very open to suggestions on that one. | In C#, how can I serialize System.Exception? (.Net CF 2.0) | [
"",
"c#",
"exception",
"serialization",
"compact-framework",
""
] |
I have a column containing items that can be sorted by the user:
```
DOC_ID DOC_Order DOC_Name
1 1 aaa
2 3 bbb
3 2 ccc
```
I'm trying to figure out a way to properly initialize DOC\_Order when the entry is created. A good value would either be the corresponding DO-CID (since it is autoassigned), or MAX(DOC-ORDER) + 1
After a bit of googling I saw it was possible to assign a scalar function's return to the default column.
```
CREATE FUNCTION [dbo].[NEWDOC_Order]
(
)
RETURNS int
AS
BEGIN
RETURN (SELECT MAX(DOC_ORDER) + 1 FROM DOC_Documents)
END
```
But each of my tries using MS SQL Management studio ended in a "Error validating the default for column 'DOC\_Order'" message.
Any idea of what the exact SQL syntax to assign a function to DEFAULT is? | The syntax to add a default like that would be
```
alter table DOC_Order
add constraint
df_DOC_Order
default([dbo].[NEWDOC_Order]())
for DOC_Order
```
Also, you might want to alter your function to handle when DOC\_Order is null
```
Create FUNCTION [dbo].[NEWDOC_Order]
(
)
RETURNS int
AS
BEGIN
RETURN (SELECT ISNULL(MAX(DOC_ORDER),0) + 1 FROM DOC_Documents)
END
``` | IF someone wants to do it using the interface, typing
```
[dbo].[NEWDOC_Order]()
```
does the trick. You apparently need all brackets or it will reject your input. | Bind a column default value to a function in SQL 2005 | [
"",
"sql",
"sql-server-2005",
"t-sql",
"default-value",
""
] |
I would like to be able to do somthing like the following:
```
//non-generic
var MyTable = new Table();
string name = MyTable.Name;
IEnumerable<String> rows = MyTable.Rows;
//generic
var MyTableGeneric = new Table<MyType>();
string name = MyTableGeneric.Name;
IEnumerable<MyType> rows = MyTableGeneric .Rows;
```
Would something like this be to much:
<http://img81.imageshack.us/img81/427/diagramcm3.jpg>
or would this be better:
<http://img301.imageshack.us/img301/4136/presentation1nh9.jpg>
Sorry if this hard to understand what I am trying to get at, basically I have two objects will share comman properties except for there row collections which will be generic. I would like to do this in cleanest way.
Sorry for my crappy diagrams, made in powerpoint :) | I'd say the second design is better. Less items and easier inheritance path.
The first design has unnecessary interfaces, which you don't really need unless you're implementing something else which implements the interface, but doesn't inherit from the base class. | What's the difference betweeen a `Table` and a `Table<string>`? In other words, can you not just use `Table<string>` as your nongeneric form?
If you *do* go for the second option, I'd suggest renaming one of your `Rows` properties - you may be able to get away with having two properties of different types through hiding etc, but it's not going to be pleasant.
How much behaviour will your `Table` type actually have? If it's really just a container, you may not need an interface - but if it's got significant logic behind it, you may want to have an interface so that you can mock out the table when testing a class which uses it. | Is this design a good idea - Interfaces and Abstract class | [
"",
"c#",
"generics",
"interface",
"abstract-class",
""
] |
Is there a way to get all alphabetic chars (A-Z) in an array in PHP so I can loop through them and display them? | ```
$alphas = range('A', 'Z');
```
Documentation: <https://www.php.net/manual/en/function.range.php> | To get both upper and lower case merge the two ranges:
```
$alphas = array_merge(range('A', 'Z'), range('a', 'z'));
``` | Way to get all alphabetic chars in an array in PHP? | [
"",
"php",
""
] |
I use RedGate SQL data compare and generated a .sql file, so I could run it on my local machine. But the problem is that the file is over 300mb, which means I can't do copy and paste because the clipboard won't be able to handle it, and when I try to open the file in SQL Server Management Studio I get an error about the file being too large.
Is there a way to run a large .sql file? The file basically contains data for two new tables. | From the command prompt, start up `sqlcmd`:
```
sqlcmd -S <server> -i C:\<your file here>.sql
```
Just replace `<server>` with the location of your SQL box and `<your file here>` with the name of your script. Don't forget, if you're using a SQL instance the syntax is:
```
sqlcmd -S <server>\instance.
```
Here is the list of all arguments you can pass sqlcmd:
```
Sqlcmd [-U login id] [-P password]
[-S server] [-H hostname] [-E trusted connection]
[-d use database name] [-l login timeout] [-t query timeout]
[-h headers] [-s colseparator] [-w screen width]
[-a packetsize] [-e echo input] [-I Enable Quoted Identifiers]
[-c cmdend] [-L[c] list servers[clean output]]
[-q "cmdline query"] [-Q "cmdline query" and exit]
[-m errorlevel] [-V severitylevel] [-W remove trailing spaces]
[-u unicode output] [-r[0|1] msgs to stderr]
[-i inputfile] [-o outputfile] [-z new password]
[-f | i:[,o:]] [-Z new password and exit]
[-k[1|2] remove[replace] control characters]
[-y variable length type display width]
[-Y fixed length type display width]
[-p[1] print statistics[colon format]]
[-R use client regional setting]
[-b On error batch abort]
[-v var = "value"...] [-A dedicated admin connection]
[-X[1] disable commands, startup script, environment variables [and exit]]
[-x disable variable substitution]
[-? show syntax summary]
``` | I had exactly the same issue and had been struggling for a while then finally found the solution which is to set `-a` parameter to the `sqlcmd` in order to change its default packet size:
```
sqlcmd -S [servername] -d [databasename] -i [scriptfilename] -a 32767
``` | How do you import a large MS SQL .sql file? | [
"",
"sql",
"sql-server",
"import",
""
] |
Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that `synchronized(this)` should be avoided. Instead, they claim, a lock on a private reference is to be preferred.
Some of the given reasons are:
* [some *evil code* may steal your lock](https://stackoverflow.com/questions/416183/in-java-critical-sections-what-should-i-synchronize-on#416198) (very popular this one, also has an "accidentally" variant)
* [all synchronized methods within the same class use the exact same lock, which reduces throughput](https://stackoverflow.com/questions/309631/what-cases-require-synchronized-method-access-in-java#309677)
* [you are (unnecessarily) exposing too much information](https://stackoverflow.com/questions/439302/allowing-a-method-to-lock-its-parent-object-in-java#439317)
Other people, including me, argue that `synchronized(this)` is an idiom that is used a lot (also in Java libraries), is safe and well understood. It should not be avoided because you have a bug and you don't have a clue of what is going on in your multithreaded program. In other words: if it is applicable, then use it.
I am interested in seeing some real-world examples (no foobar stuff) where avoiding a lock on `this` is preferable when `synchronized(this)` would also do the job.
Therefore: **should you always avoid `synchronized(this)` and replace it with a lock on a private reference?**
---
Some further info (updated as answers are given):
* we are talking about instance synchronization
* both implicit (`synchronized` methods) and explicit form of `synchronized(this)` are considered
* if you quote Bloch or other authorities on the subject, don't leave out the parts you don't like (e.g. Effective Java, item on Thread Safety: *Typically it is the lock on the instance itself, but there are exceptions.)*
* if you need granularity in your locking other than `synchronized(this)` provides, then `synchronized(this)` is not applicable so that's not the issue | I'll cover each point separately.
1. > Some evil code may steal your lock (very popular this one, also has an
> "accidentally" variant)
I'm more worried about *accidentally*. What it amounts to is that this use of `this` is part of your class' exposed interface, and should be documented. Sometimes the ability of other code to use your lock is desired. This is true of things like `Collections.synchronizedMap` (see the javadoc).
2. > All synchronized methods within the same class use the exact same
> lock, which reduces throughput
This is overly simplistic thinking; just getting rid of `synchronized(this)` won't solve the problem. Proper synchronization for throughput will take more thought.
3. > You are (unnecessarily) exposing too much information
This is a variant of #1. Use of `synchronized(this)` is part of your interface. If you don't want/need this exposed, don't do it. | Well, firstly it should be pointed out that:
```
public void blah() {
synchronized (this) {
// do stuff
}
}
```
is semantically equivalent to:
```
public synchronized void blah() {
// do stuff
}
```
which is one reason not to use `synchronized(this)`. You might argue that you can do stuff around the `synchronized(this)` block. The usual reason is to try and avoid having to do the synchronized check at all, which leads to all sorts of concurrency problems, specifically the [double checked-locking problem](http://en.wikipedia.org/wiki/Double-checked_locking), which just goes to show how difficult it can be to make a relatively simple check threadsafe.
A private lock is a defensive mechanism, which is never a bad idea.
Also, as you alluded to, private locks can control granularity. One set of operations on an object might be totally unrelated to another but `synchronized(this)` will mutually exclude access to all of them.
`synchronized(this)` just really doesn't give you anything. | Avoid synchronized(this) in Java? | [
"",
"java",
"multithreading",
"synchronization",
"synchronized",
""
] |
I'm running on a shared \*NIX server (run by Site5). I have a php script that runs in the background occasionally doing some offline calculations. It uses around 100% CPU while it runs. I've tried nice-ing it, like this:
```
nice -n 19 php script.php
```
but that doesn't seem to make any difference. | You could scatter usleep ( int $micro\_seconds ) through your code. This will force your script to stop for tiny amounts of time leaving the CPU free for other things.
Will that be necessary though? If you script has a low priority, does it matter that it's using 100% of the CPU... If other processes with a higher priority needed the CPU wouldn't they get the time they needed and your script getting the rest (up to 100%)? | Even niced, it'll use 100% CPU if available. However, the kernel will give priority to any other (non-niced) processes that come along. | How do I make php nicer to the CPU? | [
"",
"php",
"nice",
""
] |
Instruction on accessing a interface to an application, in **plain** C/C++ **without**:
* MFC
* ATL
* WTL
Basically, I would like to make use of a COM object.
Working sample source code or guidance - to **using** (functionality) a COM object, **not** creating a COM server.
Regards | Here is a simple example in plain C++:
```
CoInitialize(NULL); // absolutely essential: initialize the COM subsystem
IMyInterface* pIFace;
// create the object and obtain a pointer to the sought interface
CoCreateInstance(CLSID_MyObject, NULL, CLSCTX_ALL, IID_IMyInterface, &pIFace);
pIFace->MethodIReallyNeed(); // use the object
pIFace->Release(); // free the object
CoUninitialize(); // cleanup COM after you're done using its services
```
Copied from here: [COM Basics](http://netez.com/2xExplorer/shellFAQ/bg_com.html) | There's an article on CodeProject, [Introduction to COM - What It Is and How to Use It](http://www.codeproject.com/KB/COM/comintro.aspx) that you may find useful. It gives a pretty good introduction and a worked example. | Use of CoGetClassObject() in C - access COM Object interface | [
"",
"c++",
"c",
"windows",
"com",
""
] |
still trying to find where i would use the "yield" keyword in a real situation.
I see this thread on the subject
[What is the yield keyword used for in C#?](https://stackoverflow.com/questions/39476/what-is-the-yield-keyword-used-for-in-c)
but in the accepted answer, they have this as an example where someone is iterating around Integers()
```
public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}
```
but why not just use
```
list<int>
```
here instead. seems more straightforward.. | If you build and return a List (say it has 1 million elements), that's a big chunk of memory, and also of work to create it.
Sometimes the caller may only want to know what the first element is. Or they might want to write them to a file as they get them, rather than building the whole list in memory and then writing it to a file.
That's why it makes more sense to use yield return. It doesn't look that different to building the whole list and returning it, but it's very different because the whole list doesn't have to be created in memory before the caller can look at the first item on it.
When the caller says:
```
foreach (int i in Integers())
{
// do something with i
}
```
Each time the loop requires a new i, it runs a bit more of the code in Integers(). The code in that function is "paused" when it hits a `yield return` statement. | Yield allows you to build methods that produce data without having to gather everything up before returning. Think of it as returning multiple values along the way.
Here's a couple of methods that illustrate the point
```
public IEnumerable<String> LinesFromFile(String fileName)
{
using (StreamReader reader = new StreamReader(fileName))
{
String line;
while ((line = reader.ReadLine()) != null)
yield return line;
}
}
public IEnumerable<String> LinesWithEmails(IEnumerable<String> lines)
{
foreach (String line in lines)
{
if (line.Contains("@"))
yield return line;
}
}
```
Neither of these two methods will read the whole contents of the file into memory, yet you can use them like this:
```
foreach (String lineWithEmail in LinesWithEmails(LinesFromFile("test.txt")))
Console.Out.WriteLine(lineWithEmail);
``` | Yield keyword value added? | [
"",
"c#",
"iterator",
"ienumerable",
"yield",
""
] |
I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax.
Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime.
The way this is currently working is very simple: the templates have the Pythonic %(var)s placeholders and I replace those with a dictionary before applying Markdown2 formatting.
Turns out that the end user of this system will be a tech-savvy user and I wouldn't like to make it obvious to everyone that it's written in Python.
It's not that I don't like Python... I actually think Python is the perfect tool for the job, I just don't want to expose that to the user (would like the same even if it were written in Java, Perl, Ruby or anything else).
So I'd like to ask for insights on what would be, in your opinion, the best way to expose placeholders for the users:
1. What do you think is the best placeholder format (thinks like ${var}, $(var) or #{var})?
2. What would be the best way to replace those placeholders?
I though of using a Regular Expression to change - for instance - ${var} into %(var)s and then applying the regular Python templating substitution, but I am not sure that's the best approach.
If you go that way, it would be very nice if you could indicate me what is a draft of that regular expression as well.
Thanks!
**Update**: An user pointed out using full-blown templating systems, but I think that may not be worth it, since all I need is placeholders substitution: I won't have loops or anything like that.
**Final Update**: I have chosen not to use any template engines at this time. I chose to go with the simpler string.Template approach (as pointed out on a comment by [hyperboreean](https://stackoverflow.com/users/49032/hyperboreean)). Truth is that I don't like to pick a solution because sometime in the future there may be a need. I will keep all those suggestions on my sleeve, and if on the lifespan of the application there is a clear need for one or more features offered by them, I'll revisit the idea. Right now, I really think it's an overkill. Having full blown templates that **the end user** can edit as he wants is, at least on my point of view, more trouble than benefit. Nevertheless, it feels much nicer being aware of the reasons I did not went down that path, than just not researching anything and choosing it.
Thanks a lot for all the input. | Use a real template tool: [mako](http://www.makotemplates.org/) or [jinja](http://jinja.pocoo.org/). Don't roll your own. Not worth it. | Have a light templating system ... I am not sure if you can use some of the ones TurboGears provides (Kid or Genshi) | Hiding implementation details on an email templating system written in Python | [
"",
"python",
"email",
"formatting",
"templates",
""
] |
Using Python 2.6, is there a way to check if all the items of a sequence equals a given value, in one statement?
```
[pseudocode]
my_sequence = (2,5,7,82,35)
if all the values in (type(i) for i in my_sequence) == int:
do()
```
Instead of, say:
```
my_sequence = (2,5,7,82,35)
all_int = True
for i in my_sequence:
if type(i) is not int:
all_int = False
break
if all_int:
do()
``` | Use:
```
all( type(i) is int for i in lst )
```
Example:
```
In [1]: lst = range(10)
In [2]: all( type(i) is int for i in lst )
Out[2]: True
In [3]: lst.append('steve')
In [4]: all( type(i) is int for i in lst )
Out[4]: False
```
[Edit]. Made cleaner as per comments. | Do you mean
```
all( type(i) is int for i in my_list )
```
?
Edit: Changed to `is`. Slightly faster. | If all in list == something | [
"",
"python",
"python-2.6",
""
] |
I was just reading through ["Learning Python" by Mark Lutz and came across this code sample](http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false):
```
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
```
It was identified as a cyclic data structure.
So I was wondering, and here is my question:
## **What is a 'cyclic data structure' used for in real life programming?**
There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L
```
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
``` | Lots of things. Circular buffer, for example: you have some collection of data with a front and a back, but an arbitrary number of nodes, and the "next" item from the last should take you back to the first.
Graph structures are often cyclic; acyclicity is a special case. Consider, for example, a graph containing all the cities and roads in a traveling salesman problem.
---
Okay, here's a particular example for you. I set up a collection of towns here in Colorado:
```
V=["Boulder", "Denver", "Colorado Springs", "Pueblo", "Limon"]
```
I then set up pairs of cities where there is a road connecting them.
```
E=[["Boulder", "Denver"],
["Denver", "Colorado Springs"],
["Colorado Springs", "Pueblo"],
["Denver", "Limon"],
["Colorado Springs", "Limon"]]
```
This has a bunch of cycles. For example, you can drive from Colorado Springs, to Limon, to Denver, and back to Colorado Springs.
If you create a data structure that contains all the cities in V and all the roads in E, that's a *graph* data structure. This graph would have cycles. | I recently created a cyclic data structure to represent the eight cardinal and ordinal directions. Its useful for each direction to know its neighbors. For instance, Direction.North knows that Direction.NorthEast and Direction.NorthWest are its neighbors.
This is cyclic because each neighor knows its neighbors until it goes full swing around (the "->" represents clockwise):
North -> NorthEast -> East -> SouthEast -> South -> SouthWest -> West -> NorthWest -> North -> ...
Notice we came back to North.
That allows me to do stuff like this (in C#):
```
public class Direction
{
...
public IEnumerable<Direction> WithTwoNeighbors
{
get {
yield return this;
yield return this.CounterClockwise;
yield return this.Clockwise;
}
}
}
...
public void TryToMove (Direction dir)
{
dir = dir.WithTwoNeighbors.Where (d => CanMove (d)).First ()
Move (dir);
}
```
This turned out to be quite handy and made a lot of things much less complicated. | What is a cyclic data structure good for? | [
"",
"python",
"data-structures",
"recursion",
"cyclic-reference",
""
] |
Does there exist any way in .Net to check before opening if a file (on a local network drive) is already in use? | You should try to access it and if it failed, you either don't have required permissions (which you can check with GetAccessControl) or it's locked by another process.
But I don't think there is any reliable measure to distinguish a lock and a permission failure (since you might be able to read the file, but not able to check the permissions). Even Windows' error message says you either don't have permission or it's being used by another process.
You can use WMI `CIM_DataFile` class to query `InUseCount` for a specified data file.
If you're looking for a programmatical equivalent to `lsof` utility in Linux, to find out all open files by a given **local** process, you could try using `Win32_Process` WMI class through `System.Management` namespace. You could issue a WMI query to look up the file name in all open files being used by all local processes too see if it's there or not. Alternatively, you could P/Invoke and use `NtQuerySystemInformation` API directly to accomplish the same task. | This will do. FileShare.None as mentioned in MSDN :
> None : Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.
```
File.Open(name, FileMode.Open, FileAccess.Read, FileShare.None);
```
EDIT : Remember to wrap in a Try/Catch block, and using FileShare.None actually means you want to open the file exclusively. | Checking if the file is already in use before opening (network drive, C#) | [
"",
"c#",
"file",
"readonly",
""
] |
Whenever I read about Swing they say they are light weight components. So I just googled Swing and found that it means Swing does not depend on native peers. Is that why they are called **"light weight"**? I mean by light weight I thought maybe the Swing components occupy less memory than the AWT components. Isn't that so? | [Swing](http://java.sun.com/docs/books/tutorial/uiswing/) is considered lightweight because it is fully implemented in Java, without calling the native operating system for drawing the graphical user interface components.
On the other hand, [AWT](http://en.wikipedia.org/wiki/Abstract_Window_Toolkit) (Abstract Window Toolkit) is heavyweight toolkit, as it merely makes calls to the operating system in order to produce its GUI components.
The [Evolution of the Swing Paint System](http://java.sun.com/products/jfc/tsc/articles/painting/#background) section from the [Painting in AWT and Swing](http://java.sun.com/products/jfc/tsc/articles/painting/) article explains the difference between lightweight and heavyweight:
> When the original AWT API was
> developed for JDK 1.0, only
> heavyweight components existed
> ("heavyweight" means that the
> component has it's own opaque native
> window). This allowed the AWT to rely
> heavily on the paint subsystem in each
> native platform.
>
> [...]
>
> With
> the introduction of lightweight
> components in JDK 1.1 (a "lightweight"
> component is one that reuses the
> native window of its closest
> heavyweight ancestor), the AWT needed
> to implement the paint processing for
> lightweight components in the shared
> Java code.
As Swing is implemented in Java, it does have some performance disadvantage, however, I hear that performance has improved in recent releases of Java.
The advantage of Swing is that it has many more components available such as [`JTable`](http://java.sun.com/javase/6/docs/api/javax/swing/JTable.html) and [`JList`](http://java.sun.com/javase/6/docs/api/javax/swing/JList.html) which are more graphical and extensible than the components provided in AWT, allowing for more graphics-rich applications to be developed. | Lightweight vs heavyweight is a question of how the UI components are implemented. Heavyweight components wrap operating system objects, lightweight components don't. They are implemented strictly in the JDK. | Swing components are light-weight? | [
"",
"java",
"swing",
"awt",
""
] |
Does the Hibernate API support object result sets in the form of a collection other than a List?
For example, I have process that runs hundreds of thousands of iterations in order to create some data for a client. This process uses records from a Value table (for example) in order to create this output for each iteration.
With a List I would have to iterate through the entire list in order to find a certain value, which is expensive. I'd like to be able to return a TreeMap and specify a key programmatically so I can search the collection for the specific value I need. Can Hibernate do this for me? | I assume you are referring to the [`Query.list()`](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Query.html#list()) method. If so: no, there is no way to return top-level results other than a `List`. If you are receiving too many results, why not issue a more constrained query to the database? If the query is difficult to constrain, you can populate your own `Map` with the contents of Hibernate's `List` and then throw away the list. | If I understand correctly, you load a bunch of data from the database to memory and then use them locally by looking for certain objects in that list.
If this is the case, I see 2 options.
1. Dont load all the data, but for each iteration access the database with a query returning only the specific record that you need. This will make more database queries, so it will probably bu slower, but with much less memory consumption. This solution could easily be improved by adding cache, so that most used values will be gotten fast. It will of course need some performance measurement, but I usually favor a naive solution with good caching, as the cache can implemented as a cross-concern and be very transparent to the programmer.
2. If you really want to load all your data in memory (which is actually a form of caching), the time to transform your data from a list to a TreeMap (or any other efficient structure) will probably be small compared to the full processing. So you could do the data transformation yourself.
As I said, in the general case, I would favor a solution with caching ... | Can Hibernate return a collection of result objects OTHER than a List? | [
"",
"java",
"hibernate",
""
] |
Lately all modern programming languages have a definitive web site to support, distribute, learn the programming language, as well as community forums, e-mail lists and so on. Java has java.sun.com, python has python.org, etc.
However C/C++ does not seem to have such a site. Which site do you use, say in a document, to link for C or C++ programming language? Wikipedia entries don't count, although they might be perfect fit.
Founder's web sites? Or any other ideas? | [The C Programming Language](http://cm.bell-labs.com/cm/cs/cbook/) | Bjarne Stroustrup keeps a lot of interesting links on [his homepage](http://www.research.att.com/~bs/). The [FAQ](http://www.research.att.com/~bs/bs_faq.html) and [C++ glossary](http://www.research.att.com/~bs/glossary.html) are good references, but make sure you also check out [Did you really say that?](http://www.research.att.com/~bs/bs_faq.html#really-say-that) for an interesting read. | What is the definitive link for C and C++ programming languages? | [
"",
"c++",
"c",
""
] |
Sometimes Eclipse comes up saying "hey you should debug this line!!!" but doesn't actually close the program. I can then continue to play big two, and even go through the same events that caused the error the first time and get another error box to pop up!
The bug is simple, I'll fix it, I just want to know why some bugs are terminal and some are not? What's the difference? | Programming mistakes can be categorized in these categories:
1. Compile-time errors, which are caught by the compiler at the time of compilation and without correcting them, it's not possible to run the program at all.
2. Run-time errors, which are not caught by the compiler but put the computer in a situation which it cannot figure out what to do by itself, such as unhandled exceptions. Most of the times, this will cause the program to fail at run time and crash.
3. Logical errors, which are perfectly acceptable by the computer, as it is a valid computer program, but does not produce the result you expect. There is no way a computer can catch them since computer doesn't know your intention.
In practice, it's a good thing to make errors be as deadly as possible as soon as they occur. It makes us find them sooner and correct them easier. This is why in "safer" languages such as Java, we have checked exceptions, and unhandled exceptions will cause the application to crash immediately instead of going on and probably producing incorrect results. | A previous answer gets the java-part of this right:
> If an exception occurs in your main
> thread, it may be terminal, but if it
> occurs in another thread it is not
> terminal. It's terminal for the main
> thread if the other threads in the
> application are daemon threads.
The bigger truth is that the JVM that your application is running in will shut down when there are no non-daemon threads still running. That, or an explicit call to System.exit (or an outright JVM crash) are the only ways the JVM will completely exit.
In many simpler Java applications, there is only 1 non-daemon thread (the thread the JVM started to run your main() in at start up.) Because, in the simple case, the thread running our code is the only non-daemon thread, we get the impression that an unhandled exception causes the JVM to exit. That is not true, unless that thread happens to be the only remaining non-daemon thread.
You can prove this to yourself with the following little program:
```
public class TestMain {
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
while(true) {
System.out.println("A");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("t1 interrupted.");
}
}
}
};
t1.setDaemon(false);
Thread t2 = new Thread() {
public void run() {
int count = 0;
while(true) {
if(count < 5) {
System.out.println("B");
count++;
} else {
throw new RuntimeException("Intentional RuntimeException!");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("t2 interrupted.");
}
}
}
};
t2.setDaemon(false);
t1.start();
t2.start();
}
}
```
If you run this, you'll notice that you get intermixed "A"s and "B"s, until the 5th "B", at which point you get a stack trace of the exception we threw, and the "A"'s continue (the "B"s do not continue, because that thread just died because of the unhandled exception.)
Now, if you go back and change `t1.setDaemon(false)` to `t1.setDaemon(true)`, and run again, you'll see that when t2 terminates because of the exception, there are no non-daemon threads remaining, and the JVM will exit.
That answers the "why do some bugs not close the JVM" question. But it doesn't answer the part of the question about why Eclipse pops up a debugger.
The answer to that is simpler (but I'm a bit less certain about it...someone else chime in): the Eclipse debugger suspends any time a thread dies because of an unhandled exception. It's making the assumption that you didn't mean for the thread to die, and that you need to fix the bug. I believe it's actually watching for the java.lang.ThreadDeath exception, and suspending anytime it gets thrown. | what does it mean when a bug doesn't crash the program | [
"",
"java",
"eclipse",
"crash",
""
] |
I am compiling a c++ static library in vs2008, and in the solution i also have a startup project that uses the lib, and that works fine.
But when using the lib in another solution i get an run-time check failure.
"The value of ESP was not properly saved across a functioncall"
Stepping through the code i noticed a function foo() jumping to bar() instead right before the crash. The functions in question are just regular functions and no function pointers.
Anyone has any clue what might be going on, and why it works when using the lib's from the same solution?
edit: the functions (methods) are part of a class, if that helps. | Forgive me for stating the bleeding obvious here, but... I've seen this sort of thing happen many times before when object (.o) and header (.h) files get out of sync. Especially with respect to virtual methods.
Consider: The object file is compiled with header:
```
class Foo { virtual void f(); };
```
But then the header gets changed to:
```
class Foo { virtual void g(); virtual void f(); };
```
And for the next object file, the compiler's assumptions about where f() is located in the class's vtable are incorrect.
Oftentimes simply recompiling the world (everything!) will help. | This is most probably due to incompatible calling conventions, where the library and the caller have different ideas about stack layout.
Take a look at [MSDN](http://msdn.microsoft.com/en-us/library/984x0h58(VS.80).aspx) for more info. | Function call jumps to the wrong function | [
"",
"c++",
"visual-studio-2008",
"static",
"stack-pointer",
""
] |
As made clear in update 3 on [this answer](https://stackoverflow.com/questions/367440/javascript-associative-array-without-tostring-etc#367454), this notation:
```
var hash = {};
hash[X]
```
does not actually hash the object `X`; it actually just converts `X` to a string (via `.toString()` if it's an object, or some other built-in conversions for various primitive types) and then looks that string up, without hashing it, in "`hash`". Object equality is also not checked - if two different objects have the same string conversion, they will just overwrite each other.
Given this - are there any efficient implementations of hashmaps in JavaScript?
(For example, the second Google result of [`javascript hashmap`](http://www.google.com/search?rlz=1C1GGLS_en-USUS299US303&sourceid=chrome&ie=UTF-8&q=javascript%20hashmap) yields an implementation which is O(n) for any operation. Various other results ignore the fact that different objects with equivalent string representations overwrite each other. | Hash your objects yourself manually, and use the resulting strings as keys for a regular JavaScript dictionary. After all, you are in the best position to know what makes your objects unique. That's what I do.
Example:
```
var key = function(obj){
// Some unique object-dependent key
return obj.totallyUniqueEmployeeIdKey; // Just an example
};
var dict = {};
dict[key(obj1)] = obj1;
dict[key(obj2)] = obj2;
```
This way you can control indexing done by JavaScript without heavy lifting of memory allocation, and overflow handling.
Of course, if you truly want the "industrial-grade solution", you can build a class parameterized by the key function, and with all the necessary API of the container, but … we use JavaScript, and trying to be simple and lightweight, so this functional solution is simple and fast.
The key function can be as simple as selecting right attributes of the object, e.g., a key, or a set of keys, which are already unique, a combination of keys, which are unique together, or as complex as using some cryptographic hashes like in [DojoX encoding](http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/encoding/), or [DojoX UUID](http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/uuid/). While the latter solutions may produce unique keys, personally I try to avoid them at all costs, especially, if I know what makes my objects unique.
**Update in 2014:** Answered back in 2008 this simple solution still requires more explanations. Let me clarify the idea in a Q&A form.
*Your solution doesn't have a real hash. Where is it???*
JavaScript is a high-level language. Its basic primitive ([Object](http://en.wikipedia.org/wiki/JavaScript_syntax#Objects)) includes a hash table to keep properties. This hash table is usually written in a low-level language for efficiency. Using a simple object with string keys we use an efficiently implemented hash table without any efforts on our part.
*How do you know they use a hash?*
There are three major ways to keep a collection of objects addressable by a key:
* Unordered. In this case to retrieve an object by its key we have to go over all keys stopping when we find it. On average it will take n/2 comparisons.
* Ordered.
+ Example #1: a sorted array — doing a binary search we will find our key after ~log2(n) comparisons on average. Much better.
+ Example #2: a tree. Again it'll be ~log(n) attempts.
* Hash table. On average, it requires a constant time. Compare: O(n) vs. O(log n) vs. O(1). Boom.
Obviously JavaScript objects use hash tables in some form to handle general cases.
*Do browser vendors really use hash tables???*
Really.
* Chrome/node.js/[V8](https://github.com/v8/v8/):
[JSObject](https://github.com/v8/v8/blob/master/src/objects.h#L1680). Look for
[NameDictionary](https://github.com/v8/v8/blob/master/src/objects.h#L3618) and
[NameDictionaryShape](https://github.com/v8/v8/blob/master/src/objects.h#L3606) with
pertinent details in [objects.cc](https://github.com/v8/v8/blob/master/src/objects.cc)
and [objects-inl.h](https://github.com/v8/v8/blob/master/src/objects-inl.h).
* Firefox/[Gecko](https://github.com/mozilla/gecko-dev):
[JSObject](https://github.com/mozilla/gecko-dev/blob/master/js/src/jsobj.h#L99),
[NativeObject](https://github.com/mozilla/gecko-dev/blob/master/js/src/vm/NativeObject.h#L349), and
[PlainObject](https://github.com/mozilla/gecko-dev/blob/master/js/src/vm/NativeObject.h#L1238) with pertinent details in
[jsobj.cpp](https://github.com/mozilla/gecko-dev/blob/master/js/src/jsobj.cpp) and
[vm/NativeObject.cpp](https://github.com/mozilla/gecko-dev/blob/master/js/src/vm/NativeObject.cpp).
*Do they handle collisions?*
Yes. See above. If you found a collision on unequal strings, please do not hesitate to file a bug with a vendor.
*So what is your idea?*
If you want to hash an object, find what makes it unique and use it as a key. Do not try to calculate a real hash or emulate hash tables — it is already efficiently handled by the underlying JavaScript object.
Use this key with JavaScript's `Object` to leverage its built-in hash table while steering clear of possible clashes with default properties.
Examples to get you started:
* If your objects include a unique user name — use it as a key.
* If it includes a unique customer number — use it as a key.
+ If it includes unique government-issued numbers like US [SSNs](https://en.wikipedia.org/wiki/Social_Security_number), or a passport number, and your system doesn't allow duplicates — use it as a key.
* If a combination of fields is unique — use it as a key.
+ US state abbreviation + driver license number makes an excellent key.
+ Country abbreviation + passport number is an excellent key too.
* Some function on fields, or a whole object, can return a unique value — use it as a key.
*I used your suggestion and cached all objects using a user name. But some wise guy is named "toString", which is a built-in property! What should I do now?*
Obviously, if it is even remotely possible that the resulting key will exclusively consists of Latin characters, you should do something about it. For example, add any non-Latin Unicode character you like at the beginning or at the end to un-clash with default properties: "#toString", "#MarySmith". If a composite key is used, separate key components using some kind of non-Latin delimiter: "name,city,state".
In general, this is the place where we have to be creative and select the easiest keys with given limitations (uniqueness, potential clashes with default properties).
Note: unique keys do not clash by definition, while potential hash clashes will be handled by the underlying `Object`.
*Why don't you like industrial solutions?*
IMHO, the best code is no code at all: it has no errors, requires no maintenance, easy to understand, and executes instantaneously. All "hash tables in JavaScript" I saw were >100 lines of code, and involved multiple objects. Compare it with: `dict[key] = value`.
Another point: is it even possible to beat a performance of a primordial object written in a low-level language, using JavaScript and the very same primordial objects to implement what is already implemented?
*I still want to hash my objects without any keys!*
We are in luck: [ECMAScript 6](https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015) (released in June 2015) defines [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set).
Judging by the definition, they can use an object's address as a key, which makes objects instantly distinct without artificial keys. OTOH, two different, yet identical objects, will be mapped as distinct.
Comparison breakdown from [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared):
> Objects are similar to Maps in that both let you set keys to values,
> retrieve those values, delete keys, and detect whether something is
> stored at a key. Because of this (and because there were no built-in
> alternatives), Objects have been used as Maps historically; however,
> there are important differences that make using a Map preferable in
> certain cases:
>
> * The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
> * The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of
> insertion.
> * You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
> * A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion
> and iterating over them.
> * An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can
> be bypassed by using map = Object.create(null), but this is seldom
> done.
> * A Map may perform better in scenarios involving frequent addition and removal of key pairs. | # Problem description
JavaScript has no built-in general *map* type (sometimes called *associative array* or *dictionary*) which allows to access arbitrary values by arbitrary keys. JavaScript's fundamental data structure is the *object*, a special type of map which only accepts strings as keys and has special semantics like prototypical inheritance, getters and setters and some further voodoo.
When using objects as maps, you have to remember that the key will be converted to a string value via `toString()`, which results in mapping `5` and `'5'` to the same value and all objects which don't overwrite the `toString()` method to the value indexed by `'[object Object]'`. You might also involuntarily access its inherited properties if you don't check `hasOwnProperty()`.
JavaScript's built-in *array* type does not help one bit: JavaScript arrays are not associative arrays, but just objects with a few more special properties. If you want to know why they can't be used as maps, [look here](http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/).
# Eugene's Solution
[Eugene Lazutkin already described](https://stackoverflow.com/questions/368280/javascript-hashmap-equivalent/368504#368504) the basic idea of using a custom hash function to generate unique strings which can be used to look up the associated values as properties of a dictionary object. This will most likely be the fastest solution, because objects are internally implemented as *hash tables*.
* **Note:** Hash tables (sometimes called *hash maps*) are a particular implementation of the map concept using a backing array and lookup via numeric hash values. The runtime environment might use other structures (such as *search trees* or *skip lists*) to implement JavaScript objects, but as objects are the fundamental data structure, they should be sufficiently optimised.
In order to get a unique hash value for arbitrary objects, one possibility is to use a global counter and cache the hash value in the object itself (for example, in a property named `__hash`).
A hash function which does this is and works for both primitive values and objects is:
```
function hash(value) {
return (typeof value) + ' ' + (value instanceof Object ?
(value.__hash || (value.__hash = ++arguments.callee.current)) :
value.toString());
}
hash.current = 0;
```
This function can be used as described by Eugene. For convenience, we will further wrap it in a `Map` class.
# My `Map` implementation
The following implementation will additionally store the key-value-pairs in a doubly linked list in order to allow fast iteration over both keys and values. To supply your own hash function, you can overwrite the instance's `hash()` method after creation.
```
// Linking the key-value-pairs is optional.
// If no argument is provided, linkItems === undefined, i.e. !== false
// --> linking will be enabled
function Map(linkItems) {
this.current = undefined;
this.size = 0;
if(linkItems === false)
this.disableLinking();
}
Map.noop = function() {
return this;
};
Map.illegal = function() {
throw new Error("illegal operation for maps without linking");
};
// Map initialisation from an existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
var map = new Map;
for(var prop in obj) {
if(foreignKeys || obj.hasOwnProperty(prop))
map.put(prop, obj[prop]);
}
return map;
};
Map.prototype.disableLinking = function() {
this.link = Map.noop;
this.unlink = Map.noop;
this.disableLinking = Map.noop;
this.next = Map.illegal;
this.key = Map.illegal;
this.value = Map.illegal;
this.removeAll = Map.illegal;
return this;
};
// Overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
return (typeof value) + ' ' + (value instanceof Object ?
(value.__hash || (value.__hash = ++arguments.callee.current)) :
value.toString());
};
Map.prototype.hash.current = 0;
// --- Mapping functions
Map.prototype.get = function(key) {
var item = this[this.hash(key)];
return item === undefined ? undefined : item.value;
};
Map.prototype.put = function(key, value) {
var hash = this.hash(key);
if(this[hash] === undefined) {
var item = { key : key, value : value };
this[hash] = item;
this.link(item);
++this.size;
}
else this[hash].value = value;
return this;
};
Map.prototype.remove = function(key) {
var hash = this.hash(key);
var item = this[hash];
if(item !== undefined) {
--this.size;
this.unlink(item);
delete this[hash];
}
return this;
};
// Only works if linked
Map.prototype.removeAll = function() {
while(this.size)
this.remove(this.key());
return this;
};
// --- Linked list helper functions
Map.prototype.link = function(item) {
if(this.size == 0) {
item.prev = item;
item.next = item;
this.current = item;
}
else {
item.prev = this.current.prev;
item.prev.next = item;
item.next = this.current;
this.current.prev = item;
}
};
Map.prototype.unlink = function(item) {
if(this.size == 0)
this.current = undefined;
else {
item.prev.next = item.next;
item.next.prev = item.prev;
if(item === this.current)
this.current = item.next;
}
};
// --- Iterator functions - only work if map is linked
Map.prototype.next = function() {
this.current = this.current.next;
};
Map.prototype.key = function() {
return this.current.key;
};
Map.prototype.value = function() {
return this.current.value;
};
```
# Example
The following script,
```
var map = new Map;
map.put('spam', 'eggs').
put('foo', 'bar').
put('foo', 'baz').
put({}, 'an object').
put({}, 'another object').
put(5, 'five').
put(5, 'five again').
put('5', 'another five');
for(var i = 0; i++ < map.size; map.next())
document.writeln(map.hash(map.key()) + ' : ' + map.value());
```
generates this output:
```
string spam : eggs
string foo : baz
object 1 : an object
object 2 : another object
number 5 : five again
string 5 : another five
```
# Further considerations
[PEZ suggested](https://stackoverflow.com/questions/368280/javascript-hashmap-equivalent/384517#384517) to overwrite the `toString()` method, presumably with our hash function. This is not feasible, because it doesn't work for primitive values (changing `toString()` for primitives is a *very* bad idea). If we want `toString()` to return meaningful values for arbitrary objects, we would have to modify `Object.prototype`, which some people (myself not included) consider *verboten*.
---
The current version of my `Map` implementation as well as other JavaScript goodies [can be obtained from here](http://mercurial.intuxication.org/hg/js-hacks/raw-file/tip/map.js). | JavaScript hashmap equivalent | [
"",
"javascript",
"data-structures",
"language-features",
"hashmap",
""
] |
I'm using `FontMetrics.getHeight()` to get the height of the string, but it gives me a wrong value, cutting off the descenders of string characters. Is there a better function I can use? | The `getStringBounds()` method below is based on the `GlyphVector` for the current `Graphics2D` font, which works very well for one line string of text:
```
public class StringBoundsPanel extends JPanel
{
public StringBoundsPanel()
{
setBackground(Color.white);
setPreferredSize(new Dimension(400, 247));
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// must be called before getStringBounds()
g2.setFont(getDesiredFont());
String str = "My Text";
float x = 140, y = 128;
Rectangle bounds = getStringBounds(g2, str, x, y);
g2.setColor(Color.red);
g2.drawString(str, x, y);
g2.setColor(Color.blue);
g2.draw(bounds);
g2.dispose();
}
private Rectangle getStringBounds(Graphics2D g2, String str,
float x, float y)
{
FontRenderContext frc = g2.getFontRenderContext();
GlyphVector gv = g2.getFont().createGlyphVector(frc, str);
return gv.getPixelBounds(null, x, y);
}
private Font getDesiredFont()
{
return new Font(Font.SANS_SERIF, Font.BOLD, 28);
}
private void startUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) throws Exception
{
final StringBoundsPanel tb = new StringBoundsPanel();
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
tb.startUI();
}
});
}
}
```
Note that I've omitted the imports for clarity.
The result:
 | What makes you think it returns the wrong value? It's far more probable that your expectation of what it returns does not match the specification. Note that it's perfectly fine if some glyphs in the Font go over or under those values.
`getMaxDescent()` and `getMaxAscent()` should tell you the absolute maximum values of those fields for any glyph in the Font.
If you want to know the metrics for a specific String, then you definitely want to call `getLineMetrics()`. | How to get real string height in Java? | [
"",
"java",
"fonts",
"awt",
""
] |
Does anyone know of a Javascript based [HAML](http://haml.hamptoncatlin.com/) editor out there? I'm looking for for something like [TinyMCE](http://tinymce.moxiecode.com/) that just understands HAML (so it does indenting and highlighting correctly)
I'm thinking of using an editor like this for a dynamic website I'm building.
**Clarification**
The site I am building allows the users to define layouts(in the rails sense) and css. So finer grain control than textile and markdown is required, I know I can include raw html in markdown but haml is so much prettier. | I noticed this question hasn't been answered in a while. While this isn't a complete answer, you may want to look at [MarkItUp](http://markitup.jaysalvat.com/home/). Its specifically *not* a WYSIWYG editor, but rather, an extensible and friendly markup editor. It doesn't support HAML directly, but its fairly easy to extend it to support different languages. It can also do AJAX round trips to the server so you can preview the markup using a server side renderer. | HAML was designed as a more elegant way to define page structure; It was not intended to be used for formatting text, like what you're asking it to do.
In this case, you're probably better off using something like [Markdown](http://daringfireball.net/projects/markdown/) or [Textile](http://www.textism.com/tools/textile/). Both of these already have WYSIWYGs ([for Markdown](http://wmd-editor.com/), [for Textile](http://slateinfo.blogs.wvu.edu/plugins/textile_editor_helper) ([forked version](http://github.com/felttippin/textile-editor-helper/tree/master))), and Haml's got built-in filters to convert it into HTML.
e.g.:
```
#content
:markdown
@post.body
```
(Haml's wonderful space-indentation will even be preserved on output!) | Javascript HAML editor | [
"",
"javascript",
"haml",
""
] |
I'm trying to write a function that is able to determine whether a string contains a real or an integer value.
This is the simplest solution I could think of:
```
int containsStringAnInt(char* strg){
for (int i =0; i < strlen(strg); i++) {if (strg[i]=='.') return 0;}
return 1;
}
```
But this solution is really slow when the string is long... Any optimization suggestions?
Any help would really be appreciated! | You are using strlen, which means you are not worried about unicode. In that case why to use strlen or strchr, just check for '\0' (Null char)
```
int containsStringAnInt(char* strg){
for (int i =0;strg[i]!='\0'; i++) {
if (strg[i]=='.') return 0;}
return 1; }
```
Only one parsing through the string, than parsing through the string in each iteration of the loop. | What's the syntax of your real numbers?
1e-6 is valid C++ for a literal, but will be passed as integer by your test. | Fastest way to determine whether a string contains a real or integer value | [
"",
"c++",
"optimization",
"parsing",
""
] |
Why would I want to use PHP's [filter](http://www.php.net/filter) library? Why wouldn't I?
It seems to try and do a bit of clean-up (it's awful when you have to work with regular expressions), but on the other hand function naming and parameter constants seem to be a disaster, if you ask me. It must have been included in PHP for a reason, but I just don't seem to like it. What am I missing?
*Later edit:*
Regarding GaryF's answer, I wish to explain a bit why I don't like this function.
This isn't about using it in "my case" if it fits. This is about using it wherever it fits. There's a high chance of needing a filter that won't fit PHP's functions, so I'll have to create my own filter. In that case, the application will use two completely different kinds of functions for data filtering. I consider that to be a much worse practice than just inventing a better wheel. | My stance is that the concept of filtering input data is flawed on a conceptual level. See my reply to the almost similar question [What’s the best method for sanitizing user input with PHP?](https://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php#130323) | Probably the best resource for this is the tutorial linked to from the PHP manual page: <http://devolio.com/blog/archives/413-Data-Filtering-Using-PHPs-Filter-Functions-Part-one.html>
It's decent enough for simple filtering, but if you don't find your use-case on that page it probably isn't for you. | PHP filter() function - why? | [
"",
"php",
""
] |
I'm trying to use SDL in C++ with Visual Studio 2008 Express. The following program compiles but does not link:
```
#include <SDL.h>
int main(int argc, char *argv[])
{
return 0;
}
```
The link error is:
```
LINK : fatal error LNK1561: entry point must be defined
```
I get this regardless of how or if I link with SDL.lib and SDLmain.lib. Defining `main` as `main()` or `SDL_main()` gives the same error, with or without `extern "C"`.
Edit: I solved this by not including SDL.h in main.cpp - a refactoring I did independent of the problem. A similar solution would be to `#undef main` right before defining the function. | I don't have VC++ available at the moment, but I have seen this issue several times.
You need to create a Win32 project as opposed to a console project. A Win32 project expects a [WinMain](http://msdn.microsoft.com/en-us/library/ms633559(VS.85).aspx) function as a program entry point. SDLmain.lib contains this entry point and the SDL\_main.h header file has a macro that remaps your main function to SDL\_main. This function is called by the entry point in the SDLmain library.
The main function must have the following signature:
```
int main(int argc, char *argv[])
```
It is also required to include SDL.h before the declaration of your main function, and you need to link to both SDL.lib and SDLmain.lib.
It looks like you are doing this. **So, my guess is that you have a console project setup.** Therefore, **the linker is looking for a main function to call, but it is getting remapped to SDL\_main by the macro SDL\_main.h**. So, the linker can't find an entry point and gives up! | To me it helped to add the following lines before main():
```
#ifdef _WIN32
#undef main
#endif
```
[German Wikipedia](http://de.wikibooks.org/wiki/SDL:_Die_erste_SDL-Anwendung) also suggests to add these lines instead:
```
#ifdef _WIN32
#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")
#endif
```
Though I still had link errors when I tried second solution. | How do you get a minimal SDL program to compile and link in visual studio 2008 express? | [
"",
"c++",
"visual-studio",
"sdl",
""
] |
I am not talking about the highlight colors but the actual colors. I got a color scheme with light background color but the braces/parentheses are barely visible. Anyone knows how to change this?
Btw this is for C# because C++ seems to color braces/parentheses using operator color. | Tools > Options > Fonts and Colors > "Display Items" : Plain Text
Unfortunately this changes a lot more than just braces but its the only way to target them as far as I know. | The Visual Studio 2014 CTP 14.0.22129 dark theme blacked-out the brackets and semi-colon for some reason. I was able to fix this by changing the foreground color of the "Punctuation" display item. | How to change the braces/parenthesis colors in Visual Studio | [
"",
"c#",
"visual-studio",
"ide",
""
] |
I am going to try to build a PHP website using a framework for the first time, and after some research here and there, I've decided to try to use **[Kohana](http://kohanaframework.org)**
I downloaded the source from their website, and ran the downloaded stuff on my web server, and was then greeted with a 'Welcome to Kohana!' page, and nothing more...
I've tried to find some beginner tutorials on the web as regard this particular framework, but to my surprise, came up with almost nothing (*only [this one](http://lee.hambley.name/kohana-tutorial), but it's not a great deal of help*)
I am not new to PHP and neither am I new to the MVC concept, but I am very new to PHP Frameworks...so can anyone **point me to a Kohana tutorial somewhere on the web that will help me get started in building my website using this framework, from scratch ?**
P.S. As I said, I want a *beginners* tutorial as regarding this case.
**[UPDATE]**
I am currently reading the [Official Guide](http://kohanaframework.org/3.3/guide/kohana/install)...we'll see how that goes. | The "Kohana Tutorial" pages are pants. Not so much for their content, but for the fact that they have a pretty damn unorganised wordpress blog and finding useful info isn't exactly made easy. What they need is a post/page at <http://learn.kohanaphp.com> that lists the most important tutorials, rather than forcing you to wade through the whole blog.
Anyway, rant over, I'd start here:
<http://zacklive.com/hello-world-tutorial-for-kohana/15/>
Then:
<http://learn.kohanaphp.com/2008/03/26/blog-tutorial-1/>
<http://learn.kohanaphp.com/2008/03/28/blog-tutorial-part-2/>
Other articles of interest:
<http://www.ninjapenguin.co.uk/blog/2008/06/21/kohana-pagination-tutorial/>
<http://learn.kohanaphp.com/2008/04/25/using-auto_modeler-to-write-quicker-code/>
<http://www.ninjapenguin.co.uk/blog/2008/06/29/practical-kohana-hooks-example-phpids/>
<http://learn.kohanaphp.com/2008/04/14/5-tips-to-help-you-find-something-youre-looking-for-in-kohana/>
And, of course, Google. | I had exactly the same problem! After a few searches I found the Kohaha101.pdf. This guide/tutorial really got me started!
Link:[<http://pixelpeter.com/kohana/kohana101.pdf>[1](http://pixelpeter.com/kohana/kohana101.pdf)
Good luck and enjoy Kohana! | Searching for a Kohana Beginner's Tutorial for PHP | [
"",
"php",
"frameworks",
"kohana",
""
] |
I have a table in SQL Server 2005 which has three columns:
```
id (int),
message (text),
timestamp (datetime)
```
There is an index on timestamp and id.
I am interested in doing a query which retrieves all messages for a given date, say '12/20/2008'. However I know that simply doing where timestamp='12/20/2008' won't give me the correct result because the field is a datetime field.
Somebody had recommended using the DATEPART function and pulling the year, month, and day out of timestamp and verifying that these are equal to 2008, 12, and 20, respectively. It looks like this would not use the index I have on timestamp and would end up doing a full table scan.
So what is the best way to construct my query so that I am taking advantage of the index that I have created? | ```
-- avoid re-calculating @MyDate +1 for every row
DECLARE @NextDay DateTime
Set @NextDay = @MyDate + 1
SELECT
-- ...
WHERE [timestamp] >= @MyDate AND [timestamp] < @NextDay
``` | The use of two datetime variables has always worked infallibly in my experience. The issue of the resolution seems highly unlikely. The important fact to remember, however, is that a range (of any type) includes both end points. So you can't test using BETWEEN on two dates, because it will include both. Rather use something like
datefield >= @startdate AND datefield < @enddate
[The Manual.](http://msdn.microsoft.com/en-us/library/aa225976.aspx)
C'mon folks - the documentation for this isn't *that* hard to find. :D | How to query SQL Server table based on a specific date | [
"",
"sql",
"sql-server",
"database",
""
] |
I am reading file from ResultSet and it's required to save file into Oracle Database.
```
...
ResultSet rs = ...
java.sql.Blob myfile = rs.getBlob("field")
java.io.OutputStream os = ((oracle.sql.BLOB) myfile).getBinaryOutputStream();
```
I get get this error message
```
java.lang.ClassCastException
```
Any one have solution to this? Thanks! | I have found the solution. I'd like to share with those who has this problem.
The code to get outputstream from oracle blob is:
```
java.io.OutputStream os = ((oracle.sql.BLOB) myBlob).setBinaryStream(1L);
```
setBinaryStream() is actually returning java.io.OutputStream object | `java.sql.Blob` [is an interface](http://java.sun.com/javase/6/docs/api/java/sql/Blob.html). Presumably the implementation returned in your `ResultSet` is a different implementation to `oracle.sql.BLOB`?
What does `myfile.getClass()` return? | Why I cannot cast oracle BLOB from native java Blob | [
"",
"java",
"oracle",
"blob",
"classcastexception",
""
] |
I'm currently trying to implement a class to handle secure communications between instances of my app using RSACrytoServiceProveider class.
First question : is it a good idea implement a single class to handle sender/reciever roles or should i split the roles into individual classes ?. This is what i have done so far:
```
using System;
using System.Text;
using System.Security.Cryptography;
namespace Agnus.Cipher
{
public class RSA
{
private byte[] plaintextBytes;
private byte[] ciphertextBytes;
private RSACryptoServiceProvider rSAProviderThis;
private RSACryptoServiceProvider rSAProviderOther;
public string PublicKey
{
get { return rSAProviderThis.ToXmlString(false); }
}
public RSA()
{
rSAProviderThis = new RSACryptoServiceProvider { PersistKeyInCsp = true };
plaintextBytes = Encoding.Unicode.GetBytes(PublicKey);
}
public void InitializeRSAProviderOther(string parameters)
{
rSAProviderOther.FromXmlString(parameters);
}
public byte[] Encrypt()
{
return rSAProviderThis.Encrypt(plaintextBytes, true);
}
public byte[] Decrypt()
{
return rSAProviderThis.Decrypt(ciphertextBytes, true);
}
public byte[] Sign()
{
using (SHA1Managed SHA1 = new SHA1Managed())
{
byte[] hash = SHA1.ComputeHash(ciphertextBytes);
byte[] signature = rSAProviderThis.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
return signature;
}
}
public void Verify()
{
throw new NotImplementedException();
}
}
}
```
Second question : how do i send and receive data to be fed into the class ? i'm a green horn in this field, pointers would be appreciated. | I would make the encrypt/sign/decrypt/verify methods take parameters for the data rather than having member variables for them. Having member variables for the key and provider seems okay though. Basically I'd expect to use the same key multiple times but not the same data.
I'd also make it immutable - make all the variables readonly, taking all the parameters you'll need for the providers in the constructor instead of having a separate initialisation method.
Beyond that, it seems okay to wrap the functionality in a simpler API for your needs though, yes. | I have made some adjustments, here is what the implementation looks like:
```
using System;
using System.Security.Cryptography;
namespace Agnus.Cipher
{
public class RSA : IDisposable
{
private RSACryptoServiceProvider rSAProviderThis;
private RSACryptoServiceProvider rSAProviderOther = null;
public string PublicKey
{
get { return rSAProviderThis.ToXmlString(false); }
}
public RSA()
{
rSAProviderThis = new RSACryptoServiceProvider { PersistKeyInCsp = true };
}
public void InitializeRSAProviderOther(string parameters)
{
rSAProviderOther.FromXmlString(parameters);
}
public byte[] Encrypt(byte[] plaintextBytes)
{
return rSAProviderThis.Encrypt(plaintextBytes, true);
}
public string Decrypt(byte[] ciphertextBytes)
{
try
{
return Convert.ToBase64String( rSAProviderThis.Decrypt(ciphertextBytes, true));
}
catch (CryptographicException ex)
{
Console.WriteLine("Unable to decrypt: " + ex.Message + " " + ex.StackTrace);
}
finally
{
this.Dispose();
}
return string.Empty;
}
public string SignData(byte[] ciphertextBytes)
{
string signature = GenerateSignature(ciphertextBytes, rSAProviderThis);
return signature;
}
private string GenerateSignature(byte[] ciphertextBytes, RSACryptoServiceProvider provider)
{
using (SHA1Managed SHA1 = new SHA1Managed())
{
byte[] hash = SHA1.ComputeHash(ciphertextBytes);
string signature = Convert.ToBase64String(provider.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")));
return signature;
}
}
public string VerifySignature(byte[] ciphertextBytes, string parameters, string signatureToVerify)
{
InitializeRSAProviderOther(parameters);
string actualSignature = GenerateSignature(ciphertextBytes, rSAProviderOther);
if (actualSignature.Equals(signatureToVerify))
{
//verification successful
string decryptedData = this.Decrypt(ciphertextBytes);
return decryptedData;
//decryptedData is a symmetric key
}
else
{
//verification unsuccessful
//end session
}
return string.Empty;
}
#region IDisposable Members
public void Dispose()
{
if (rSAProviderOther != null)
{
rSAProviderOther.Clear();
}
rSAProviderThis.Clear();
GC.SuppressFinalize(this);
}
#endregion
}
}
```
you guys still haven't said anything about how communication is going to be established (i'm thinking sockets). Please enlighten me. | Implementing RSA in C# | [
"",
"c#",
"rsa",
"rsacryptoserviceprovider",
""
] |
```
game.h needs:
- packet.h
- socket.h
socket.h needs:
- game.h
```
The problem comes when I try to include `socket.h` into `game.h`, because `socket.h` has `game.h` included already. How do I solve these kind of problems? | The usual way, use #ifdef and #define in your header files
inside game.h:
```
#ifndef GAME_H
#define GAME_H
.. rest of your header file here
#endif
```
This way, the contents will be read multiple times, but only defined once.
**Edit**: Removed underscores at start and end of identifier per comments. | The key is forward declaration. Take the stuff from `game.h` that is required in `socket.h` (or vice-versa) and forward-declare it in yet another header, e.g. `game_forwards.h`. As an example, consider the following:
```
// game_fwd.h
#ifndef GAME_FWD_H
#define GAME_FWD_H
class game;
#endif // ndef GAME_FWD_H
// game.h
#ifndef GAME_H
#define GAME_H
#include "socket.h"
class game {
socket* m_sck;
};
#endif // ndef GAME_H
// socket.h
#ifndef SOCKET_H
#define SOCKET_H
#include "game_fwd.h"
class socket {
game* m_game;
};
#endif // ndef SOCKET_H
```
Clearly, for this to work, it's important to separate interface and implementation. | How do I solve circular includes between header files? | [
"",
"c++",
"header-files",
""
] |
I still feel C++ offers some things that can't be beaten. It's not my intention to start a flame war here, please, if you have strong opinions about not liking C++ don't vent them here. I'm interested in hearing from C++ gurus about why they stick with it.
I'm particularly interested in aspects of C++ that are little known, or underutilised. | I have stayed with C++ as it is still the highest performing general purpose language for applications that need to combine efficiency *and* complexity. As an example, I write real time surface modelling software for hand-held devices for the surveying industry. Given the limited resources, Java, C#, etc... just don't provide the necessary performance characteristics, whereas lower level languages like C are much slower to develop in given the weaker abstraction characteristics. The range of levels of abstraction available to a C++ developer is huge, at one extreme I can be overloading arithmetic operators such that I can say something like *MaterialVolume = DesignSurface - GroundSurface* while at the same time running a number of different heaps to manage the memory most efficiently for my app on a specific device. Combine this with a wealth of freely available source for solving pretty much any common problem, and you have one heck of a powerful development language.
Is C++ still the optimal development solution for most problems in most domains? Probably not, though at a pinch it can still be used for most of them. Is it still the best solution for efficient development of high performance applications? IMHO without a doubt. | **RAII / deterministic finalization**. No, garbage collection is not *just as good* when you're dealing with a scarce, shared resource.
**Unfettered access to OS APIs**. | What can C++ do that is too hard or messy in any other language? | [
"",
"c++",
""
] |
Does anyone know how to disable an ASP.NET validator using JavaScript?
I'm using javascript style.display = 'none' to disable parts of a web page. However these disabled parts have asp.net validators that are still firing and I need to disable then without doing a round trip to the server.
Thanks. | Use this snippet:
```
function doSomething()
{
var myVal = document.getElementById('myValidatorClientID');
ValidatorEnable(myVal, false);
}
``` | This is an old question but surprised the following answer it not given. I implemented it using of the comments above and works flawlessly
```
# enable validation
document.getElementById('<%=mytextbox.ClientID%>').enabled = true
#disable validation
document.getElementById('<%=mytextbox.ClientID%>').enabled = false
```
This implementation can be someone tricky because remember if there is an error in javascript, the code will exit but you wont get any errors. Some helpful points
1. Make sure you can set a break point *and* can single step through the code. If not restart browser.
2. Set the break point at the start of the function where you put this code. Step through the code, if there is an error, the code will exit and you won't be able to step into the code.
3. In firefox Firebug, you can type the entire javascript statement in console tab to see what your statement returns. Most importantly you want to check for not null values of controls. | Disable ASP.NET validators with JavaScript | [
"",
"asp.net",
"javascript",
"validation",
""
] |
How can you check whether a **string** is **convertible** to an **int?**
Let's say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the **string** or use the parsed **int** value instead.
*In JavaScript we had this [parseInt()](http://www.w3schools.com/jsref/jsref_parseInt.asp) function. If the string **couldn't be parsed**, it would get back **NaN**.* | `Int32.TryParse(String, Int32)` - <http://msdn.microsoft.com/en-us/library/f02979c7.aspx>
```
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
``` | Could you not make it a little more elegant by running the tryparse right into the if?
Like so:
```
if (Int32.TryParse(value, out number))
Console.WriteLine("Converted '{0}' to {1}.", value, number);
``` | Convert string to int and test success in C# | [
"",
"c#",
"string",
"parsing",
"int",
""
] |
I want to do something like this:
```
c:\data\> python myscript.py *.csv
```
and pass all of the .csv files in the directory to my python script (such that `sys.argv` contains `["file1.csv", "file2.csv"]`, etc.)
But `sys.argv` just receives `["*.csv"]` indicating that the wildcard was not expanded, so this doesn't work.
I feel like there is a simple way to do this, but can't find it on Google. Any ideas? | You can use the glob module, that way you won't depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards :-) ).
```
from glob import glob
filelist = glob('*.csv') #You can pass the sys.argv argument
``` | In Unix, the shell expands wildcards, so programs get the expanded list of filenames. Windows doesn't do this: the shell passes the wildcards directly to the program, which has to expand them itself.
Vinko is right: the glob module does the job:
```
import glob, sys
for arg in glob.glob(sys.argv[1]):
print "Arg:", arg
``` | Passing arguments with wildcards to a Python script | [
"",
"python",
"windows",
"command-line",
"arguments",
""
] |
I work on a project that uses multiple open source Java libraries. When upgrades to those libraries come out, we tend to follow a conservative strategy:
1. if it ain't broke, don't fix it
2. if it doesn't have new features we want, ignore it
We follow this strategy because we usually don't have time to put in the new library and thoroughly test the overall application. (Like many software development teams we're always behind schedule on features we promised months ago.)
But, I sometimes wonder if this strategy is wise given that some performance improvements and a large number of bug fixes usually come with library upgrades. (i.e. "Who knows, maybe things will work better in a way we don't foresee...")
What criteria do you use when you make these types of decisions in your project? | I've learned enough lessons to do the following:
1. Check the library's change list. What did they fix? Do I care? If there isn't a change list, then the library isn't used in my project.
2. What are people posting about on the Library's forum? Are there a rash of posts starting shortly after release pointing out obvious problems?
3. Along the same vein as number 2, don't upgrade immediately. EVERYONE has a bad release. I don't intend to be the first to get bit with that little bug. (anymore that is). This doesn't mean wait 6 months either. Within the first month of release you should know the downsides.
4. When I decide to go ahead with an upgrade; test, test test. Here automated testing is extremely important.
**EDIT:** I wanted to add one more item which is at least as important, and maybe more so than the others.
* What breaking changes were introduced in this release? In other words, is the library going off in a different direction? If the library is deprecating or replacing functionality you will want to stay on top of that. | Important: Avoid [Technical Debt](http://en.wikipedia.org/wiki/Technical_debt).
"If it ain't broke, don't upgrade" is a crazy policy that leads to software so broken that no one can fix it.
Rash, untested changes are a bad idea, but not as bad as accumulating technical debt because it appears cheaper in the short run.
Get a "nightly build" process going so you can continuously test all changes -- yours as well as the packages on which you depend.
Until you have a continuous integration process, you can do quarterly major releases that include infrastructure upgrades.
Avoid Technical Debt. | How do you decide when to upgrade a library in your project? | [
"",
"java",
"versioning",
""
] |
Is it recommended to set member variables of a base class to protected, so that subclasses can access these variables? Or is it more recommended to set the member variables to private and let the subclasses get or set the varible by getters and setters?
And if it is recommended to use the getters and setters method, when are protected variables used? | This is very *similar* to [this question](https://stackoverflow.com/questions/355787), about whether to access information within the same class via properties or direct access. It's probably worth reading all those answers too.
Personally, I don't like any fields to be non-private with the occasional exception of static readonly fields with immutable values (whether const or not). To me, properties just give a better degree of encapsulation. How data is stored is an *implementation* decision, not an *API* decision (unlike properties). Why should class Foo deriving from class Bar care about the *implementation* of class Bar?
In short, I'd always go for properties, and I don't use protected variables for anything other than throwaway test code.
With automatically implemented properties in C# 3.0, it's easier than ever before to turn fields into properties. There's precious little reason *not* to do it. | Classes in other assemblies can derive from your unsealed classes and can access protected fields. If you one day decide to make those fields into properties, those classes in other assemblies will need to be recompiled to work with the new version of your assembly. That's called "breaking binary compatibility", and is perhaps the one solid reason why you shouldn't ever expose fields outside of an assembly. | c# using setters or getters from base class | [
"",
"c#",
"variables",
"member",
"protected",
""
] |
Besides the fact that `$_REQUEST` reads from cookies, are there any reasons why I should use `$_GET` and `$_POST` instead of `$_REQUEST`? What are theoretical and practical reasons for doing so? | I use $\_REQUEST when I just want certain data from the user to return certain data.
Never use $\_REQUEST when the request will have side effects. Requests that produce side effects should be POST (for semantic reasons, and also because of basic CSRF stuff, a false img tag can hit any GET endpoint without a user even knowing).
$\_GET should be used when GETing or POSTing to a page will produce different results. | > Besides the fact that $\_REQUEST reads from cookies
Besides the fact that this is undefined (It's configurable on a per-installation level), the problem using `$_REQUEST` is that it over-simplifies things. There is (or should be) a semantic difference between a GET request and a POST request. Thus it should matter to your application if you get input from one source or the other. This is how the HTTP protocol is defined, so by ignoring it, you are undermining the protocol, which makes your application less interoperable. It's the same type argument that can be made for using semantic HTML markup, rather than presentation-oriented markup. Or more generally, following the intentions of a protocol rather than just doing whatever works in the concrete situation. | Why should I use $_GET and $_POST instead of $_REQUEST? | [
"",
"php",
"security",
""
] |
I've got a bunch of stateless ejb 3.0 beans calling each other in chain.
Consider, BeanA.do(message) -> BeanB.do() -> BeanC.do() -> BeanD.do().
Now i'd like to access message data from BeanD.do(). Obvious solution is to pass message as a parameter to all that do() calls (actually that's how it works now), but i want some nicer solution.
Is there some kind of call context? And can i associate arbitrary data with it?
What i'd like to do, is simply put message in BeanA.do(message) to some local storage associated with bean function call and retrieve it in BeanD.do().
Any ideas? | i don't believe there is anything in the EJB spec that provides that functionality. If you are on a specific app server, you may be able to use app server specific stuff (i think JBoss allows you to add stuff to a call context). you also may be able to fake something up using JNDI.
personally, this seems (to me) like a poor design. i could see doing this if you had some code in the middle you could not control, but why do it otherwise? you are making your code logic very hard to follow because you have a bunch of "magic" data which just appears in your function. | You could have a class with static get/set methods that access a static ThreadLocal field. However I would take james' advice and consider very carefully if you want to couple your EJBs to that other class. Definitely double-check your app server docs as I'm not sure if using ThreadLocals in an EJB environment is supported. | Associate arbitrary data with ejb call context | [
"",
"java",
"jakarta-ee",
"ejb-3.0",
""
] |
Given the following table in SQL Server 2005:
```
ID Col1 Col2 Col3
-- ---- ---- ----
1 3 34 76
2 32 976 24
3 7 235 3
4 245 1 792
```
What is the best way to write the query that yields the following result (i.e. one that yields the final column - a column containing the minium values out of Col1, Col2, and Col 3 **for each row**)?
```
ID Col1 Col2 Col3 TheMin
-- ---- ---- ---- ------
1 3 34 76 3
2 32 976 24 24
3 7 235 3 3
4 245 1 792 1
```
***UPDATE:***
For clarification (as I have said in the coments) in the real scenario the database is **properly normalized**. These "array" columns are not in an actual table but are in a result set that is required in a report. And the new requirement is that the report also needs this MinValue column. I can't change the underlying result set and therefore I was looking to T-SQL for a handy "get out of jail card".
I tried the CASE approach mentioned below and it works, although it is a bit cumbersome. It is also more complicated than stated in the answers because you need to cater for the fact that there are two min values in the same row.
Anyway, I thought I'd post my current solution which, given my constraints, works pretty well. It uses the UNPIVOT operator:
```
with cte (ID, Col1, Col2, Col3)
as
(
select ID, Col1, Col2, Col3
from TestTable
)
select cte.ID, Col1, Col2, Col3, TheMin from cte
join
(
select
ID, min(Amount) as TheMin
from
cte
UNPIVOT (Amount for AmountCol in (Col1, Col2, Col3)) as unpvt
group by ID
) as minValues
on cte.ID = minValues.ID
```
I'll say upfront that I don't expect this to offer the best performance, but given the circumstances (I can't redesign all the queries just for the new MinValue column requirement), it is a pretty elegant "get out of jail card". | There are likely to be many ways to accomplish this. My suggestion is to use Case/When to do it. With 3 columns, it's not too bad.
```
Select Id,
Case When Col1 < Col2 And Col1 < Col3 Then Col1
When Col2 < Col1 And Col2 < Col3 Then Col2
Else Col3
End As TheMin
From YourTableNameHere
``` | Using `CROSS APPLY`:
```
SELECT ID, Col1, Col2, Col3, MinValue
FROM YourTable
CROSS APPLY (SELECT MIN(d) AS MinValue FROM (VALUES (Col1), (Col2), (Col3)) AS a(d)) A
```
[SQL Fiddle](http://sqlfiddle.com/#!3/dbbd3/1) | What's the best way to select the minimum value from several columns? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
"min",
""
] |
I'm trying to convert Matt Berseth's '[YUI Style Yes/No Confirm Dialog](http://mattberseth.com/blog/2007/10/yui_style_yesno_confirm_dialog.html)' so I can use it with the jQuery blockUI plugin.
I have to admit I'm no CSS guru but I thought this would pretty easy even for me....except 10hrs later I'm at a loss as to why I can't get the blasted thing to work.
The problem is that I can't seem to get the 'confirmDialogue' DIV to centre on the page without some artifacts showing above it. Alternatively if I reset blockUI's CSS settings by doing....:
```
$.blockUI.defaults.css = {};
```
.....I find that the DIV aligns left.
I've tried all sorts of stuff but CSS isn't my strong point being a server side app kinda guy :(
So if anyone out there who's a jQuery/blockUI/CSS wizard reading this...please can you have a go and let me know what I'm getting wrong?
Basically I followed the design template on Matt's blog and the HTML looks like the stuff below (the CSS is unchanged from Matt's sample). You can grab the png 'sprite' file from the complete sample project download at <http://mattberseth2.com/downloads/yui_simpledialog.zip> - it's a .net project but I'm just trying to get this to work in a simple html file, so no .NET knowledge required.
Anyway any advice and guidance would be really really really useful. I'll even incentivise things buy promising to buy you lashings of beer if we ever meet :)
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="script/jquery-1.2.6.js"></script>
<script type="text/javascript" src="script/jquery.blockUI.js"></script>
<style>
.modalpopup
{
font-family: arial,helvetica,clean,sans-serif;
font-size: small;
padding: 2px 3px;
display: block;
position: absolute;
}
.container
{
width: 300px;
border: solid 1px #808080;
border-width: 1px 0px;
}
.header
{
background: url(img/sprite.png) repeat-x 0px -200px;
color: #000;
border-color: #808080 #808080 #ccc;
border-style: solid;
border-width: 0px 1px 1px;
padding: 3px 10px;
}
.header .msg
{
font-weight: bold;
}
.body
{
background-color: #f2f2f2;
border-color: #808080;
border-style: solid;
border-width: 0px 1px;
padding-top: 10px;
padding-left: 10px;
padding-bottom: 30px;
}
.body .msg
{
background: url(img/sprite.png) no-repeat 0px -1150px;
float: left;
padding-left: 22px;
}
.footer
{
background-color: #f2f2f2;
border-color: #808080;
border-style: none solid;
border-width: 0px 1px;
text-align:right;
padding-bottom: 8px;
padding-right: 8px;
}
.close
{
right: 7px;
background: url(img/sprite.png) no-repeat 0px -300px;
width: 25px;
cursor: pointer;
position: absolute;
top: 7px;
height: 15px;
}
.modalBackground
{
background-color:Gray;
filter:alpha(opacity=50);
opacity:0.5;
}
</style>
</head>
<body>
<input id="triggerDialogue" name="triggerDialogue" type="button" value="Go" />
<div id="confirmDialogue"
class="modalpopup" style="display:none; text-align: center">
<div class="container">
<div class="header">
<span class="msg">Are you sure?</span>
<a onclick="return false;" class="close"
href="javascript: return false;"></a>
</div>
<div class="body">
<span class="msg">Do you want to continue?</span>
</div>
<div class="footer">
<input type="button" id="Button1" value="Yes" style="width:40px" />
<input type="button" id="Button2" value="No" style="width:40px" />
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#triggerDialogue').click(function() {
$.blockUI({ message: $('#confirmDialogue') });
});
});
</script>
</body>
</html>
```
@Owen - many thanks for that. I had to make a wee change in the .modalPopup CSS class in Matt's stylesheet to:
```
position: fixed;
```
....and it works. Much appreciated. I really gotta sit down with my [O'Reilly CSS book](http://oreilly.com/catalog/9780596527334/) which I never get a chance to read some night....:) | hmm i'm not that familiar with blockUI, but the basics of centering a div are pretty universal. i'm assuming you want your `#confirmDialogue` div centered within the whole screen?
if so, you want to do a few things:
```
#confirmDialogue {
position: fixed; // absolutely position this element on the page
height: 200px; // define your height/width so we can calculate with it after
width: 300px;
}
```
now your jQuery:
```
$('#triggerDialogue').click(function() {
// to position #confirmDialogue, we need the window height/width
var msg = $('#confirmDialogue');
var height = $(window).height();
var width = $(document).width();
msg.css({
'left' : width/2 - (msg.width() / 2), // half width - half element width
'top' : height/2 - (msg.height() / 2), // similar
'z-index' : 15, // make sure element is on top
});
// etc...
});
```
basically, you want to fix the position of your `#confirmDialogue` (so that you can position it relative to the size of your window/document. `left` and `top` declarations are calculated based on the elements current height/width, and the window's height and document width. | Take a look at this [jQuery MSG plugin](http://dreamerslab.com/blog/en/jquery-blockui-alternative-with-jquery-msg-plugin/). It is very light weight and easy to use.
### Example code
```
// default usage, this will block the screen and shows a 'please wait...' msg
$.msg();
// this will show a 'blah blah' msg
$.msg({ content : 'blah blah' });
```
more options please see this [demo](http://dreamerslab.com/demos/jquery-blockui-alternative-with-jquery-msg-plugin)
full documentation please take a look at [this post](http://dreamerslab.com/blog/en/jquery-blockui-alternative-with-jquery-msg-plugin/). download and source code links are included in the post.
Or if you just want to centralize some DOM element you can also try this [plugin](http://dreamerslab.com/blog/en/centralize-html-dom-element-with-jquery-center-plugin/) | How can I get a DIV to centre on a page using jQuery and blockUI? | [
"",
"javascript",
"jquery",
"css",
"blockui",
""
] |
I'm still trying to debug a very sneaky memory corruption problem. I came across a section of my code that allocates memory on one thread and deletes it on another.
I have a vague feeling that this is wrong, but I'm not sure why. The threads share the process memory and access to these structures is protected by a mutex, so I think everything would work. However, is it there any danger I'm not seeing? | As indicated in another answer by @monjardin, there is nothing inherently wrong with what you are trying to do.
As an additional thought, you didn't mention the platform, etc. you are running into this problem on but if multi-threading is new to you and/or this application you are working on, you want to be sure that the standard support libraries you are using are the thread safe versions of the libraries. In many environments/platforms they have both the single threaded and multi-threaded versions of the support libraries available to the developer. If you are using threads but linking against the single thread version of the libraries, lots of bad things could be happening. For example, in a single threaded support library for *malloc()* and *free()* it would not have mutex protection for the heap (as an optimization). The multi-thread version of the library would add mutex protection to the heap manager to support more than one thread manipulating the heap at a time. (This is just one example). | remember that the memory manager itself has to be thread-safe too, not only your use of the memory. check your platform docs. | Memory allocation and deallocation across threads | [
"",
"c++",
"multithreading",
"memory",
""
] |
It seems to be a common requirement nowadays to have a search feature that can search almost anything you want. Can anyone give me samples or tips as to how to go about building a one stop search for an application?
For example: you have 3 tables customers, products, employees. The application has a master page that has a textbox at the right hand corner very similar to what you have on stackoverflow.
How do I have a search say for term say "Phoenix" and have results like
Customers
```
Result 1
......
```
Products
```
Result 1
......
```
Employees
```
Result 1
......
```
Any tips, tutorials and hints would be really appreciated. My environment is Win2k3,.net3.5,C#,ASP.net.
EDIT: Looking specifically at performance and scalability.
Thanks in advance! | [Lucene.NET](http://incubator.apache.org/lucene.net/) is an extremely fast full text search engine.
Sample usage:
See [Source code](http://code.google.com/p/dotnetkicks/) of [DotNetKicks](http://www.dotnetkicks.com/) starting from [codebehind of search page](http://code.google.com/p/dotnetkicks/source/browse/trunk/DotNetKicks/Incremental.Kick.Web.UI/Pages/Story/Search.aspx.cs) | If you want something really scalable, I guess you'll have to build first a data dictionnary, listing each table and each column in your database. The building of such a table can be [fully automated](https://stackoverflow.com/questions/281979/do-you-generate-your-data-dictionary#283813).
You will indicate in this table which fields are available for straight or soft (*with wild card*) searching.
You'll then be able to build some nice and smart user interface where the machine will be able to find that a code such as `'*823*'` refer both to `'INV-0823456'` and `'INV-0880823'` invoice numbers, as long as invoice number field is available for soft searching. The user might even be given the option to choose which column(s) to search, as scanning all telephone numbers in the database might not allways make sense.
You should not try to index all searchable columns. A "full-index" strategy can become very costy in termes of disk volume\server overhead, and will not allways make sense for rarely searched columns. Don't worry a lot about that: users will not mind some delay in getting their answer. | How do I build a search mechanism for my application? | [
"",
"c#",
"asp.net",
"sql-server",
"linq",
"search",
""
] |
What are general guidelines on when user-defined implicit conversion could, should, or should not be defined?
I mean things like, for example, "an implicit conversion should never lose information", "an implicit conversion should never throw exceptions", or "an implicit conversion should never instantiate new objects". I am pretty sure the first one is correct, the third one is not (or we could only ever have implicit conversion to structs), and I don't know about the second one. | The first isn't as simple as you might expect. Here's an example:
```
using System;
class Test
{
static void Main()
{
long firstLong = long.MaxValue - 2;
long secondLong = firstLong - 1;
double firstDouble = firstLong;
double secondDouble = secondLong;
// Prints False as expected
Console.WriteLine(firstLong == secondLong);
// Prints True!
Console.WriteLine(firstDouble == secondDouble);
}
}
```
Personally I very rarely create my own implicit conversions. I'm happy enough with the ones in the framework, but I rarely feel that adding my own would make life better. (The same is true of value types in general, btw.)
EDIT: Just to actually answer the question a bit, it's probably worth reading the [conversion operators part of the Microsoft class library design guidelines](http://msdn.microsoft.com/en-us/library/ms229059.aspx). | I'd agree with the first definitely - the second most of the time ("never say never"), but wouldn't get excited by the third; apart from anything else, it creates an unnecessary distinction between structs and classes. In some cases, having an implicit conversion can vastly simplify a calling convention.
For explicit conversions, all things are possible.
It isn't that often you need to write conversion operators, though. And in many cases, explicit operators are more useful, with the acceptance that they can break if conditions aren't right (for example, with `Nullable<T>`, if they don't have a value). | .Net implicit conversion guidelines | [
"",
"c#",
"types",
"implicit",
""
] |
What have others done to get around the fact that the Commons Logging project (for both .NET and Java) do not support Mapped or Nested Diagnostic Contexts as far as I know? | For the sake of completeness, I ended up writing my own very simple generic interface:
```
public interface IDiagnosticContextHandler
{
void Set(string name, string value);
}
```
then implemented a Log4Net specific version:
```
public class Log4NetDiagnosticContextHandler : IDiagnosticContextHandler
{
private readonly Assembly assembly;
private readonly Type mdcType;
public Log4NetDiagnosticContextHandler()
{
this.assembly = Assembly.Load("log4net");
this.mdcType = this.assembly.GetType("log4net.MDC", true);
}
public void Set(string name, string value)
{
this.mdcType.InvokeMember("Set", BindingFlags.InvokeMethod, null, null, new object[] { name, value });
}
}
```
I then used an IoC container (Spring.Net) to bring in the correct implementation. If a different logging framework was later required it'd be a simple matter of writing a different implementation of that interface changing the IoC configuration. | **Exec summary:**
We opted to use the implementor logging framework directly (in our case, log4j).
**Long answer:**
Do you need an abstract logging framework to meet your requirements? They're great for libraries that want to play nice with whatever host environment they end up in, but if you're writing an application, you can just use the implementing logging framework directly in many cases (i.e. there often isn't any reason why the logging implementor should change over the course of the application's life).
We opted to use the implementor logging framework directly (in our case, log4j). Commons-Logging is available on the classpath, but it's only there for the sake of the libraries that depend on it. In our case it was an easy choice, as the company I'm working for has had log4j as a mandatory standard for years and it's unlikely to change, but even if that's less obvious, it boils down to a bit of cost/benefit analysis.
* what's the benefit NDC and other specialty features give me?
* what's the chance of having to change logging implementor, and what's the cost if I have to?
and maybe:
* do I have to support different logging implementors in simultaneous deployments?
In our case, if we ever are required to change logging implementors, we'll have some refactoring to do, but with everything in the org.apache.log4j package, that's neither a difficult nor a very risky refactoring1. The log4e Eclipes plugin will happily convert the actual logging statements automatically; the NDC object could be a problem because not all logging frameworks support such a thing. You could consider hiding the NDC.enter() and NDC.leave() methods inside a utility class under your own control, we didn't bother.
---
1) famous Last Words | Logging Commons and Mapped Diagnostic Context | [
"",
"java",
".net",
"logging",
"apache-commons",
""
] |
Sample data:
!!Part|123456,ABCDEF,ABC132!!
The comma delimited list can be any number of any combination of alphas and numbers
I want a regex to match the entries in the comma separated list:
What I have is:
!!PART\|(\w+)(?:,{1}(\w+))\*!!
Which seems to do the job, the thing is I want to retrieve them in order into an ArrayList or similar so in the sample data I would want:
* 1 - 132456
* 2 - ABCDEF
* 3 - ABC123
The code I have is:
```
string partRegularExpression = @"!!PART\|(\w+)(?:,{1}(\w+))*!!"
Match match = Regex.Match(tag, partRegularExpression);
ArrayList results = new ArrayList();
foreach (Group group in match.Groups)
{
results.Add(group.Value);
}
```
But that's giving me unexpected results. What am I missing?
Thanks
**Edit:**
A solution would be to use a regex like !!PART\|(\w+(?:,??\w+)\*)!! to capture the comma separated list and then split that as suggested by Marc Gravell
I am still curious for a working regex for this however :o) | You can either use split:
```
string csv = tag.Substring(7, tag.Length - 9);
string[] values = csv.Split(new char[] { ',' });
```
Or a regex:
```
Regex csvRegex = new Regex(@"!!Part\|(?:(?<value>\w+),?)+!!");
List<string> valuesRegex = new List<string>();
foreach (Capture capture in csvRegex.Match(tag).Groups["value"].Captures)
{
valuesRegex.Add(capture.Value);
}
``` | Unless I'm mistaken, that still only counts as one group. I'm guessing you'll need to do a string.Split(',') to do what you want? Indeed, it looks a lot simpler to not bother with regex at all here... Depending on the data, how about:
```
if (tag.StartsWith("!!Part|") && tag.EndsWith("!!"))
{
tag = tag.Substring(7, tag.Length - 9);
string[] data = tag.Split(',');
}
``` | Extract comma separated portion of string with a RegEx in C# | [
"",
"c#",
"regex",
""
] |
I have this piece of code:
```
var myObj = function () {
this.complex = function (text) { /* long piece of code */ }
this.parse(text) {
return text.replace(/valid_pattern/gi, function ($1) { return this.complex($1); } );
}
}
```
Of course calling **this.complex($1)** won't do the trick, because I'm in the scope of the anonymous function. I can't re-scope the anonymous function using **.call(this)** statement either, because in th ta case I would lose the parameters passed to the function by *String.replace*.
So far I'm using the concrete instance of the object. This is my solution:
```
var instance = new myObj;
var myObj = function () {
this.complex = function (text) { /* long piece of code */ }
this.parse(text) {
return text.replace(/valid_pattern/gi, function ($1) { return instance.complex($1); } );
}
}
```
So far it's sufficient to my needs, but **I'm wondering if there is any universal solution** to this problem. The only idea that has worked for me so far is this:
```
function ($1) { return (new myObj).complex($1); }
```
... which suffers from serious performance issues. Any ideas would be greatly appreciated.
-- D.
P. S. Sorry about my English, it's not my first language. | Maybe try:
```
var myObj = function () {
this.complex = function (text) { /* long piece of code */ }
this.parse(text) {
var that = this;
return text.replace(/valid_pattern/gi, function ($1) { return that.complex($1); } );
}
}
```
It is one of the most useful tricks :-)
**UPDATE:** The trick is not mine, I learned it (as most of things I know about Javascript) from: [Douglas Crockford](http://javascript.crockford.com/) | This is what prototype and others do
```
// Monkey Patching, not everyone likes it
Function.prototype.bind = function( obj ) {
var _this = this;
return function() {
return _this.apply( obj, arguments )
}
}
```
Now you can do this
```
var myObj = function () {
this.complex = function (text) { /* long piece of code */ }
this.parse = function(text) {
return text.replace(/valid_pattern/gi, function ($1) { return this.complex($1); }.bind( this ) );
}
}
O = new myObj();
alert( O.parse( 'some text' );
``` | String.replace; replace by function result problem | [
"",
"javascript",
""
] |
This is how I do it at the moment. I try to open the file with the FileShare set to none. So I want exclusive accesss to the file. If I can't get that then its a good bet somebody else has the file locked.
There's got to be a better and faster way. Any ideas?
```
try
{
using (FileStream fs = File.Open(GetLockFilename(), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fs.Close();
}
// The file is not locked
}
catch (Exception)
{
// The file is locked
}
``` | There is no need first to check if the file is locked and then access it, as between the check and the access some other process may still get a lock on the file. So, what you do is correct, if you succeed, do your work with the file. | The truth is, even if you do figure out a way to check if the file is "locked" by the time you get to the next line where you open the file, something else in the OS may try to get a hold of that file, and your code to open it will fail anyway. You'll have to put a try/catch there anyway. Therefore, I say no. There isn't really a better solution. | Detecting whether a file is locked by another process (or indeed the same process) | [
"",
"c#",
".net",
""
] |
How could I unpack a tuple of unknown to, say, a list?
I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need? | Unpack the tuple to a list?
```
l = list(t)
``` | You can use the asterisk to unpack a variable length, for instance:
```
foo, bar, *other = funct()
```
This should put the first item into `foo`, the second into `bar`, and all the rest into `other`.
**Update:** I forgot to mention that this is Python 3.0 compatible only. | Unpack to unknown number of variables? | [
"",
"python",
"casting",
"iterable-unpacking",
""
] |
I have a user defined function in SQL called getBuisnessDays it takes @startdate and @enddate and returns the number of business days between the two dates. How can I call that function within my select?
Here's what I'd like to do..
```
SELECT getBusinessDays(a.opendate,a.closedate)
FROM account a
WHERE ...
``` | Yes, you can do almost that:
```
SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...
``` | If it's a table-value function (returns a table set)
you simply join it as a Table
this function generates one column table with all the values from passed comma-separated list
```
SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')
``` | SQL User Defined Function Within Select | [
"",
"sql",
"sql-server",
"select",
"user-defined-functions",
""
] |
This following code gets this compile error: "*`invalid types 'int[int]' for array subscript`*". What should be changed?
```
#include <iostream>
using namespace std;
int main(){
int myArray[10][10][10];
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++x){
for (int y = 0; y <= 9; ++y){
myArray[i][t][x][y] = i+t+x+y; //This will give each element a value
}
}
}
}
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++x){
for (int y = 0; y <= 9; ++y){
cout << myArray[i][t][x][y] << endl;
}
}
}
}
system("pause");
}
``` | You are subscripting a three-dimensional array `myArray[10][10][10]` four times `myArray[i][t][x][y]`. You will probably need to add another dimension to your array. Also consider a container like [Boost.MultiArray](http://www.boost.org/doc/libs/1_37_0/libs/multi_array/doc/index.html), though that's probably over your head at this point. | What to change? Aside from the 3 or 4 dimensional array problem, you should get rid of the magic numbers (10 and 9).
```
const int DIM_SIZE = 10;
int myArray[DIM_SIZE][DIM_SIZE][DIM_SIZE];
for (int i = 0; i < DIM_SIZE; ++i){
for (int t = 0; t < DIM_SIZE; ++t){
for (int x = 0; x < DIM_SIZE; ++x){
``` | invalid types 'int[int]' for array subscript | [
"",
"c++",
"arrays",
"compiler-errors",
""
] |
How can I create a Popup balloon like you would see from Windows Messenger or AVG or Norton or whomever?
I want it to show the information, and then slide away after a few seconds.
**Edit: It needs to be blocking like Form.ShowDialog()** because the program exits after displaying the notification | You can use the notifyIcon control that's part of .NET 2.0 System.Windows.Forms. That allows you to place an icon for your application in the System Tray. Then, you can call the ShowBalloonTip(int timeOut) method on that. Be sure however to first set the text, and icon properties on the notifyIcon for it to work. Small code sample:
```
private void button1_Click(object sender, EventArgs e)
{
this.notifyIcon1.BalloonTipText = "Whatever";
this.notifyIcon1.BalloonTipTitle = "Title";
this.notifyIcon1.Icon = new Icon("icon.ico");
this.notifyIcon1.Visible = true;
this.notifyIcon1.ShowBalloonTip(3);
}
```
EDIT: Ok, so notifyIcon won't work for you. My second suggestion would then be to create your own control for this. Actually, I would use a form. A simple form, with no borders, and no control box and just have a timer running so you can set the Opacity for fade in/out. Then, you can easily get the bottom right of the screen using the Rectangle Screen.PrimaryScreen.WorkingArea. Then just show your form at that position. | Don't create a modal (blocking) balloon. Please. A big part of the design of these UIs is that they are *not* dialogs: they're transient, potentially *non-interactive* elements, intended to provide incidental information to a user *without* necessarily interrupting their workflow. A balloon that steals focus and blocks user input would be irritating at best - if you *need* a dialog, then use a dialog. | Creating a Popup Balloon like Windows Messenger or AVG | [
"",
"c#",
".net",
"popup-balloons",
""
] |
How do I convert a date string, formatted as `"MM-DD-YY HH:MM:SS"`, to a `time_t` value in either C or C++? | Use `strptime()` to parse the time into a `struct tm`, then use `mktime()` to convert to a `time_t`. | In the absence of `strptime` you could use `sscanf` to parse the data into a `struct tm` and then call `mktime`. Not the most elegant solution but it would work. | Date/time conversion: string representation to time_t | [
"",
"c++",
"c",
"datetime",
""
] |
I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level). | First normalize 2 XML, then you can compare them. I've used the following using lxml
```
import xml.etree.ElementTree as ET
obj1 = objectify.fromstring(expect)
expect = ET.tostring(obj1)
obj2 = objectify.fromstring(xml)
result = ET.tostring(obj2)
self.assertEquals(expect, result)
``` | This is an old question, but the accepted [Kozyarchuk's answer](https://stackoverflow.com/a/321893/3357935) doesn't work for me because of attributes order, and the [minidom solution](https://stackoverflow.com/a/321941/3357935) doesn't work as-is either (no idea why, I haven't debugged it).
This is what I finally came up with:
```
from doctest import Example
from lxml.doctestcompare import LXMLOutputChecker
class XmlTest(TestCase):
def assertXmlEqual(self, got, want):
checker = LXMLOutputChecker()
if not checker.check_output(want, got, 0):
message = checker.output_difference(Example("", want), got, 0)
raise AssertionError(message)
```
This also produces a diff that can be helpful in case of large xml files. | Comparing XML in a unit test in Python | [
"",
"python",
"xml",
"elementtree",
""
] |
I am trying to determine what issues could be caused by using the following serialization surrogate to enable serialization of anonymous functions/delegate/lambdas.
```
// see http://msdn.microsoft.com/msdnmag/issues/02/09/net/#S3
class NonSerializableSurrogate : ISerializationSurrogate
{
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
info.AddValue(f.Name, f.GetValue(obj));
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,
ISurrogateSelector selector)
{
foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
f.SetValue(obj, info.GetValue(f.Name, f.FieldType));
return obj;
}
}
```
**Listing 1** *adapted from* [Counting Demo](http://www.agilekiwi.com/dotnet/CountingDemo.cs)
The main issue I can think of that might be a problem is that the anonymous class is an internal compiler detail and it's structure is not guaranteed to remain constant between revisions to the .NET Framework. I'm fairly certain this is the case based on my research into the similar problem with iterators.
## Background
I am investigating the serialization of anonymous functions. I was expecting this not to work, but found it did for some cases. As long as the lambda did \*not& force the compiler to generate an anonymous class everything works fine.
A SerializationException is thrown if the compiler requires a generated class to implement the anonymous function. This is because the compiler generated class is not marked as serializable.
## Example
```
namespace Example
{
[Serializable]
class Other
{
public int Value;
}
[Serializable]
class Program
{
static void Main(string[] args)
{
MemoryStream m = new MemoryStream();
BinaryFormatter f = new BinaryFormatter();
// Example 1
Func<int> succeeds = () => 5;
f.Serialize(m, succeeds);
// Example 2
Other o = new Other();
Func<int> fails = () => o.Value;
f.Serialize(m, fails); // throws SerializationException - Type 'Example.Program+<>c__DisplayClass3' in Assembly 'Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
}
}
```
**Listing 2**
This is similar to the issue of trying to serialize *iterators* and I had found the following code in a previous search (see [countingdemo](http://www.agilekiwi.com/dotnet/CountingDemo.cs)) Using the code from **Listing 1** and an ISurrogateSelector I was able to successfully serialize and deserialize the second failing example.
## Objective
I have a system that is exposed via a web service. The system has a complex but small state (many objects, not a lot of properties per object). The state is saved in the ASP.NET Cache, but is also serialized to a BLOB in SQL in case of cache expiration. Some objects need to execute arbitrary "events" upon reaching some condition. Hence they have properties accepting Action/Func objects. Contrived example:
```
class Command
{
public Command(Action action, Func<bool> condition);
}
```
Somewhere else
```
void DoSomethingWithThing(Thing thing)
{
state = Store.GetCurrentState();
Command cmd = new Command(() => thing.Foo(), () => thing.IsReady())
state.Add(cmd);
Store.Save(state);
}
``` | Did you see this post that I wrote as a followup to the CountingDemo: <http://dotnet.agilekiwi.com/blog/2007/12/update-on-persistent-iterators.html> ? Unfortunately, Microsoft have confirmed that they probably will change the compiler details (one day), in a way that is likely to cause problems. (e.g. f/when you update to the new compiler, you won't be able to deserialise the stuff you saved under the old (current) compiler.) | > Some objects need execute arbitrary "events" reaching some condition.
Just how arbitrary are these events? Can they be counted, assigned ID's and mapped to referentially?
```
public class Command<T> where T : ISerializable
{
T _target;
int _actionId;
int _conditionId;
public Command<T>(T Target, int ActionId, int ConditionId)
{
_target = Target;
_actionId = ActionId;
_conditionId = ConditionId;
}
public bool FireRule()
{
Func<T, bool> theCondition = conditionMap.LookupCondition<T>(_conditionId)
Action<T> theAction = actionMap.LookupAction<T>(_actionId);
if (theCondition(_target))
{
theAction(_target);
return true;
}
return false;
}
}
``` | Serializing anonymous delegates in C# | [
"",
"c#",
".net-3.5",
"serialization",
""
] |
Is there a good equivalent implementation of `strptime()` available for Windows? Unfortunately, this POSIX function does not appear to be available.
[Open Group description of strptime](http://www.opengroup.org/onlinepubs/009695399/functions/strptime.html) - summary: it converts a text string such as `"MM-DD-YYYY HH:MM:SS"` into a `tm struct`, the opposite of `strftime()`. | An open-source version (BSD license) of `strptime()` can be found here: [<http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD>](http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD)
You'll need to add the following declaration to use it:
```
char *strptime(const char * __restrict, const char * __restrict, struct tm * __restrict);
``` | If you don't want to port any code or condemn your project to boost, you can do this:
1. parse the date using `sscanf`
2. then copy the integers into a `struct tm` (subtract 1 from month and 1900 from year -- months are 0-11 and years start in 1900)
3. finally, use `mktime` to get a UTC epoch integer
Just remember to set the `isdst` member of the `struct tm` to -1, or else you'll have daylight savings issues. | strptime() equivalent on Windows? | [
"",
"c++",
"c",
"windows",
"datetime",
""
] |
Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.
```
def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
``` | I don't think there is any way to do that in Python. When the closure is defined, the current state of variables in the enclosing scope is captured and no longer has a directly referenceable name (from outside the closure). If you were to call `foo()` again, the new closure would have a different set of variables from the enclosing scope.
In your simple example, you might be better off using a class:
```
class foo:
def __init__(self):
self.var_a = 2
self.var_b = 3
def __call__(self, x):
return self.var_a + self.var_b + x
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
localClosure.var_a = 0
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
```
If you do use this technique I would no longer use the name `localClosure` because it is no longer actually a closure. However, it works the same as one. | It is quite possible in python 3 thanks to the magic of [nonlocal](http://jeremyhylton.blogspot.com/2007/02/nonlocal-implemented.html).
```
def foo():
var_a = 2
var_b = 3
def _closure(x, magic = None):
nonlocal var_a
if magic is not None:
var_a = magic
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
print(a)
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
localClosure(0, 0)
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
print(b)
``` | Modify bound variables of a closure in Python | [
"",
"python",
"functional-programming",
"closures",
""
] |
I have a simple task of authenticating against Active Directory using Java. Just verifying credentials and nothing else. Let's say my domain is "fun.xyz.tld", OU path is unknown, and username/password is testu/testp.
I know there's a few Java libraries out there that simplify this task, but I wasn't successful at implementing them. Most examples that I've found addressed LDAP in general, not specifically Active Directory. Issuing LDAP request means sending an OU path in it, which I don't have. Also, the application that issues LDAP request should be already bound to Active Directory in order to access it... Insecure, since the credentials would have to be stored someplace discoverable. I would like a test bind with test credentials, if possible - this would mean that account is valid.
Last, if possible, is there a way to make such authentication mechanism encrypted? I know that AD uses Kerberos, but not sure if Java's LDAP methods do.
Does anyone has an example of working code? Thanks. | Here's the code I put together based on example from this blog: [LINK](https://community.oracle.com/blogs/kohsuke/2008/06/12/more-active-directory-integration-java) and this source: [LINK](https://github.com/jenkinsci/active-directory-plugin/blob/master/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java).
```
import com.sun.jndi.ldap.LdapCtxFactory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
class App2 {
public static void main(String[] args) {
if (args.length != 4 && args.length != 2) {
System.out.println("Purpose: authenticate user against Active Directory and list group membership.");
System.out.println("Usage: App2 <username> <password> <domain> <server>");
System.out.println("Short usage: App2 <username> <password>");
System.out.println("(short usage assumes 'xyz.tld' as domain and 'abc' as server)");
System.exit(1);
}
String domainName;
String serverName;
if (args.length == 4) {
domainName = args[2];
serverName = args[3];
} else {
domainName = "xyz.tld";
serverName = "abc";
}
String username = args[0];
String password = args[1];
System.out
.println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + "@" + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
System.out.println("Authentication succeeded!");
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),
"(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls);
if (!renum.hasMore()) {
System.out.println("Cannot locate user information for " + username);
System.exit(1);
}
SearchResult result = renum.next();
List<String> groups = new ArrayList<String>();
Attribute memberOf = result.getAttributes().get("memberOf");
if (memberOf != null) {// null if this user belongs to no group at all
for (int i = 0; i < memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
Attribute att = atts.get("CN");
groups.add(att.get().toString());
}
}
context.close();
System.out.println();
System.out.println("User belongs to: ");
Iterator ig = groups.iterator();
while (ig.hasNext()) {
System.out.println(" " + ig.next());
}
} catch (AuthenticationException a) {
System.out.println("Authentication failed: " + a);
System.exit(1);
} catch (NamingException e) {
System.out.println("Failed to bind to LDAP / get account information: " + e);
System.exit(1);
}
}
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if (token.length() == 0)
continue; // defensive check
if (buf.length() > 0)
buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
}
``` | There are 3 authentication protocols that can be used to perform authentication between Java and Active Directory on Linux or any other platform (and these are not just specific to HTTP services):
1. Kerberos - Kerberos provides Single Sign-On (SSO) and delegation but web servers also need SPNEGO support to accept SSO through IE.
2. NTLM - NTLM supports SSO through IE (and other browsers if they are properly configured).
3. LDAP - An LDAP bind can be used to simply validate an account name and password.
There's also something called "ADFS" which provides SSO for websites using SAML that calls into the Windows SSP so in practice it's basically a roundabout way of using one of the other above protocols.
Each protocol has it's advantages but as a rule of thumb, for maximum compatibility you should generally try to "do as Windows does". So what does Windows do?
First, authentication between two Windows machines favors Kerberos because servers do not need to communicate with the DC and clients can cache Kerberos tickets which reduces load on the DCs (and because Kerberos supports delegation).
But if the authenticating parties do not both have domain accounts or if the client cannot communicate with the DC, NTLM is required. So Kerberos and NTLM are not mutually exclusive and NTLM is not obsoleted by Kerberos. In fact in some ways NTLM is better than Kerberos. Note that when mentioning Kerberos and NTLM in the same breath I have to also mention SPENGO and Integrated Windows Authentication (IWA). IWA is a simple term that basically means Kerberos or NTLM or SPNEGO to negotiate Kerberos or NTLM.
Using an LDAP bind as a way to validate credentials is not efficient and requires SSL. But until recently implementing Kerberos and NTLM have been difficult so using LDAP as a make-shift authentication service has persisted. But at this point it should generally be avoided. LDAP is a directory of information and not an authentication service. Use it for it's intended purpose.
So how do you implement Kerberos or NTLM in Java and in the context of web applications in particular?
There are a number of big companies like Quest Software and Centrify that have solutions that specifically mention Java. I can't really comment on these as they are company-wide "identity management solutions" so, from looking the marketing spin on their website, it's hard to tell exactly what protocols are being used and how. You would need to contact them for the details.
Implementing Kerberos in Java is not terribly hard as the standard Java libraries support Kerberos through the org.ietf.gssapi classes. However, until recently there's been a major hurdle - IE doesn't send raw Kerberos tokens, it sends SPNEGO tokens. But with Java 6, SPNEGO has been implemented. In theory you should be able to write some GSSAPI code that can authenticate IE clients. But I haven't tried it. The Sun implementation of Kerberos has been a comedy of errors over the years so based on Sun's track record in this area I wouldn't make any promises about their SPENGO implementation until you have that bird in hand.
For NTLM, there is a Free OSS project called JCIFS that has an NTLM HTTP authentication Servlet Filter. However it uses a man-in-the-middle method to validate the credentials with an SMB server that does not work with NTLMv2 (which is slowly becoming a required domain security policy). For that reason and others, the HTTP Filter part of JCIFS is scheduled to be removed. Note that there are number of spin-offs that use JCIFS to implement the same technique. So if you see other projects that claim to support NTLM SSO, check the fine print.
The only correct way to validate NTLM credentials with Active Directory is using the NetrLogonSamLogon DCERPC call over NETLOGON with Secure Channel. Does such a thing exist in Java? Yes. Here it is:
<http://www.ioplex.com/jespa.html>
Jespa is a 100% Java NTLM implementation that supports NTLMv2, NTLMv1, full integrity and confidentiality options and the aforementioned NETLOGON credential validation. And it includes an HTTP SSO Filter, a JAAS LoginModule, HTTP client, SASL client and server (with JNDI binding), generic "security provider" for creating custom NTLM services and more.
Mike | Authenticating against Active Directory with Java on Linux | [
"",
"java",
"authentication",
"active-directory",
"ldap",
""
] |
Say I need to call a javascript file in the `<head>` of an ERb template.
My instinct is to do the usual:
```
<head>
<%= javascript_include_tag :defaults %> <!-- For example -->
</head>
```
in my application's layout. The problem of course becoming that these javascript files are loaded into every page in my application, regardless of whether or not they are needed for the page being viewed.
So what I'm wondering is if there's a good way of loading a javascript into the the headers of, for example, all ERb templates found only in a specific directory. | I would use [content\_for](http://apidock.com/rails/ActionView/Helpers/CaptureHelper/content_for).
For instance, specify the place to insert it in the application layout:
```
<head>
<title>Merry Christmas!</title>
<%= yield(:head) -%>
</head>
```
And send it there from a view:
```
<%- content_for(:head) do -%>
<%= javascript_include_tag :defaults -%>
<%- end -%>
``` | I feel there's nothing wrong including all yr defaults since they can then be cached on user's browser. | Javascript Include Tag Best Practice in a Rails Application | [
"",
"javascript",
"ruby-on-rails",
"header",
"rjs",
""
] |
I know that the f# list is not the same at the c# List. What do I need to do to be able to pass a list of ints from a c# application to an f# library? I'd like to be able to use pattern matching on the data once it's in the f# code. | Here is how I ended up doing it.
The FSharp code:
```
let rec FindMaxInList list =
match list with
| [x] -> x
| h::t -> max h (FindMaxInList t)
| [] -> failwith "empty list"
let rec FindMax ( array : ResizeArray<int>) =
let list = List.ofSeq(array)
FindMaxInList list
```
The c Sharp code:
```
List<int> myInts = new List<int> { 5, 6, 7 };
int max = FSModule.FindMax(myInts);
``` | You can use
```
Seq.toList : IEnumerable<'a> -> list<'a>
```
to convert any `IEnumerable<'a>` `seq` to an F# list. Note that F# lists are immutable; if you want to work with the mutable list, you don't need to do anything special, but you won't be able to use pattern matching. Or, rather, you *can* define active patterns for `System.Collections.Generic.List<'a>`; it's just a bad idea. | What can I do to pass a list from C# to F#? | [
"",
"c#",
"f#",
""
] |
I've looked breifly into [GWT](http://code.google.com/webtoolkit/) and like the idea that I can develop in Java and have the application compile down to HTML and JavaScript. Is the concept behind GWT and AWT and Swing the same or different? | GWT is very much similar to Swing in its usage of Widgets, Panels and the EventListeners it provides. A different way to look at GWT is to think of Javascript and HTML as Assembly language and GWT as a sort of High level language which generates Javascript and HTML. With GWT its easy to develop desktop-like apps for the web using the same tools you would use for building a desktop app | It is programmed very similarly(patterned after Swing) and the code is 100% java (compiles with a standard Java compiler without errors), but the way it works is very different. Instead of compiling into a Java app, it compiles into Javascript that is sent to your browser.
This ability to program good active Javascript without actually coding Javascript and HTML is pretty nice.
Also, since it programs much like swing, you can do stuff like adding listeners that effect other controls pretty easily. | Is Google Web Toolkit similar to AWT and Swing | [
"",
"java",
"swing",
"gwt",
"awt",
""
] |
Currently I am evaluating number of web service frameworks in Java. I need web service framework that will help me to expose some functionality of existent application running on JBoss, The application is mostly developed using Spring and POJOs (no EJBs).
What I need is a framework having following properties:
1. It should provide tools for automatic generation of boilerplate code and save time by eliminating repetitive tasks, for example tools generating WSDL from Java (java2wsdl), tools generating endpoints etc.
2. Applications should be easily deployed on existent J2EE platform (JBoss), this means that it should contain as less as possible configuration files (like axis2.xml in axis2 framework).
* Also it is preferred to be able to deploy web service within *.war* archive of existent application. (it seems that Axis2 need a separate archive for web service app.)
* It will be very cool to use a combination of *POJOs* and *Spring*.
* Generally, the framework should have clean structure and design (for example Spring-WS lacks it), good documentation and whatever else characterizes a good piece of software.
* It is preferred that framework incorporates some standard features like *JAX-WS* etc. instead of vendor specific methods.
I have briefly examined
* Axis2
* Apache CXF
* and Sun's Metro
* Spring WS
But still it is difficult to decide what to use in my case:
* Axis2 seems to be so low level, it requires separate application archive and lots of configurations
* Spring WS seems to be too opaque and "sophisticated for impression purposes (?)"
* Apache CXF and Metro probably are two frameworks that I prefer to chose from but still
I need your opinion and experience about usage of some of them in a real-world applications. | I've used CXF's forerunner, XFire, for a while now and it's not been too bad. At the time, we migrated from Axis for two major reasons: performance and ease of development. At the time (don't know if this is true now), the performance of XFire was much better than anything out there, and with annotation-driven development, instead of having to run stub generation, it was really really easy to add new web services.
CXF seems to be more of the same but better - we haven't migrated yet due to constraints on development time as well as not having a pressing reason to do so (plus the relative lack of documentation 6-12 months ago wasn't too encouraging). Additionally I haven't really evaluated the market of late, so I can't tell you how CXF stands up to its contemporary competitors.
Regarding your points:
1. There is no boilerplate code to be generated, the WSDL is automatically created from the service class' annotations and published by the server.
2. Deployment in Tomcat was relatively simple. Just define another servlet in web.xml and map a URL pattern to this servlet.
3. Our web services were deployed in WAR files, I'm not sure what the alternatives are in fact but this seemed to be the default and obvious way to do it.
4. POJOs work fine initially; we've now moved most of the web service object creation to Spring in order to wire more complex conditional dependencies in and have had no problems with this.
5. Documentation was a weak point with CXF originally, though having just had a look it seems to be better now. The general design and architecture seems relatively sane; slotting in one's own filters to modify the transmission details was not very painful, and extending existing classes has generally been considered (so sensible methods are marked protected instead of private, for example).
6. JAX-WS is full supported in CXF.
So I'm probably a little impartial as I haven't tried the other ones, but I'll give a thumbs up to having a look at CXF. It's pretty fast, relatively simple to get going with and fairly powerful if you need to tweak it. | We have tried Metro and CXF and kept CXF because Metro includes too many dependencies like Sun's APIs in its jar files which makes it difficult to integrate in another application server than Glassfish. CXF has a cleaner packaging with explicit external dependencies.
We also failed to enable Gzip compression with Metro while it worked like a charm with CXF. | Java Web Service framework/library, which is a better one and why? | [
"",
"java",
"web-services",
"spring",
"jakarta-ee",
"frameworks",
""
] |
I have a SQLServer with a linked server onto another database somewhere else. I have created a view on that linked server
```
create view vw_foo as
select
[id],
[name]
from LINKEDSERVER.RemoteDatabase.dbo.tbl_bar
```
I'd like to to the following
```
alter table [baz]
add foo_id int not null
go
alter table [baz] with check
add constraint [fk1_baz_to_foo]
foreign key([foo_id])
references [dbo].[vw_foo] ([id])
go
```
But that generates the error: "Foreign key 'fk1\_baz\_to\_foo' references object 'dbo.vw\_foo' which is not a user table."
If I try and put the foreign key directly onto the table using the following
```
alter table [baz] with check
add constraint [fk1_baz_to_bar]
foreign key([foo_id])
references LINKEDSERVER.RemoteDatabase.dbo.tbl_bar ([id])
```
Then I get the following error:
> The object name 'LINKEDSERVER.RemoteDatabase.dbo.tbl\_bar' contains more than the maximum number of prefixes. The maximum is 2.
Is there any way I can achieve the same effect? | Foreign keys can't be connected to non-local objects - they have to reference local tables. You get the "maximum number of prefixes" error because you're referencing the table with a 4-part name (LinkedServer.Database.Schema.Object), and a local object would only have a 3-part name.
Other solutions :
1. Replicate the data from the source (the location of the view) to the same server as the table you're trying to add the key on. You can do this hourly, daily, or whatever, depending on how often the source data changes.
2. Add a trigger on the source table to push any changes to your local copy. This would essentially be the same as #1, but with immediate population of changes
3. Add an INSTEAD OF" trigger to your table that manually checks the foreign key constraint by selecting from the linked server and comparing the value you're trying to INSERT/UPDATE. If it doesn't match, you can reject the change. | You can, but you have to use some dynamic SQL trickery to make it happen.
```
declare @cmd VARCHAR(4000)
SET @cmd = 'Use YourDatabase
ALTER TABLE YourTable
DROP CONSTRAINT YourConstraint'
exec YourServer.master.dbo.sp_executesql @SQL
``` | Can you have a Foreign Key onto a View of a Linked Server table in SQLServer 2k5? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"foreign-keys",
"linked-server",
""
] |
**Dupe: [Null Difference](https://stackoverflow.com/questions/302701/null-difference)**
A lifetime ago I came across an article that explained that the following were not equal (in c#):
```
if (o == null) {}
if (null == o) {}
```
The article explained that the latter was preferred because it resulted in a more accurate test. I've been coding like that ever since. Now that I understand so much more I was looking for the article, or another like it, to see what the exact findings were, but I can't find anything on the subject.
Thoughts? Is there a difference? First glance would say no. But who knows what happens in the bowels of IL and C# compilation. | it's an old habit to prevent you from typing `if (o = null)`. if (null = o) is a syntax error. kind of pointless in C#, because null values aren't ever coerced into booleans. | The latter is a holdover from the C/C++ days, where it was possible to accidentally assign a value instead of compare. C# won't allow you to do this, so either/or is acceptable (but I find the former more readable). | Checking for null, which is better? "null ==" or "==null" | [
"",
"c#",
".net",
"null",
""
] |
I currently have a small Java program which I would like to run both on the desktop (ie in a JFrame) and in an applet. Currently all of the drawing and logic are handled by a class extending Canvas. This gives me a very nice main method for the Desktop application:
```
public static void main(String[] args) {
MyCanvas canvas = new MyCanvas();
JFrame frame = MyCanvas.frameCanvas(canvas);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.loop();
}
```
Can I do something similar for the applet? Ideally MyCanvas would remain the same for both cases.
Not sure if its important but I am drawing using BufferStrategy with `setIgnoreRepaint(true)`.
**Edit**: To clarify, my issue seems to be painting the canvas -- since all the painting is being done from the `canvas.loop()` call. | [Applet](http://java.sun.com/j2se/1.5.0/docs/api/java/applet/Applet.html) is a [Container](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html), just [add](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html#add(java.awt.Component)) your Canvas there. | Generally, the way you would have an application that is also an applet is to have your entry point class extend Applet, and have its setup add the Canvas to itself, etc. etc.
Then, in the main method version, you just instantiate your Applet class and add it to a new Frame (or JApplet / JFrame, etc.).
See [here](http://www.heatonresearch.com/articles/18/page6.html) and [here](http://www.devx.com/tips/Tip/16650) for examples of the technique, which essentially boils down to (from the first example):
```
public static void main(String args[])
{
Applet applet = new AppletApplication();
Frame frame = new Frame();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
frame.add(applet);
frame.setSize(IDEAL_WIDTH,IDEAL_HEIGHT);
frame.show();
}
``` | Painting a Canvas in an Applet | [
"",
"java",
"graphics",
"applet",
"canvas",
""
] |
I trying to export an HTML table named Table that is dynamically binded to ViewData.Model in C#. I have a method called export that is called based on another method's actions. so everything before that is set up.. I just don't know how to export the data to a CSV or Excel file.. So when the I step inside the Export method I don't know what next to do to export the table. Can someone help me
```
public void Export(List<data> List)
{
//the list is the rows that are checked and need to be exported
StringWriter sw = new StringWriter();
//I don't believe any of this syntax is right, but if they have Excel export to excel and if not export to csv "|" delimeted
for(int i=0; i<List.Count;i++)
{
sw.WriteLine(List[i].ID+ "|" + List[i].Date + "|" + List[i].Description);
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
``` | I don't quite understand the whole "export an HTML table named Table that is dynamically binded to ViewData.Model" so I'll just ignore that and focus on your *Export(List<data> list)* method. Btw, you never really mentioned what was going wrong and where.
I see you had written "if they have Excel export to excel and if not export to csv" - I would personally just export it as a CSV file in both cases because excel can handle csv files no problem.
So with that in mind, here would be my export method based on your code.
```
public void Export(List<DataType> list)
{
StringWriter sw = new StringWriter();
//First line for column names
sw.WriteLine("\"ID\",\"Date\",\"Description\"");
foreach(DataType item in list)
{
sw.WriteLine(string.format("\"{0}\",\"{1}\",\"{2}\"",
item.ID,
item.Date,
item.Description));
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
``` | This is an excellent example, but I think that need a globalization modification.
```
String ltListSeparator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
sw.WriteLine(string.format("{0}" + ltListSeparator + "{1}" + ltListSeparator + "{2}", item.ID, item.Date, item.Description));
``` | Export HTML Table in asp.net MVC | [
"",
"c#",
"asp.net-mvc",
""
] |
I have two simple while loops in my program that I feel ought to be math equations, but I'm struggling to convert them:
```
float a = someValue;
int b = someOtherValue;
int c = 0;
while (a <= -b / 2) {
c--;
a += b;
}
while (a >= b / 2) {
c++;
a -= b;
}
```
This code works as-is, but I feel it could be simplified into math equations. The idea here being that this code is taking an offset (someValue) and adjusting a coordinate (c) to minimize the distance from the center of a tile (of size someOtherValue). Any help would be appreciated. | It can be proved that the following is correct:
```
c = floor((a+b/2)/b)
a = a - c*b
```
Note that floor means round down, towards negative infinity: not towards 0. (E.g. floor(-3.1)=-4. The `floor()` library functions will do this; just be sure not to just cast to int, which will usually round towards 0 instead.)
Presumably `b` is strictly positive, because otherwise neither loop will never terminate: adding `b` will not make `a` larger and subtracting `b` will not make `a` smaller. With that assumption, we can prove that the above code works. (And paranoidgeek's code is also almost correct, except that it uses a cast to int instead of `floor`.)
**Clever way of proving it**:
The code adds or subtracts multiples of `b` from `a` until `a` is in `[-b/2,b/2)`, which you can view as adding or subtracting *integers* from `a/b` until `a/b` is in `[-1/2,1/2)`, i.e. until `(a/b+1/2)` (call it `x`) is in `[0,1)`. As you are only changing it by integers, the value of `x` does not change `mod 1`, i.e. it goes to its **remainder mod 1**, which is `x-floor(x)`. So the effective number of subtractions you make (which is `c`) is `floor(x)`.
**Tedious way of proving it**:
At the end of the first loop, the value of `c` is the negative of the number of times the loop runs, i.e.:
* 0 if: a > -b/2 <=> a+b/2 > 0
* -1 if: -b/2 ≥ a > -3b/2 <=> 0 ≥ a+b/2 > -b <=> 0 ≥ x > -1
* -2 if: -3b/2 ≥ a > -5b/2 <=> -b ≥ a+b/2 > -2b <=> -1 ≥ x > -2 etc.,
where `x = (a+b/2)/b`, so c is: 0 if x>0 and "ceiling(x)-1" otherwise. If the first loop ran at all, then it was ≤ -b/2 just before the *last time* the loop was executed, so it is ≤ -b/2+b now, i.e. ≤ b/2. According as whether it is exactly b/2 or not (i.e., whether `x` when you started was exactly a non-positive integer or not), the second loop runs exactly 1 time or 0, and c is either ceiling(x) or ceiling(x)-1. So that solves it for the case when the first loop did run.
If the first loop didn't run, then the value of c at the end of the second loop is:
* 0 if: a < b/2 <=> a-b/2 < 0
* 1 if: b/2 ≤ a < 3b/2 <=> 0 ≤ a-b/2 < b <=> 0 ≤ y < 1
* 2 if: 3b/2 ≤ a < 5b/2 <=> b ≤ a-b/2 < 2b <=> 1 ≤ y < 2, etc.,
where `y = (a-b/2)/b`, so c is: 0 if y<0 and 1+floor(y) otherwise. [And `a` now is certainly < b/2 and ≥ -b/2.]
So you can write an expression for `c` as:
```
x = (a+b/2)/b
y = (a-b/2)/b
c = (x≤0)*(ceiling(x) - 1 + (x is integer))
+(y≥0)*(1 + floor(y))
```
Of course, next you notice that `(ceiling(x)-1+(x is integer))` is same as `floor(x+1)-1` which is `floor(x)`, and that `y` is actually `x-1`, so `(1+floor(y))=floor(x)`, and as for the conditionals:
when x≤0, it cannot be that (y≥0), so `c` is just the first term which is `floor(x)`,
when 0 < x < 1, neither of the conditions holds, so `c` is `0`,
when 1 ≤ x, then only 0≤y, so c is just the second term which is `floor(x)` again.
So c = `floor(x)` in all cases. | ```
c = (int)((a - (b / 2)) / b + 1);
a -= c * b;
```
Test case at <http://pastebin.com/m1034e639> | Turn while loop into math equation? | [
"",
"c++",
"c",
"algorithm",
"math",
""
] |
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java. And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...
Here's the problem I was given:
```
/* What is the output of the following program? */
public class Test {
public boolean equals( Test other ) {
System.out.println( "Inside of Test.equals" );
return false;
}
public static void main( String [] args ) {
Object t1 = new Test();
Object t2 = new Test();
Test t3 = new Test();
Object o1 = new Object();
int count = 0;
System.out.println( count++ );// prints 0
t1.equals( t2 ) ;
System.out.println( count++ );// prints 1
t1.equals( t3 );
System.out.println( count++ );// prints 2
t3.equals( o1 );
System.out.println( count++ );// prints 3
t3.equals(t3);
System.out.println( count++ );// prints 4
t3.equals(t2);
}
}
```
I asserted that the output should have been two separate print statements from within the overridden `equals()` method: at `t1.equals(t3)` and `t3.equals(t3)`. The latter case is obvious enough, and with the former case, even though `t1` has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.
Apparently not. My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line `t3.equals(t3)`.
My question then is, why? As I mentioned already, even though `t1` is a reference of type Object (so static binding would invoke Object's `equals()` method), dynamic binding *should* take care of invoking the most specific version of the method based on the instantiated type of the reference. What am I missing? | Java uses static binding for overloaded methods, and dynamic binding for overridden ones. In your example, the equals method is overloaded (has a different param type than Object.equals()), so the method called is bound to the **reference** type at compile time.
Some discussion [here](http://forums.techarena.in/software-development/1070300.htm)
The fact that it is the equals method is not really relevant, other than it is a common mistake to overload instead of override it, which you are already aware of based on your answer to the problem in the interview.
Edit:
A good description [here](http://skeletoncoder.blogspot.com/2006/09/java-tutorials-overloading-is-compile.html) as well. This example is showing a similar problem related to the parameter type instead, but caused by the same issue.
I believe if the binding were actually dynamic, then any case where the caller and the parameter were an instance of Test would result in the overridden method being called. So t3.equals(o1) would be the only case that would not print. | The `equals` method of `Test` does not override the `equals` method of `java.lang.Object`. Look at the parameter type! The `Test` class is overloading `equals` with a method that accepts a `Test`.
If the `equals` method is intended to override, it should use the @Override annotation. This would cause a compilation error to point out this common mistake. | Java dynamic binding and method overriding | [
"",
"java",
"inheritance",
"dynamic-binding",
""
] |
Given an enum that has assigned values, what is the best way to get the next or previous enum given a value. For example, consider this enum:
```
public enum TimeframeType {
None = 0,
[Description("1 month")]
Now = 30,
[Description("1-3 months")]
Short = 90,
[Description("3-6 months")]
Medium = 180,
[Description("6+ months")]
Long = 360
}
```
Is there a good way create a function that would do EnumPrevious(TimeframeType.Short) returns TimeframeType.Now and EnumNext(TimeframeType.Short) would return TimeframeType.Medium?
I already wrote an ugly implementation of EnumNext but I'm not convinced that it is the best way to do so. I'm hoping someone else has already tackled this problem.
```
public static T EnumNext<T>(T value) where T : struct {
T[] values = (T[])Enum.GetValues(typeof(T));
int i;
for (i = 0; i < values.Length; i++) {
if (object.Equals(value, values[i])) {
break;
}
}
if (i >= values.Length - 1) {
return values[values.Length - 1];
} else {
return values[i + 1];
}
}
``` | You are trying to solve the wrong problem. This is far too complex for a simple enum to calculate. Refactor the enum to a class and use a comparison interface.
If this route is open to you look at how this *could* be implemented by a class:
```
public class TimeFrame: IComparable
{
private int days;
public int Days
{
set
{
days = value;
}
}
public int CompareTo(object other)
{
//see this for implementation -- http://msdn.microsoft.com/en-us/library/system.icomparable.aspx#Mtps_DropDownFilterText
}
public string Description
{
get code to return the description string , ie "1-3 months"
}
}
``` | Enums in .NET aren't really meant to be ordered, so you shouldn't rely on it. Someone else later might just come and add a value somewhere in the middle that would be out of order. Thus there also isn't such a functionality built in. You can write your own functions (similar to what you have already written) but that's completely up to you. I would also adivse you do the sorting by yourself in your method and not rely on .NET to keep the items "sorted".
**Added:** That, and I also second the opinion that you should choose another data structure. | Next or previous enum | [
"",
"c#",
"enums",
""
] |
So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing. | As for future plans of MySQLdb, you might want to ask the author (Andy Dustman).
His blog is here: <http://mysql-python.blogspot.com/> | It appears the MySQLdb is pretty much a dead project. However, [PyMySQL](https://github.com/PyMySQL/PyMySQL/) is a dbapi compliant, pure-python implementation of a mysql client, and it has python 3 support.
EDIT: There's also [MySQL Connector/Python](https://launchpad.net/myconnpy). Same idea. | MySQL-db lib for Python 3.x? | [
"",
"python",
"mysql",
"python-3.x",
""
] |
Is there a quick way to detect classes in my application that are never used? I have just taken over a project and I am trying to do some cleanup.
I do have [ReSharper](http://www.jetbrains.com/resharper/) if that helps. | I don't recommend deleting old code on a new-to-you project. That's really asking for trouble. In the best case, it might tidy things up for you, but isn't likely to help the compiler or your customer much. In all but the best case, something will break.
That said, I realize it doesn't really answer your question. For that, I point you to this related question:
[Is there a custom FxCop rule that will detect unused PUBLIC methods?](https://stackoverflow.com/questions/71518/is-there-a-custom-fxcop-rule-that-will-detect-unused-public-methods) | 1. [NDepend](http://www.ndepend.com/)
2. [Resharper 4.5](http://rabdullin.com/journal/2008/12/19/resharper-45-features-and-release-date.html) (4.0 merely detects unused private members)
3. Build your own code quality unit-tests with Mono.Cecil (some samples could be found in the *Lokad.Quality* the [this open source project](http://rabdullin.com/shared-libraries/)) | How do I find and remove unused classes to cleanup my code? | [
"",
"c#",
"resharper",
""
] |
Found the following in an Oracle-based application that we're migrating *(generalized)*:
```
SELECT
Table1.Category1,
Table1.Category2,
count(*) as Total,
count(Tab2.Stat) AS Stat
FROM Table1, Table2
WHERE (Table1.PrimaryKey = Table2.ForeignKey(+))
GROUP BY Table1.Category1, Table1.Category2
```
What does `(+)` do in a WHERE clause? I've never seen it used like that before. | Depending on which side of the "=" the "(+) is on, it denotes a LEFT OUTER or a RIGHT OUTER join (in this case, it's a left outer join). It's old Oracle syntax that is sometimes preferred by people who learned it first, since they like that it makes their code shorter.
Best not to use it though, for readability's sake. | As others have stated, the `(+)` syntax is obsolete, proprietary syntax that Oracle used for years to accomplish the same results as an `OUTER JOIN`. I assume they adopted their proprietary syntax before SQL-92 decided on the standard syntax.
The equivalent query to the one you showed, using standard SQL `OUTER JOIN` syntax (which is now supported by all major RDBMS implementations) would be the following:
```
SELECT
Table1.Category1,
Table1.Category2,
COUNT(*) AS Total,
COUNT(Table2.Stat) AS Stat
FROM Table1
LEFT OUTER JOIN Table2 ON (Table1.PrimaryKey = Table2.ForeignKey)
GROUP BY Table1.Category1, Table1.Category2;
```
Which means:
* All rows from `Table1` are included in the query result.
* Where there are matching rows in `Table2`, include those rows (repeating content from `Table1` if there are multiple matching rows in `Table2`).
* Where there are no matching rows in `Table2`, use `NULL` for all of `Table2`'s columns in the query result. | Oracle: What does `(+)` do in a WHERE clause? | [
"",
"sql",
"oracle",
"operators",
""
] |
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return `None`. This code works:
```
def main():
my_list = get_list()
if len(my_list) > 0:
return my_list[0]
return None
```
but it seems to me that there should be a simple one-line idiom for doing this. Is there? | ## Python 2.6+
```
next(iter(your_list), None)
```
If `your_list` can be `None`:
```
next(iter(your_list or []), None)
```
## Python 2.4
```
def get_first(iterable, default=None):
if iterable:
for item in iterable:
return item
return default
```
Example:
```
x = get_first(get_first_list())
if x:
...
y = get_first(get_second_list())
if y:
...
```
Another option is to inline the above function:
```
for x in get_first_list() or []:
# process x
break # process at most one item
for y in get_second_list() or []:
# process y
break
```
To avoid `break` you could write:
```
for x in yield_first(get_first_list()):
x # process x
for y in yield_first(get_second_list()):
y # process y
```
Where:
```
def yield_first(iterable):
for item in iterable or []:
yield item
return
``` | The best way is this:
```
a = get_list()
return a[0] if a else None
```
You could also do it in one line, but it's much harder for the programmer to read:
```
return (get_list()[:1] or [None])[0]
``` | Python idiom to return first item or None | [
"",
"python",
"idioms",
""
] |
I'm using SQL Server 2005 and would like to know how I can get a list of all tables with the number of records in each.
I know I can get a list of tables using the `sys.tables` view, but I'm unable to find the count.
Thank you | From here: <http://web.archive.org/web/20080701045806/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-get-a-list-of-sql-server-tables-and-their-row-counts.html>
```
SELECT
[TableName] = so.name,
[RowCount] = MAX(si.rows)
FROM
sysobjects so,
sysindexes si
WHERE
so.xtype = 'U'
AND
si.id = OBJECT_ID(so.name)
GROUP BY
so.name
ORDER BY
2 DESC
``` | For what it's worth, the sysindexes system table is deprecated in SQL 2008. The above still works, but here's query that works going forward with SQL 2008 system views.
```
select
schema_name(obj.schema_id) + '.' + obj.name,
row_count
from (
select
object_id,
row_count = sum(row_count)
from sys.dm_db_partition_stats
where index_id < 2 -- heap or clustered index
group by object_id
) Q
join sys.tables obj on obj.object_id = Q.object_id
``` | Counting rows for all tables at once | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this:
```
<main>
<object1 attr="name">content</object>
</main>
```
And turn it into something like this:
```
main
main.object1 = "content"
main.object1.attr = "name"
```
The XML data will have a more complicated structure than that and I can't hard code the element names. The attribute names need to be collected when parsing and used as the object properties.
How can I convert XML data into a Python object? | It's worth looking at [`lxml.objectify`](http://lxml.de/objectify.html).
```
xml = """<main>
<object1 attr="name">content</object1>
<object1 attr="foo">contenbar</object1>
<test>me</test>
</main>"""
from lxml import objectify
main = objectify.fromstring(xml)
main.object1[0] # content
main.object1[1] # contenbar
main.object1[0].get("attr") # name
main.test # me
```
Or the other way around to build xml structures:
```
item = objectify.Element("item")
item.title = "Best of python"
item.price = 17.98
item.price.set("currency", "EUR")
order = objectify.Element("order")
order.append(item)
order.item.quantity = 3
order.price = sum(item.price * item.quantity for item in order.item)
import lxml.etree
print(lxml.etree.tostring(order, pretty_print=True))
```
Output:
```
<order>
<item>
<title>Best of python</title>
<price currency="EUR">17.98</price>
<quantity>3</quantity>
</item>
<price>53.94</price>
</order>
``` | I've been recommending this more than once today, but try [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) (easy\_install BeautifulSoup).
```
from BeautifulSoup import BeautifulSoup
xml = """
<main>
<object attr="name">content</object>
</main>
"""
soup = BeautifulSoup(xml)
# look in the main node for object's with attr=name, optionally look up attrs with regex
my_objects = soup.main.findAll("object", attrs={'attr':'name'})
for my_object in my_objects:
# this will print a list of the contents of the tag
print my_object.contents
# if only text is inside the tag you can use this
# print tag.string
``` | How can I convert XML into a Python object? | [
"",
"python",
"xml",
""
] |
I have to work on some code that's using generic lists to store a collection of custom objects.
Then it does something like the following to check if a given object's in the collection and do something if so:
```
List<CustomObject> customObjects;
//fill up the list
List<CustomObject> anotherListofCustomObjects;
//fill it up
//...
foreach (CustomObject myCustomObject in customObjects)
{
if (anotherListofCustomObjects.Contains(myCustomObject))
{
//do stuff
}
}
```
Problem is is taking forever to process 7000 objects like that.
This is not my code - I am just trying to come up options to improve it - Looks to me it would be much faster to use a dictionary to get the stuff by key instead of looping through the whole collection like the above.
Suggestions? | Well, you seem to have answered it yourself? If you need fast query against a set of data, then a dictionary may be better than a flat list (for largish data sizes, which yours is).
You could, for example, use the object as its own key -
```
Dictionary<CustomObject,CustomObject> ...
```
Note that the meaning of equality depends on the context. If you are passing in the original reference, then that is fine - `ContainsKey` would do the job. If you have a *different but similar-for-the-purposes-of-equality* object to compare to, then you'll need to implement your own `GetHashCode()`, `Equals()`, and ideally `IEquatable<CustomObject>`. Either in `CustomObject` itself, or in a custom `IEqualityComparer<CustomObject>`. | Another way besides dictionaries is, if you're on .NET 3.5, to use Linq to objects and Intersect:
```
foreach(CustomObject c in customObjects.Intersect(anotherListOfCustomObjects))
{
// do stuff.
}
```
According to reflector, it uses Hash-based sets to perform the intersection of the sequences. | Best way of checking content of Generic List | [
"",
"c#",
".net",
"performance",
"generics",
""
] |
I need some way to add a class attribute to the output of the `label_tag()` method for a forms field.
I see that there is the ability to pass in an `attrs` dictionary and I have tested it in the shell and I can do something like:
```
for field in form:
print field.label_tag(attrs{'class':'Foo'})
```
I will see the `class='Foo'` in my output, but I don't see a way to add an `attrs` argument from the template - in fact, templates are designed specifically against that, no?
Is there a way in my form definition to define the class to be displayed in the label?
In the form, I can do the following to give the inputs a class
```
self.fields['some_field'].widget.attrs['class'] = 'Foo'
```
I just need to have it output the class for the `<label />` as well. | A [custom template tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags) seems to be the solution. A custom filter would also do, although it can be less elegant. But you would need to fall back to custom form rendering in both cases.
If this is a task of high importance; I'd create a Mixin that allows me to annotate the form fields with label classes and supplies form rendering methods using those classes. So that the following code works:
```
{{ form.as_table_with_label_classes }}
```
But I'd like to ask; Do you really need a class on the label tag? I mean HTML design-wise. Is it absolutely necessary to *add* a class in there? Couldn't it be solved with some CSS like:
```
encapsulating_selector label {
some-attr: some-value;
}
```
I sometimes use [jQuery](http://jquery.com) for such cases where; *it will improve the page if it works, but it won't be a disaster if it doesn't*. And keep the HTML source as lean as possible. | **Technique 1**
I take issue with another answer's assertion that a filter would be "less elegant." As you can see, it's very elegant indeed.
```
@register.filter(is_safe=True)
def label_with_classes(value, arg):
return value.label_tag(attrs={'class': arg})
```
Using this in a template is just as elegant:
```
{{ form.my_field|label_with_classes:"class1 class2"}}
```
**Technique 2**
Alternatively, one of the more interesting technique I've found is: [Adding \* to required fields](https://thebitguru.com/blog/908-adding-to-required-fields).
You create a decorator for BoundField.label\_tag that will call it with *attrs* set appropriately. Then you monkey patch BoundField so that calling BoundField.label\_tag calls the decorated function.
```
from django.forms.forms import BoundField
def add_control_label(f):
def control_label_tag(self, contents=None, attrs=None):
if attrs is None: attrs = {}
attrs['class'] = 'control-label'
return f(self, contents, attrs)
return control_label_tag
BoundField.label_tag = add_control_label(BoundField.label_tag)
``` | Add class to Django label_tag() output | [
"",
"python",
"django",
"forms",
"newforms",
""
] |
I'm looking for a piece of code which behaves a bit like a singleton but isn't (because singleton's are bad :) What I'm looking for must meet these goals:
1. Thread safe
2. Simple (Understand & use, i.e. few lines of code. Library calls are OK)
3. Fast
4. Not a singleton; for tests, it must be possible to overwrite the value (and reset it after the test).
5. Local (all necessary information must be in one place)
6. Lazy (run only when the value is actually needed).
7. Run once (code on RHS must be executed once and only once)
Example code:
```
private int i = runOnce(5); // Set i to 5
// Create the connection once and cache the result
private Connection db = runOnce(createDBConnection("DB_NAME"));
public void m() {
String greet = runOnce("World");
System.out.println("Hello, "+greet+"!");
}
```
Note that the fields are *not* static; only the RHS (right hand side) of the expression is ... well "static" to some degree. A test should be able to inject new values for `i` and `greet` temporarily.
Also note that this piece of code outlines how I intend to use this new code. Feel free to replace runOnce() with anything or move it to some other place (the constructor, maybe, or an init() method or a getter). But the less LOC, the better.
Some background information:
I'm not looking for Spring, I'm looking for a piece of code which can be used for the most common case: You need to implement an interface and there won't ever be a second implementation except for tests where you want to pass in mock objects. Also, Spring fails #2, #3 and #5: You need to learn the config language, you must set up the app context somewhere, it needs an XML parser and it's not local (information is spread all over the place).
A global config object or factory doesn't meet the bill because of #5.
`static final` is out because of #4 (can't change final). `static` smells because of classloader issues but you'll probably need it inside `runOnce()`. I'd just prefer to be able to avoid it in the LHS of the expression.
One possible solution might be to use [ehcache](http://ehcache.sourceforge.net/) with a default setup which would return the same object. Since I can put things in the cache, this would also allow to override the value at any time. But maybe there is a more compact/simple solution than ehcache (which again needs an XML config file, etc).
[EDIT] I'm wondering why so many people downvote this. It's a valid question and the use case is pretty common (at least in my code). So if you don't understand the question (or the reason behind it) or if you have no answer or you don't care, why downvote? :/
[EDIT2] If you look at the app context of Spring, you'll find that more than 99% of all beans have just a single implementation. You could have more but in practice, you simply don't. So instead of separating interface, implementation and configuration, I'm looking at something which has only an implementation (in the most simple case), a current() method and one or two lines of clever code to initialize the result for current() once (when it is called for the first time) but at the same times allows to override the result (thread safe, if possible). Think of it as an atomic "if(o==null) o = new O(); return o" where you can override the o. Maybe an AtomicRunOnceReference class is the solution.
Right now, I just feel that what we all have and use daily is not the optimum, that there is a baffling solution which will make us all slap our heads and say "that's it". Just as we felt when Spring came around a few years ago and we realized where all our singleton problems came from and how to solve them. | Here is a solution that fulfills all my requirements:
```
/** Lazy initialization of a field value based on the (correct)
* double checked locking idiom by Joschua Bloch
*
* <p>See "Effective Java, Second Edition", p. 283
*/
public abstract class LazyInit<T>
{
private volatile T field;
/** Return the value.
*
* <p>If the value is still <code>null</code>, the method will block and
* invoke <code>computeValue()</code>. Calls from other threads will wait
* until the call from the first thread will complete.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("UG_SYNC_SET_UNSYNC_GET")
public T get ()
{
T result = field;
if (result == null) // First check (no locking)
{
synchronized (this)
{
result = field;
if (result == null) // Second check (with locking)
{
field = result = computeValue ();
}
}
}
return result;
}
protected abstract T computeValue ();
/** Setter for tests */
public synchronized void set (T value)
{
field = value;
}
public boolean hasValue()
{
return field != null;
}
}
``` | The best idiom for threadsafe initialization code (imho) is the lazy inner class. The classic version is
```
class Outer {
class Inner {
private final static SomeInterface SINGLETON;
static {
// create the SINGLETON
}
}
public SomeInterface getMyObject() {
return Inner.SINGLETON;
}
}
```
because it's threadsafe, lazy-loading and (imho) elegant.
Now you want testability and replaceability. It's hard to advise without knowing what exactly it is but the most obvious solution would be to use dependency injection, particularly if you're using Spring and have an application context anyway.
That way your "singleton"'s behaviour is represented by an interface and you simply inject one of those into your relevant classes (or a factory to produce one) and then you can of course replace it with whatever you like for testing purposes. | Ways for lazy "run once" initialization in Java with override from unit tests | [
"",
"java",
"multithreading",
"singleton",
"lazy-evaluation",
""
] |
In C# how do you write a DataSet to file without it being written with pretty print?
Using C# and .NET 2.0, I've been using dataSet.WriteXml(fileName, XmlWriteMode.IgnoreSchema), which by default is writing the Xml file with pretty print. The company consuming the Xml files I write suggested that writing without the pretty print will not affect them, and will significantly decrease the size of the files. With a little playing around in the System.Xml namespace, I did find a solution. However, in my searching I did not find the answer anywhere, so I thought it might be helpful to someone else in the future if I posted the question. Also, I wouldn't be surprised at all if there's a better or at least different way of accomplishing this.
For those that don't know (I didn't until today), Xml "pretty print" is:
```
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Foo>
<Bar>abc</Bar>
</Foo>
</NewDataSet>
```
Without pretty print it looks like this:
```
<?xml version="1.0" encoding="utf-8"?><NewDataSet><Foo><Bar>abc</Bar></Foo></NewDataSet>
```
Additionally, the size savings was significant, 70mb files are becoming about 40mb. I'll post my solution later today if no one else has. | It's pretty simple, you just have to create an `XmlWriter` using an `XmlWriterSettings` which has the `Indent` property set to false:
```
// The memory stream for the backing.
using (MemoryStream ms = new MemoryStream())
{
// The settings for the XmlWriter.
XmlWriterSettings settings = new XmlWriterSettings();
// Do not indent.
settings.Indent = false;
// Create the XmlWriter.
using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings))
{
// Write the data set to the writer.
dataSet.WriteXml(xmlWriter);
}
}
``` | Even easier than using XmlWriterSettings:
```
XmlTextWriter xml = new XmlTextWriter(fileName, Encoding.UTF8)
{ Formatting = Formatting.None };
dataSet.WriteXml(xml);
``` | How to NOT write XML with pretty print from C# DataSet | [
"",
"c#",
"xml",
""
] |
**(resolved: see bottom)**
I have the following code snippet:
```
Protected Sub SqlDataSource1_Inserted(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)
Handles SqlDataSource1.Inserted
affected = CInt(DirectCast(e.Command.Parameters("@affected"), IDbDataParameter).Value)
newID = CInt(DirectCast(e.Command.Parameters("@newID"), IDbDataParameter).Value)
End Sub
```
Where @newID is defined like this in the SQL string:
```
"INSERT INTO x(a,b,c) VALUES (@a,@b,@c); SELECT @affected = @@rowcount, @newID = SCOPE_IDENTITY();
```
The parameters are defined using ASP.NET as follows:
The strange thing about it is that this works 90% of the time, but every once and a while it throws an InvalidCastException saying that "Conversion from type 'DBNull' to type 'Integer' is not valid." Any ideas on what could be causing this value to be null? I don't have any triggers set on the table, and the only thing my query is doing is running a plain insert into 1 table.
**Edit**: Based on the suggestions here, I added an `affected` parameter. I set a breakpoint, and affected = 1 but I still got the exception. However, I then figured out that I had SELECT @newID before SELECT @affected. I switched the order, and now @affected = 0. So it appears to be a problem with my insert statement after all. Thanks for your help! | From [MSDN](http://msdn.microsoft.com/en-us/library/ms187342.aspx)
> After an INSERT, SELECT INTO, or bulk
> copy statement is completed,
> @@IDENTITY contains the last identity
> value that is generated by the
> statement. If the statement did not
> affect any tables with identity
> columns, @@IDENTITY returns NULL.
Do you have a check to see if the insert has succeeded? It may be possible that the record you are trying to insert fails to insert anything for some reason, therefore the id is null.
Are there any triggers set up on the table? You may be retrieving the id from a trigger procedure using @@IDENTITY
I would suggest either using [SCOPE\_IDENTITY()](http://msdn.microsoft.com/en-us/library/ms190315.aspx) or an [output parameter](http://msdn.microsoft.com/en-us/library/ms378108(SQL.90).aspx) to get the id | You should use `SCOPE_IDENTITY()` as oppose to `@@IDENTITY` in 99.9% of cases. It is very rare you will have a situation that requires something other than `SCOPE_IDENTITY()`
> `@@IDENTITY` returns the last IDENTITY
> value produced on a connection,
> regardless of the table that produced
> the value, and regardless of the scope
> of the statement that produced the
> value. If you have a trigger on a
> table that causes an identity to be
> created in another table, you will get
> the identity that was created last,
> even if it was the trigger that
> created it.
>
> `SCOPE_IDENTITY()` returns the last IDENTITY value produced on a
> connection and by a statement in the
> same scope, regardless of the table
> that produced the value.
> SCOPE\_IDENTITY(), like @@IDENTITY,
> will return the last identity value
> created in the current session, but it
> will also limit it to your current
> scope as well.
Are you sure there are no auditing triggers on that table (perhaps added by your DBA)? | Why would @@IDENTITY or SCOPE_IDENTITY() be DBNull? | [
"",
"sql",
"vb.net",
"identity",
""
] |
For years and years, I've tried to understand the [part](http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4) of Java specification that deals with memory model and concurrency. I have to admit that I've failed miserably. Yes' I understand about locks and "synchronized" and wait() and notify(). And I can use them just fine, thank you. I even have a vague idea about what "volatile" does. But all of that was not derived from the language spec - rather from general experience.
Here are two sample questions that I am asking. I am not so much interested in particular answers, as I need to understand how the answers are derived from the spec (or may be how I conclude that the spec has no answer).
* What does "volatile" do, exactly?
* Are writes to variable atomic? Does it depend on variable's type? | I'm not going to attempt to actually answer your questions here - instead I'll redirect you to the book which I seeing recommended for advice on this topic: [Java Concurrency in Practice](https://rads.stackoverflow.com/amzn/click/com/0321349601).
One word of warning: if there *are* answers here, expect quite a few of them to be wrong. One of the reasons I'm not going to post details is because I'm pretty sure *I'd* get it wrong in at least some respects. I mean no disrespect whatsoever to the community when I say that the chances of everyone who thinks they can answer this question actually having enough rigour to get it right is practically zero. (Joe Duffy recently found a bit of the .NET memory model that was surprised by. If he can get it wrong, so can mortals like us.)
---
I will offer some insight on just one aspect, because it's often misunderstood:
There's a difference between volatility and atomicity. People often think that an atomic write is volatile (i.e. you don't need to worry about the memory model if the write is atomic). That's not true.
Volatility is about whether one thread performing a read (logically, in the source code) will "see" changes made by another thread.
Atomicity is about whether there is any chance that if a change *is* seen, only part of the change will be seen.
For instance, take writing to an integer field. That is guaranteed to be atomic, but not volatile. That means that if we have (starting at foo.x = 0):
```
Thread 1: foo.x = 257;
Thread 2: int y = foo.x;
```
It's possible for `y` to be 0 or 257. It won't be any other value, (e.g. 256 or 1) due to the atomicity constraint. However, even if you know that in "wall time" the code in thread 2 executed after the code in thread 1, there could be odd caching, memory accesses "moving" etc. Making the variable `x` volatile will fix this.
I'll leave the rest up to real honest-to-goodness experts. | * non-`volatile` variables can be cached thread-locally, so different threads may see different values at the same time; `volatile` prevents this ([source](http://www.javamex.com/tutorials/synchronization_volatile.shtml))
* writes to variables of 32 bits or smaller are guaranteed to be atomic ([implied here](http://java.sun.com/docs/books/jvms/second_edition/html/Threads.doc.html#22244)); not so for `long` and `double`, though 64bit JVMs probably implement them as atomic operations | Java memory model - can someone explain it? | [
"",
"java",
"concurrency",
""
] |
It is obvious what I am trying to do below, but I get the following exception:
> Unable to return a TimeSpan property value for a Duration value of 'Automatic'.
I was discouraged to read that
> NaturalDuration cannot be determined until after MediaOpened has occurred. ([link](http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer.naturalduration(VS.85).aspx))
Does this mean that I have to come up with a contrived method to open the file, wait for the media opened event in a separate thread, then return the duration only after the event has fired?
```
public static int PlayAudio(string fileName)
{
try
{
myMediaPlayer.Stop();
myMediaPlayer.Close();
myMediaPlayer.Open(new Uri(filename));
myMediaPlayer.Play();
return myMediaPlayer.NaturalDuration.TimeSpan.Milliseconds;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return -1;
}
}
``` | > I have to come up with a contrived method to open the file, wait for the media opened event in a separate thread, then return the duration only after the event has fired
That's exactly what it means, unfortunately. The below is what I just came up with for this:
```
using System;
using System.Threading;
using System.Windows.Media;
using System.Windows.Threading;
class Program
{
static void Main(string[] args)
{
var mediaFile = @"c:\path\to\mediafile.mp3";
var duration = GetMediaDuration(mediaFile, TimeSpan.FromMilliseconds(500));
Console.WriteLine(duration.ToString());
Console.ReadKey();
}
static TimeSpan GetMediaDuration(string mediaFile)
{
return GetMediaDuration(mediaFile, TimeSpan.Zero);
}
static TimeSpan GetMediaDuration(string mediaFile, TimeSpan maxTimeToWait)
{
var mediaData = new MediaData() {MediaUri = new Uri(mediaFile)};
var thread = new Thread(GetMediaDurationThreadStart);
DateTime deadline = DateTime.Now.Add(maxTimeToWait);
thread.Start(mediaData);
while (!mediaData.Done && ((TimeSpan.Zero == maxTimeToWait) || (DateTime.Now < deadline)))
Thread.Sleep(100);
Dispatcher.FromThread(thread).InvokeShutdown();
if (!mediaData.Done)
throw new Exception(string.Format("GetMediaDuration timed out after {0}", maxTimeToWait));
if (mediaData.Failure)
throw new Exception(string.Format("MediaFailed {0}", mediaFile));
return mediaData.Duration;
}
static void GetMediaDurationThreadStart(object context)
{
var mediaData = (MediaData) context;
var mediaPlayer = new MediaPlayer();
mediaPlayer.MediaOpened +=
delegate
{
if (mediaPlayer.NaturalDuration.HasTimeSpan)
mediaData.Duration = mediaPlayer.NaturalDuration.TimeSpan;
mediaData.Success = true;
mediaPlayer.Close();
};
mediaPlayer.MediaFailed +=
delegate
{
mediaData.Failure = true;
mediaPlayer.Close();
};
mediaPlayer.Open(mediaData.MediaUri);
Dispatcher.Run();
}
}
class MediaData
{
public Uri MediaUri;
public TimeSpan Duration = TimeSpan.Zero;
public bool Success;
public bool Failure;
public bool Done { get { return (Success || Failure); } }
}
``` | Yes, there is no straightforward way to open a media file and get the media duration, the reason is that the file is opened in the background (to support files that take a long time to open, for example files on remote servers), so right after you call Open the file hasn't been opened yet.
Your best option is to restructure your code so you open the file without returning the duration and then wait for the MediaOpened/MediaFailed events.
If you absolutely need to open the file and return the duration you are in for some trouble, just try to avoid Thread.Sleep since it will lock out your UI and remember the user can keep interacting with the GUI while you wait for the file to open, potentially opening another file while you wait. | How do I write a method to open, start playing, then return the duration of an audio file using a MediaPlayer in WPF? | [
"",
"c#",
"wpf",
"audio",
""
] |
Is there a way that I can get the last value (based on the '\' symbol) from a full path?
Example:
`C:\Documents and Settings\img\recycled log.jpg`
With this case, I just want to get `recycled log.jpg` from the full path in JavaScript. | ```
var filename = fullPath.replace(/^.*[\\/]/, '')
```
This will handle both / OR \ in paths. | Just for the sake of performance, I tested all the answers given here:
```
var substringTest = function (str) {
return str.substring(str.lastIndexOf('/')+1);
}
var replaceTest = function (str) {
return str.replace(/^.*(\\|\/|\:)/, '');
}
var execTest = function (str) {
return /([^\\]+)$/.exec(str)[1];
}
var splitTest = function (str) {
return str.split('\\').pop().split('/').pop();
}
substringTest took 0.09508600000000023ms
replaceTest took 0.049203000000000004ms
execTest took 0.04859899999999939ms
splitTest took 0.02505500000000005ms
```
And the winner is the **Split and Pop** style answer, Thanks to **bobince** ! | How to get the file name from a full path using JavaScript? | [
"",
"javascript",
""
] |
How do I create or use a global variable inside a function?
How do I use a global variable that was defined in one function inside other functions?
---
Failing to use the `global` keyword where appropriate often causes `UnboundLocalError`. The precise rules for this are explained at [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357). Generally, please close other questions as a duplicate of *that* question when an explanation is sought, and *this* question when someone simply needs to know the `global` keyword. | You can use a global variable within other functions by declaring it as `global` **within each function that assigns a value to it**:
```
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
```
Since it's unclear whether `globvar = 1` is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the `global` keyword.
See other answers if you want to share a global variable across modules. | If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.
Say you've got a module like this:
```
# sample.py
_my_global = 5
def func1():
_my_global = 42
def func2():
print _my_global
func1()
func2()
```
You might be expecting this to print 42, but instead, it prints 5. As has already been mentioned, if you add a '`global`' declaration to `func1()`, then `func2()` will print 42.
```
def func1():
global _my_global
_my_global = 42
```
What's going on here is that Python assumes that any name that is *assigned to*, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only *reading* from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).
When you assign 42 to the name `_my_global`, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is [garbage-collected](http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection) when `func1()` returns; meanwhile, `func2()` can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of `_my_global` inside `func1()` before you assign to it, you'd get an `UnboundLocalError`, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the '`global`' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.
(I believe that this behavior originated largely through optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.) | How to use a global variable in a function? | [
"",
"python",
"global-variables",
"scope",
""
] |
What do you find to provide the best menu for an ASP.Net 2.0 - 3.5 web application? Suggestions do not have to particularly be ASP.Net controls, but could be other menu's that work well within an ASP.Net web application.
I would like for the suggestions to be options that do not require purchasing or royalty fees. OpenSource suggestions would be even better. | I use jQuery Superfish: <http://users.tpg.com.au/j_birch/plugins/superfish/>. Highly recommended [by others](http://encosia.com/2008/10/19/7-of-my-favorite-jquery-plugins-for-use-with-aspnet/) as well. | I've found that the most flexible is to use CSS to style an unordered list like this:
```
<div id="nav_main" >
<ul>
<li id="current">Button 1</li>
<li><a href="#">Button 2</a></li>
<li><a href="#">Button 3</a></li>
<li><a href="#">Button 4</a></li>
<li><a href="#">Button 5</a></li>
</ul>
</div>
```
You'll find many CSS ways to style this kind of list with hover background images, etc.
Now if you are using Webforms and you want to use your sitemap, then I would suggest using a Repeater and NOT use the menu control. You will have the most control of your generating your list this way.
Similarly, if you are using ASP.NET MVC, you can do a foreach on your sitemap to create your list.
This of course is just for simple menus, but it can be expanded to include more complicated menus. I've found the following CSS-styled menu to be very good: <http://www.lwis.net/free-css-drop-down-menu/> | What is the best menu for an ASP.Net application? | [
"",
"asp.net",
"javascript",
"html",
"asp.net-2.0",
""
] |
How to create a java.awt.Image from image data? Image data is not pure RGB pixel data but encoded in jpeg/png format.
JavaME has a simple api Image.createImage(...) for doing this.
```
public static Image createImage(byte[] imageData,
int imageOffset,
int imageLength)
```
imageData - the array of image data in a supported image format.
Is there anything similar to this available in JavaSE? | ```
import java.awt.*;
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.createImage(imageData,imageOffset,imageLength);
``` | Use javax.imageio.ImageIO
```
BufferedImage image = ImageIO.read(new ByteArrayInputStream(myRawData));
```
**Do not** use the older functions which return an implementation of Image other than BufferedImage. The Image interface is in fact only a handle that might be loaded by a background thread and give you all kinds of headaches. | How to create a java.awt.Image from image data? | [
"",
"java",
"image",
"awt",
""
] |
I am to take up the task of porting a C++ networking application code base of quite a size from Solaris to Linux platform. The code also uses third party libraries like ACE. The application when written initially was not planned for a possible porting in future.
I would like to get some advice and suggestions as to how I go about the task. What would be the best methods to follow.
-Prabhu. S | **"There is no such thing as a portable application only applications that have been ported"**
First start with using the same tools on both platforms, if you can. I.E. if the Solaris version has not been changed to use GCC and GNU make etc, I advise you to change this first and get the Solaris build working. You will find that you will fix compiler problems first and not try to fix them on Linux at the same time as trying to port the application.
Second make sure you can get all the same libraries on each platform at the same version. I think you can get ACE for Linux. Make sure that the libraries at that version work on Solaris. This will limit compatibility problems.
Once you have done that then the real work starts.
You will need to compile each source file one at a time and find the functions that are not available in Linux. First look for a replacement that is available in both OSs. If there is no simple replacement then create two libraries one for Solaris and one for Linux. Create wrapper classes or functions to abstract the incompatibilities away.
If this sounds like a lot of work - it is. | ACE is a plus there, as it is multiplatform. You must check where and how your type sizes are used. If ACE\_\* basic types are used you are hitting a streak there, as those are portable, else I would start by changing the Solaris version into using multiplatform data types and elements (use ACE facilities since you already have that in place).
If you are using any Solaris only external library, you will have to locate an equivalent in linux and write a wrapper so that the rest of the application does not need to know what implementation is being used.
After that, migration into linux should be straight forward with just one code base. You should compile and test it through-fully. | Porting Application from Solaris to Linux | [
"",
"c++",
"linux",
"solaris",
"porting",
""
] |
I'm trying to create a query which uses a list of ids in the where clause, using the Silverlight ADO.Net Data Services client api (and therefore Linq To Entities). Does anyone know of a workaround to Contains not being supported?
I want to do something like this:
```
List<long?> txnIds = new List<long?>();
// Fill list
var q = from t in svc.OpenTransaction
where txnIds.Contains(t.OpenTransactionId)
select t;
```
---
Tried this:
```
var q = from t in svc.OpenTransaction
where txnIds.Any<long>(tt => tt == t.OpenTransactionId)
select t;
```
But got "The method 'Any' is not supported". | **Update:** EF ≥ 4 supports [`Contains`](http://msdn.microsoft.com/en-us/library/bb352880.aspx "Enumerable.Contains<T>") directly (Checkout [`Any`](http://msdn.microsoft.com/en-us/library/bb534972.aspx "Enumerable.Any<T>")), so you don't need any workaround.
```
public static IQueryable<TEntity> WhereIn<TEntity, TValue>
(
this ObjectQuery<TEntity> query,
Expression<Func<TEntity, TValue>> selector,
IEnumerable<TValue> collection
)
{
if (selector == null) throw new ArgumentNullException("selector");
if (collection == null) throw new ArgumentNullException("collection");
if (!collection.Any())
return query.Where(t => false);
ParameterExpression p = selector.Parameters.Single();
IEnumerable<Expression> equals = collection.Select(value =>
(Expression)Expression.Equal(selector.Body,
Expression.Constant(value, typeof(TValue))));
Expression body = equals.Aggregate((accumulate, equal) =>
Expression.Or(accumulate, equal));
return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
}
//Optional - to allow static collection:
public static IQueryable<TEntity> WhereIn<TEntity, TValue>
(
this ObjectQuery<TEntity> query,
Expression<Func<TEntity, TValue>> selector,
params TValue[] collection
)
{
return WhereIn(query, selector, (IEnumerable<TValue>)collection);
}
```
USAGE:
```
public static void Main()
{
using (MyObjectContext context = new MyObjectContext())
{
//Using method 1 - collection provided as collection
var contacts1 =
context.Contacts.WhereIn(c => c.Name, GetContactNames());
//Using method 2 - collection provided statically
var contacts2 = context.Contacts.WhereIn(c => c.Name,
"Contact1",
"Contact2",
"Contact3",
"Contact4"
);
}
}
``` | You can fall back on hand coding some e-sql (note the keyword "it"):
```
return CurrentDataSource.Product.Where("it.ID IN {4,5,6}");
```
Here is the code that I used to generate some e-sql from a collection, YMMV:
```
string[] ids = orders.Select(x=>x.ProductID.ToString()).ToArray();
return CurrentDataSource.Products.Where("it.ID IN {" + string.Join(",", ids) + "}");
``` | 'Contains()' workaround using Linq to Entities? | [
"",
"c#",
"linq",
"entity-framework",
".net-3.5",
"linq-to-entities",
""
] |
Some of Oracle's analytic functions allow for a [windowing clause](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm#i97640) to specify a subset of the current partition, using keywords like "unbounded preceding/following", "current row", or "value\_expr preceding/following" where value\_expr is a physical or logical offset from the current row or value (depending on whether you have specified ROW or RANGE, respectively).
Here is an example using scott/tiger that displays employees in dept 30, and a count of the number of employees in their dept hired before them (including themselves):
```
select deptno,
empno,
hiredate,
count(*) over (partition by deptno
order by hiredate
range between unbounded preceding and current row) cnt_hired_before1,
count(*) over (partition by deptno
order by hiredate
range between unbounded preceding and 0 preceding) cnt_hired_before2
from emp
where deptno = 30
order by deptno, hiredate;
```
...can anyone provide an example or documentation where "current row" is different than "0 preceding/following"? It just seems like syntactic sugar to me... | It doesn't really matter which you use. They are two different ways of expressing the windowing, but the optimizer will perform the query the same way. The term "current row" is one that is common to multiple databases with analytic functions, not just Oracle. It's more of a stylistic difference, in the same way that some people prefer count(\*) over count(1). | The Oracle documentation that I have to hand (Oracle 9.2) says:
> If you specified RANGE:
>
> * value\_expr is a logical offset. It must be a constant or expression that
> evaluates to a positive numeric value
> or an interval literal.
This implies that you shouldn't really be using 0 since it isn't a positive numeric value. But, obviously it is possible to use 0 preceding/following since you are. | Any difference between "current row" and "0 preceding/following" in windowing clause of Oracle analytic functions? | [
"",
"sql",
"oracle",
"analytics",
""
] |
I was wondering if anyone has any preference for referencing images/ css or javascript files in their sites?
The reason I ask is if a client wants to host the site we've writen under a virtual directory, the site usually has to have it's file references changed - even down to url (...image path) in CSS files because we usually develop the site as if it's a root application - sometimes the client doesn't know where they're going to host it until the day before drop-date!
Using ASP.NET we can get around the problem in the forms by referencing items using the '~' when using runat server components or the Url.Content method when using ASP.NET MVC...
So, are there any good solutions for keeping the file references generic or are we faced with having to change the file references everytime? | **Images** (like background-url) **in CSS are always referenced relative to the css file.**
Example:
```
/img/a.gif
/css/c.css
```
To reference `a.gif` from the css file, you must always reference it like such `../img/a.gif`, irrelevant to where a page is located or how it is rewritten | I like to keep all of my style images in sub-directories of the style sheet location, for example:
Site->Style->Common.css
Site->Style->Images->Background.png
This way you alleviate the issues with "up" directories in the CSS being confusing, or needing to move the CSS easily, as it is all self contained in a single directory.
Frankly, mixing style images and content images together can get a bit messy in a large site with lots of media. | JavaScript/ CSS/ Image reference paths | [
"",
"javascript",
"css",
""
] |
I'm working on a project, written in Java, which requires that I build a very large 2-D sparse array. Very sparse, if that makes a difference. Anyway: the most crucial aspect for this application is efficency in terms of time (assume loads of memory, though not nearly so unlimited as to allow me to use a standard 2-D array -- the key range is in the billions in both dimensions).
Out of the kajillion cells in the array, there will be several hundred thousand cells which contain an object. I need to be able to modify cell contents VERY quickly.
Anyway: Does anyone know a particularly good library for this purpose? It would have to be Berkeley, LGPL or similar license (no GPL, as the product can't be entirely open-sourced). Or if there's just a very simple way to make a homebrew sparse array object, that'd be fine too.
I'm considering [MTJ](http://ressim.berlios.de/), but haven't heard any opinions on its quality. | Sparsed arrays built with hashmaps are very inefficient for frequently read data. The most efficient implementations uses a Trie that allows access to a single vector where segments are distributed.
A Trie can compute if an element is present in the table by performing only read-only TWO array indexing to get the effective position where an element is stored, or to know if its absent from the underlying store.
It can also provide a default position in the backing store for the default value of the sparsed array, so that you don't need ANY test on the returned index, because the Trie guarantees that all possible source index will map at least to the default position in the backing store (where you'll frequently store a zero, or an empty string or a null object).
There exists implementations that support fast-updatable Tries, with an otional "compact()" operation to optimze the size of the backing store at end of multiple operations. Tries are MUCH faster than hashmaps, because they don't need any complex hashing function, and don't need to handle collisions for reads (With Hashmaps, you have collision BOTH for reading and for writing, this requires a loop to skip to the next candidate position, and a test on each of them to compare the effective source index...)
In addition, Java Hashmaps can only index on Objects, and creating an Integer object for each hashed source index (this object creation will be needed for every read, not just writes) is costly in terms of memory operations, as it stresses the garbage collector.
I really hoped that the JRE included an IntegerTrieMap<Object> as the default implementation for the slow HashMap<Integer, Object> or LongTrieMap<Object> as the default implementation for the even slower HashMap<Long, Object>... But this is still not the case.
---
---
You may wonder what is a Trie?
It's just a small array of integers (in a smaller range than the full range of coordinates for your matrix) that allows mapping the coordinates into an integer position in a vector.
For example suppose you want a 1024\*1024 matrix containing only a few non zero values. Instead of storing that matrix in a array containing 1024\*1024 elements (more than 1 million), you may just want to split it into subranges of size 16\*16, and you'll just need 64\*64 such subranges.
In that case, the Trie index will contain just 64\*64 integers (4096), and there will be at least 16\*16 data elements (containing the default zeroes, or the most common subrange found in your sparse matrix).
And the vector used to store the values will contain only 1 copy for subranges that are equal with each other (most of them being full of zeroes, they will be represented by the same subrange).
So instead of using a syntax like `matrix[i][j]`, you'd use a syntax like:
```
trie.values[trie.subrangePositions[(i & ~15) + (j >> 4)] +
((i & 15) << 4) + (j & 15)]
```
which will be more conveniently handled using an access method for the trie object.
Here is an example, built into a commented class (I hope it compiles OK, as it was simplified; signal me if there are errors to correct):
```
/**
* Implement a sparse matrix. Currently limited to a static size
* (<code>SIZE_I</code>, <code>SIZE_I</code>).
*/
public class DoubleTrie {
/* Matrix logical options */
public static final int SIZE_I = 1024;
public static final int SIZE_J = 1024;
public static final double DEFAULT_VALUE = 0.0;
/* Internal splitting options */
private static final int SUBRANGEBITS_I = 4;
private static final int SUBRANGEBITS_J = 4;
/* Internal derived splitting constants */
private static final int SUBRANGE_I =
1 << SUBRANGEBITS_I;
private static final int SUBRANGE_J =
1 << SUBRANGEBITS_J;
private static final int SUBRANGEMASK_I =
SUBRANGE_I - 1;
private static final int SUBRANGEMASK_J =
SUBRANGE_J - 1;
private static final int SUBRANGE_POSITIONS =
SUBRANGE_I * SUBRANGE_J;
/* Internal derived default values for constructors */
private static final int SUBRANGES_I =
(SIZE_I + SUBRANGE_I - 1) / SUBRANGE_I;
private static final int SUBRANGES_J =
(SIZE_J + SUBRANGE_J - 1) / SUBRANGE_J;
private static final int SUBRANGES =
SUBRANGES_I * SUBRANGES_J;
private static final int DEFAULT_POSITIONS[] =
new int[SUBRANGES](0);
private static final double DEFAULT_VALUES[] =
new double[SUBRANGE_POSITIONS](DEFAULT_VALUE);
/* Internal fast computations of the splitting subrange and offset. */
private static final int subrangeOf(
final int i, final int j) {
return (i >> SUBRANGEBITS_I) * SUBRANGE_J +
(j >> SUBRANGEBITS_J);
}
private static final int positionOffsetOf(
final int i, final int j) {
return (i & SUBRANGEMASK_I) * MAX_J +
(j & SUBRANGEMASK_J);
}
/**
* Utility missing in java.lang.System for arrays of comparable
* component types, including all native types like double here.
*/
public static final int arraycompare(
final double[] values1, final int position1,
final double[] values2, final int position2,
final int length) {
if (position1 >= 0 && position2 >= 0 && length >= 0) {
while (length-- > 0) {
double value1, value2;
if ((value1 = values1[position1 + length]) !=
(value2 = values2[position2 + length])) {
/* Note: NaN values are different from everything including
* all Nan values; they are are also neigher lower than nor
* greater than everything including NaN. Note that the two
* infinite values, as well as denormal values, are exactly
* ordered and comparable with <, <=, ==, >=, >=, !=. Note
* that in comments below, infinite is considered "defined".
*/
if (value1 < value2)
return -1; /* defined < defined. */
if (value1 > value2)
return 1; /* defined > defined. */
if (value1 == value2)
return 0; /* defined == defined. */
/* One or both are NaN. */
if (value1 == value1) /* Is not a NaN? */
return -1; /* defined < NaN. */
if (value2 == value2) /* Is not a NaN? */
return 1; /* NaN > defined. */
/* Otherwise, both are NaN: check their precise bits in
* range 0x7FF0000000000001L..0x7FFFFFFFFFFFFFFFL
* including the canonical 0x7FF8000000000000L, or in
* range 0xFFF0000000000001L..0xFFFFFFFFFFFFFFFFL.
* Needed for sort stability only (NaNs are otherwise
* unordered).
*/
long raw1, raw2;
if ((raw1 = Double.doubleToRawLongBits(value1)) !=
(raw2 = Double.doubleToRawLongBits(value2)))
return raw1 < raw2 ? -1 : 1;
/* Otherwise the NaN are strictly equal, continue. */
}
}
return 0;
}
throw new ArrayIndexOutOfBoundsException(
"The positions and length can't be negative");
}
/**
* Utility shortcut for comparing ranges in the same array.
*/
public static final int arraycompare(
final double[] values,
final int position1, final int position2,
final int length) {
return arraycompare(values, position1, values, position2, length);
}
/**
* Utility missing in java.lang.System for arrays of equalizable
* component types, including all native types like double here.
*/
public static final boolean arrayequals(
final double[] values1, final int position1,
final double[] values2, final int position2,
final int length) {
return arraycompare(values1, position1, values2, position2, length) ==
0;
}
/**
* Utility shortcut for identifying ranges in the same array.
*/
public static final boolean arrayequals(
final double[] values,
final int position1, final int position2,
final int length) {
return arrayequals(values, position1, values, position2, length);
}
/**
* Utility shortcut for copying ranges in the same array.
*/
public static final void arraycopy(
final double[] values,
final int srcPosition, final int dstPosition,
final int length) {
arraycopy(values, srcPosition, values, dstPosition, length);
}
/**
* Utility shortcut for resizing an array, preserving values at start.
*/
public static final double[] arraysetlength(
double[] values,
final int newLength) {
final int oldLength =
values.length < newLength ? values.length : newLength;
System.arraycopy(values, 0, values = new double[newLength], 0,
oldLength);
return values;
}
/* Internal instance members. */
private double values[];
private int subrangePositions[];
private bool isSharedValues;
private bool isSharedSubrangePositions;
/* Internal method. */
private final reset(
final double[] values,
final int[] subrangePositions) {
this.isSharedValues =
(this.values = values) == DEFAULT_VALUES;
this.isSharedsubrangePositions =
(this.subrangePositions = subrangePositions) ==
DEFAULT_POSITIONS;
}
/**
* Reset the matrix to fill it with the same initial value.
*
* @param initialValue The value to set in all cell positions.
*/
public reset(final double initialValue = DEFAULT_VALUE) {
reset(
(initialValue == DEFAULT_VALUE) ? DEFAULT_VALUES :
new double[SUBRANGE_POSITIONS](initialValue),
DEFAULT_POSITIONS);
}
/**
* Default constructor, using single default value.
*
* @param initialValue Alternate default value to initialize all
* positions in the matrix.
*/
public DoubleTrie(final double initialValue = DEFAULT_VALUE) {
this.reset(initialValue);
}
/**
* This is a useful preinitialized instance containing the
* DEFAULT_VALUE in all cells.
*/
public static DoubleTrie DEFAULT_INSTANCE = new DoubleTrie();
/**
* Copy constructor. Note that the source trie may be immutable
* or not; but this constructor will create a new mutable trie
* even if the new trie initially shares some storage with its
* source when that source also uses shared storage.
*/
public DoubleTrie(final DoubleTrie source) {
this.values = (this.isSharedValues =
source.isSharedValues) ?
source.values :
source.values.clone();
this.subrangePositions = (this.isSharedSubrangePositions =
source.isSharedSubrangePositions) ?
source.subrangePositions :
source.subrangePositions.clone());
}
/**
* Fast indexed getter.
*
* @param i Row of position to set in the matrix.
* @param j Column of position to set in the matrix.
* @return The value stored in matrix at that position.
*/
public double getAt(final int i, final int j) {
return values[subrangePositions[subrangeOf(i, j)] +
positionOffsetOf(i, j)];
}
/**
* Fast indexed setter.
*
* @param i Row of position to set in the sparsed matrix.
* @param j Column of position to set in the sparsed matrix.
* @param value The value to set at this position.
* @return The passed value.
* Note: this does not compact the sparsed matric after setting.
* @see compact(void)
*/
public double setAt(final int i, final int i, final double value) {
final int subrange = subrangeOf(i, j);
final int positionOffset = positionOffsetOf(i, j);
// Fast check to see if the assignment will change something.
int subrangePosition, valuePosition;
if (Double.compare(
values[valuePosition =
(subrangePosition = subrangePositions[subrange]) +
positionOffset],
value) != 0) {
/* So we'll need to perform an effective assignment in values.
* Check if the current subrange to assign is shared of not.
* Note that we also include the DEFAULT_VALUES which may be
* shared by several other (not tested) trie instances,
* including those instanciated by the copy contructor. */
if (isSharedValues) {
values = values.clone();
isSharedValues = false;
}
/* Scan all other subranges to check if the position in values
* to assign is shared by another subrange. */
for (int otherSubrange = subrangePositions.length;
--otherSubrange >= 0; ) {
if (otherSubrange != subrange)
continue; /* Ignore the target subrange. */
/* Note: the following test of range is safe with future
* interleaving of common subranges (TODO in compact()),
* even though, for now, subranges are sharing positions
* only between their common start and end position, so we
* could as well only perform the simpler test <code>
* (otherSubrangePosition == subrangePosition)</code>,
* instead of testing the two bounds of the positions
* interval of the other subrange. */
int otherSubrangePosition;
if ((otherSubrangePosition =
subrangePositions[otherSubrange]) >=
valuePosition &&
otherSubrangePosition + SUBRANGE_POSITIONS <
valuePosition) {
/* The target position is shared by some other
* subrange, we need to make it unique by cloning the
* subrange to a larger values vector, copying all the
* current subrange values at end of the new vector,
* before assigning the new value. This will require
* changing the position of the current subrange, but
* before doing that, we first need to check if the
* subrangePositions array itself is also shared
* between instances (including the DEFAULT_POSITIONS
* that should be preserved, and possible arrays
* shared by an external factory contructor whose
* source trie was declared immutable in a derived
* class). */
if (isSharedSubrangePositions) {
subrangePositions = subrangePositions.clone();
isSharedSubrangePositions = false;
}
/* TODO: no attempt is made to allocate less than a
* fully independant subrange, using possible
* interleaving: this would require scanning all
* other existing values to find a match for the
* modified subrange of values; but this could
* potentially leave positions (in the current subrange
* of values) unreferenced by any subrange, after the
* change of position for the current subrange. This
* scanning could be prohibitively long for each
* assignement, and for now it's assumed that compact()
* will be used later, after those assignements. */
values = setlengh(
values,
(subrangePositions[subrange] =
subrangePositions = values.length) +
SUBRANGE_POSITIONS);
valuePosition = subrangePositions + positionOffset;
break;
}
}
/* Now perform the effective assignment of the value. */
values[valuePosition] = value;
}
}
return value;
}
/**
* Compact the storage of common subranges.
* TODO: This is a simple implementation without interleaving, which
* would offer a better data compression. However, interleaving with its
* O(N²) complexity where N is the total length of values, should
* be attempted only after this basic compression whose complexity is
* O(n²) with n being SUBRANGE_POSITIIONS times smaller than N.
*/
public void compact() {
final int oldValuesLength = values.length;
int newValuesLength = 0;
for (int oldPosition = 0;
oldPosition < oldValuesLength;
oldPosition += SUBRANGE_POSITIONS) {
int oldPosition = positions[subrange];
bool commonSubrange = false;
/* Scan values for possible common subranges. */
for (int newPosition = newValuesLength;
(newPosition -= SUBRANGE_POSITIONS) >= 0; )
if (arrayequals(values, newPosition, oldPosition,
SUBRANGE_POSITIONS)) {
commonSubrange = true;
/* Update the subrangePositions|] with all matching
* positions from oldPosition to newPosition. There may
* be several index to change, if the trie has already
* been compacted() before, and later reassigned. */
for (subrange = subrangePositions.length;
--subrange >= 0; )
if (subrangePositions[subrange] == oldPosition)
subrangePositions[subrange] = newPosition;
break;
}
if (!commonSubrange) {
/* Move down the non-common values, if some previous
* subranges have been compressed when they were common.
*/
if (!commonSubrange && oldPosition != newValuesLength) {
arraycopy(values, oldPosition, newValuesLength,
SUBRANGE_POSITIONS);
/* Advance compressed values to preserve these new ones. */
newValuesLength += SUBRANGE_POSITIONS;
}
}
}
/* Check the number of compressed values. */
if (newValuesLength < oldValuesLength) {
values = values.arraysetlength(newValuesLength);
isSharedValues = false;
}
}
}
```
Note: this code is not complete because it handles a single matrix size, and its compactor is limited to detect only common subranges, without interleaving them.
Also, the code does not determine where it is the best width or height to use for splitting the matrix into subranges (for x or y coordinates), according to the matrix size. It just uses the same static subrange sizes of 16 (for both coordinates), but it could be conveniently any other small power of 2 (but a non power of 2 would slow down the `int indexOf(int, int)` and `int offsetOf(int, int)` internal methods), independantly for both coordinates, and up to the maximum width or height of the matrix.ideally the `compact()` method should be able to determine the best fitting sizes.
If these splitting subranges sizes can vary, then there will be a need to add instance members for these subrange sizes instead of the static `SUBRANGE_POSITIONS`, and to make the static methods `int subrangeOf(int i, int j)` and `int positionOffsetOf(int i, int j)` into non static; and the initialization arrays `DEFAULT_POSITIONS`and `DEFAULT_VALUES` will need to be dropped or redefined differently.
If you want to support interleaving, basically you'll start by dividing the existing values in two of about the same size (both being a multiple of the minimum subrange size, the first subset possibly having one more subrange than the second one), and you'll scan the larger one at all successive positions to find a matching interleaving; then you'll try to match these values. Then you'll loop recursely by dividing the subsets in halves (also a multiple of the minimum subrange size) and you'll scan again to match these subsets (this will multiply the number of subsets by 2: you have to wonder if the doubled size of the subrangePositions index is worth the value compared to the existing size of the values to see if it offers an effective compression (if not, you stop there: you have found the optimum subrange size directly from the interleaving compression process). In that case; the subrange size will be mutable, during compaction.
But this code shows how you assign non-zero values and reallocate the `data` array for additional (non-zero) subranges, and then how you can optimize (with `compact()` after assignments have been performed using the `setAt(int i, int j, double value)` method) the storage of this data when there are duplicate subranges that may be unified within the data, and reindexed at the same position in the `subrangePositions` array.
Anyway, all the principles of a trie are implemented there:
1. It is always faster (and more compact in memory, meaning better locality) to represent a matrix using a single vector instead of a double-indexed array of arrays (each one allocated separately). The improvement is visible in the `double getAt(int, int)` method !
2. You save a lot of space, but when assigning values it may take time to reallocate new subranges. For this reason, the subranges should not be too small or reallocations will occur too frequently for setting up your matrix.
3. It is possible to transform an initial large matrix automatically into a more compact matrix by detecting common subranges. A typical implementation will then contain a method such as `compact()` above. However, if get() access is very fast and set() is quite fast, compact() may be very slow if there are lots of common subranges to compress (for example when substracting a large non-sparse randomly-filled matrix with itself, or multiplying it by zero: it will be simpler and much faster in that case to reset the trie by instanciating a new one and dropping the old one).
4. Common subranges use common storage in the data, so this shared data must be read-only. If you must change a single value without changing the rest of the matrix, you must first make sure that it is referenced only one time in the `subrangePositions` index. Otherwise you'll need to allocate a new subrange anywhere (conveniently at end) of the `values` vector, and then store the position of this new subrange into the `subrangePositions` index.
---
---
Note that the generic Colt library, though very good as it is, is not as good when working on sparse matrice, because it uses hashing (or row-compresssed) technics which do not implement the support for tries for now, despite it is an excellent optimization, which is both space-saving **and** time-saving, notably for the most frequent getAt() operations.
Even the setAt() operation described here for tries saves lot of time (the way is is implemented here, i.e. without automatic compaction after setting, which could still be implemented based on demand and estimated time where compaction would still save lot of storage space at the price of time): the time saving is proportional to the number of cells in subranges, and space saving is inversely proportional to the number of cells per subrange. A good compromize if then to use a subrange size such the number of cells per subrange is the square root of the total number of cells in a 2D matrix (it would be a cubic root when working with 3D matrice).
Hashing technics used in Colt sparse matrix implementations have the inconvenience that they add a lot of storage overhead, and slow access time due to possible collisions. Tries can avoid all collisions, and can then warranty to save linear O(n) time to O(1) time in the worst cases, where (n) is the number of possible collisions (which, in case of sparse matrix, may be up to the number of non-default-value cells in the matrix, i.e. up to the total number of size of the matrix times a factor proportional to the hashing filling factor, for a non-sparse i.e. full matrix).
The RC (row-compressed) technics used in Colt are nearer from Tries, but this is at another price, here the compression technics used, that have very slow access time for the most frequent read-only get() operations, and very slow compression for setAt() operations. In addition, the compression used is not orthogonal, unlike in this presentation of Tries where orthogonality is preserved. Tries would also be preserve this orthogonality for related viewing operations such as striding, transposition (viewed as a striding operation based on integer cyclic modular operations), subranging (and subselections in general, including with sorting views).
I just hope that Colt will be updated in some future to implement another implementation using Tries (i.e. TrieSparseMatrix instead of just HashSparseMatrix and RCSparseMatrix). The ideas are in this article.
The Trove implementation (based in int->int maps) are also based on hashing technics similar to the Colt's HashedSparseMatrix, i.e. they have the same inconvenience. Tries will be a lot faster, with a moderate additional space consumed (but this space can be optimized and become even better than Trove and Colt, in a deferred time, using a final compact()ion operation on the resulting matrix/trie).
Note: this Trie implementation is bound to a specific native type (here double). This is voluntary, because generic implementation using boxing types have a huge space overhead (and are much slower in acccess time). Here it just uses native unidimensional arrays of double rather than generic Vector. But it is certainly possible to derive a generic implementation as well for Tries... Unfortunately, Java still does not allow writing really generic classes with all the benefits of native types, except by writing multiple implementations (for a generic Object type or for each native type), and serving all these operation via a type factory. The language should be able to automatically instanciate the native implementations and build the factory automatically (for now it is not the case even in Java 7, and this is something where .Net still maintains its advantage for really generic types that are as fast as native types). | Following framework to test Java Matrix Libraries, provides also a good list of these!
<https://lessthanoptimal.github.io/Java-Matrix-Benchmark/>
Tested Libraries:
```
* Colt
* Commons Math
* Efficient Java Matrix Library (EJML)
* Jama
* jblas
* JScience (Older benchmarks only)
* Matrix Toolkit Java (MTJ)
* OjAlgo
* Parallel Colt
* Universal Java Matrix Package (UJMP)
``` | Sparse matrices / arrays in Java | [
"",
"java",
"algorithm",
"sparse-matrix",
"sparse-array",
""
] |
Is there a good, free telnet library available for C# (not ASP .NET)? I have found a few on google, but they all have one issue or another (don't support login/password, don't support a scripted mode).
I am assuming that MS still has not included a telnet library as part of .NET v3.5 as I couldn't find it if it was. I would loooooove to be wrong though. | Best C# Telnet Lib I've found is called [Minimalistic Telnet](https://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library). Very easy to understand, use and modify. It works great for the Cisco routers I need to configure. | Here is my code that is finally working
```
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;
class TelnetTest
{
static void Main(string[] args)
{
TelnetTest tt = new TelnetTest();
tt.tcpClient = new TcpClient("myserver", 23);
tt.ns = tt.tcpClient.GetStream();
tt.connectHost("admin", "admin");
tt.sendCommand();
tt.tcpClient.Close();
}
public void connectHost(string user, string passwd) {
bool i = true;
while (i)
{
Console.WriteLine("Connecting.....");
Byte[] output = new Byte[1024];
String responseoutput = String.Empty;
Byte[] cmd = System.Text.Encoding.ASCII.GetBytes("\n");
ns.Write(cmd, 0, cmd.Length);
Thread.Sleep(1000);
Int32 bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.WriteLine("Responseoutput: " + responseoutput);
Regex objToMatch = new Regex("login:");
if (objToMatch.IsMatch(responseoutput)) {
cmd = System.Text.Encoding.ASCII.GetBytes(user + "\r");
ns.Write(cmd, 0, cmd.Length);
}
Thread.Sleep(1000);
bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.Write(responseoutput);
objToMatch = new Regex("Password");
if (objToMatch.IsMatch(responseoutput))
{
cmd = System.Text.Encoding.ASCII.GetBytes(passwd + "\r");
ns.Write(cmd, 0, cmd.Length);
}
Thread.Sleep(1000);
bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.Write("Responseoutput: " + responseoutput);
objToMatch = new Regex("#");
if (objToMatch.IsMatch(responseoutput))
{
i = false;
}
}
Console.WriteLine("Just works");
}
}
``` | C# Telnet Library | [
"",
"c#",
".net",
"telnet",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.