Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm getting tired of all this boring boilerplate code to parse application configuration like database connections, working directories, API endpoints and whatnot. Spring IoC looks nice, but this will force the user of my application to modify the XML file just to edit the database URL and so on. This might also be very distributed in the XML file where all my other wiring ocours.
What is the best technique to allow end-users to configurate services (which do not run inside an application server)? What go you guys use? | Use Spring, being explicit wiring in XML, auto-wiring or some combination thereof, to define "constant" config and then externalize the rest in properties files. Database credentials are a common example of this.
See [Spring and Ibatis Tutorial](http://www.cforcoding.com/2009/06/spring-and-ibatis-tutorial.html) for a baseline example of this. Short version:
```
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:database.properties"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.class}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
```
with database.properties (in the classpath):
```
database.username=scratch
database.password=scratch
database.class=oracle.jdbc.OracleDriver
database.url=jdbc:oracle:thin:@localhost:1521:XE
``` | you can store application configuration in a properties file and use [PropertyPlaceholderConfigurer](http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html) to load in those properties.
So, in your applicationContext file, you might have this:
```
<bean id="dataSource" class="com.x.y.z.DataSource">
<property name="url" value="${dataSource.url}" />
</bean>
```
The dataSource.url property will get loaded in from your properties file.
This is what I use in an application I'm working on, and it makes configuration much easier! | Application Configuration (Spring?) | [
"",
"java",
"spring",
""
] |
I'm new to closures and have a 'gets me by doing most things' understanding of javascript and so am wondering how I can improve etc on the following which was me trying to have an object that has a counter in it...trying to improve/further my understanding.
edit: the following code works, sure...but likely it is wrong (is it?)...I don't have even close to an idea of whether it is code that is correct or incorrect...where can i improve...is there a better way to have a timer in an object/function?
```
function myObj() {
this.outputId = 'div_output1';
this.counter = 0;
this.limit = 10;
this.count = function() {
// reference to self
var me = this;
if (me.doStuff(me)) setTimeout(function() {
me.count();
},1000);
};
this.doStuff = function(me) {
if (me.counter >= me.limit) {
document.getElementById(me.outputId).innerText = 'count reached limit';
return false;
} else {
document.getElementById(me.outputId).innerText = 'count = ' + me.counter;
me.counter += 1;
return true;
}
}
}
```
// example usage of the object...
```
window.onload = function() {
var x = new myObj;
x.outputId = 'div_output2';
x.count();
var y = new myObj;
y.limit = 8;
y.count();
}
``` | You are using closure correctly. Because when setTimeout calls your function, the 'this' will be 'Window' object and you have to create a closure (which you did by assigning 'this' to me) and accessing it.
Anyway, I would still write your code a little differently. I would make doStuff call itself instead of making it return true/false and then deciding whether to call doStuff again or not.
I don't like how you are passing the 'this' object to this.doStuff function. There is no need for that. To understand how 'this' works in JavaScript, check [my detailed answer on the subject](https://stackoverflow.com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work/1162192#1162192).
```
function Counter(opts)
{
this.outputId = opts.outputId || 'div_output1';
this._currentCount = 0;
this.limit = opts.limit || 10;
this.count = function()
{
this.deferDoStuff();
};
this.deferDoStuff = function()
{
var me = this;
setTimeout(function() { me.doStuff(); }, 1000);
};
this.doStuff = function()
{
if(this._currentCount > this.limit)
{
document.getElementById(this.outputId).innerHTML = 'Count limit reached';
return;
}
document.getElementById(this.outputId).innerHTML = 'count = ' + this._currentCount;
this._currentCount++;
this.deferDoStuff();
};
}
```
Usage:
```
var x = new Counter( { 'outputId' : 'div1' } );
var y = new Counter( { 'outputId' : 'div2' } );
x.count();
y.count();
``` | I would use the closure over `this` just for the function call in the callback function. The other methods of the object can use `this` as usual. The callback needs an explicit reference to the object because it needs to call the objects method "from the outside". But for the called method it is just a normal function call and it can use the implicit `this` to access it's object, just as usual.
I also normally move the method declaration out of the constructor into the objects prototype because it's clearer and more efficient:
```
function myObj() {
this.outputId = 'div_output1';
this.counter = 0;
this.limit = 10;
}
myObj.prototype.count = function() {
// reference to self
var me = this;
var callback = function() {
me.count();
};
if (this.doStuff())
setTimeout(callback,1000);
}
myObj.prototype.doStuff = function() {
if (this.counter >= this.limit) {
document.getElementById(this.outputId).innerText = 'count reached limit';
return false;
} else {
document.getElementById(this.outputId).innerText = 'count = ' + this.counter;
this.counter += 1;
return true;
}
}
``` | Javascript setTimout within an object/function help | [
"",
"javascript",
"closures",
""
] |
I'm relatively new to Soap on the "creating the service side", so appologies in advance for any terminology I'm munging.
Is it possible to return a PHP array from a Remote Procedure Soap Service that's been setup using PHP's SoapServer Class?
I have a WSDL (built by blindly following a tutorial) that, in part, looks something like this
```
<message name='genericString'>
<part name='Result' type='xsd:string'/>
</message>
<message name='genericObject'>
<part name='Result' type='xsd:object'/>
</message>
<portType name='FtaPortType'>
<operation name='query'>
<input message='tns:genericString'/>
<output message='tns:genericObject'/>
</operation>
</portType>
```
The PHP method I'm calling is named query, and looks something like this
```
public function query($arg){
$object = new stdClass();
$object->testing = $arg;
return $object;
}
```
This allows me to call
```
$client = new SoapClient("http://example.com/my.wsdl");
$result = $client->query('This is a test');
```
and dump of result will look something like
```
object(stdClass)[2]
public 'result' => string 'This is a test' (length=18)
```
I want to return a native PHP array/collection from my query method. If I change my query method to return an array
```
public function query($arg) {
$object = array('test','again');
return $object;
}
```
It's serialized into an object on the client side.
```
object(stdClass)[2]
public 'item' =>
array
0 => string 'test' (length=4)
1 => string 'again' (length=5)
```
This makes sense, as I've specific a `xsd:object` as the Result type in my WSDL. I'd like to, if possible, return an native PHP array that's not wrapped in an Object. My instincts say there's a specific xsd:type that will let me accomplish this, but I don't know. I'd also settle for the object being serialized as an `ArrayObject`.
Don't hold back on schooling me in the technical details os WSDL. I'm trying to get a grasp on the underlying concepts fo | I used [this WSDL generator](http://www.jool.nl/new/1,webservice_helper.html) to create description file.
Returning array of strings is something what my web service does, here's part of WSDL:
```
<wsdl:types>
<xsd:schema targetNamespace="http://schema.example.com">
<xsd:complexType name="stringArray">
<xsd:complexContent>
<xsd:restriction base="SOAP-ENC:Array">
<xsd:attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="xsd:string[]" />
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
</xsd:schema>
</wsdl:types>
<message name="notifyRequest">
<part name="parameters" type="xsd:string" />
</message>
<message name="notifyResponse">
<part name="notifyReturn" type="tns:stringArray" />
</message>
```
Then API function `notify` is defined:
```
<wsdl:operation name="notify">
<wsdl:input message="tns:notifyRequest" />
<wsdl:output message="tns:notifyResponse" />
</wsdl:operation>
``` | Little trick - encode as JSON objects, decode back into recursive associative arrays:
```
$data = json_decode(json_encode($data), true);
``` | Returning a PHP Array from a PHP SoapServer | [
"",
"php",
"soap",
"wsdl",
"soapserver",
""
] |
Does anyone know why my require\_once () or die(); is not working. It's always shown the Fatal error instead of the error message that I key in into the die(). See below for my code:
```
require_once ('abc.php') or die("oops");
```
Error message display as below
> "Fatal error: controller::require\_once() [function.require]: Failed opening required '1' (include\_path='....."
instead of the message (**"oops"**) I key in. | *or* has a higher precedence than require/require\_once. Therefore php evaluates
```
('abc.php') or die("oops")
```
before passing the result to require\_once. *Or* takes two boolean operands. ('abc.php') evaluates to *true* therefore the whole expression is *true* and
```
require_once true;
```
is invoked. require\_once takes a string, bool(true)->string => 1 =>
> Failed opening required '**1**'
You don't need the or die(...) there. If the file can't be read require\_once will stop the php instance anyway. | As [`include`](http://docs.php.net/include) is a special language construct and not a function, it doesn’t need paranthesis for the paremeter list:
> Because `include()` is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.
In fact it has just one parameter and wrapping it in additional parenthesis doesn’t change anything:
> 1 ≡ (1) ≡ ((1)) ≡ (((1))) ≡ …
So your statement is identical to this (the paremter is just wrapped):
```
require_once (('abc.php') or die("oops"));
```
So we have a boolean expression as parameter that is either *true* or *false*. And that values have the string equivalent of `"1"` and `""` respectively:
```
var_dump((string) true === "1");
var_dump((string) false === "");
```
That’s the reason why get this *Failed opening required '1'* error message.
But using parenthesis on the right place like this makes it work like you want it:
```
(@include_once 'abc.php') or die("oops");
```
Here `'abc.php'` is clearly the parameter and the disjunction with `die("oops")` is performed on the return value of `include_once`. The [`@` operator](http://docs.php.net/manual/en/language.operators.errorcontrol.php) is just to ignor the error message `includ_once` will throw if the file does not exist.
PS: [`print`](http://docs.php.net/print) is also a special language construct and works the same way. | require_once () or die() not working | [
"",
"php",
""
] |
Does \h have some special meaning? I store the username in a hidden field in my HTML, and all usernames works, but mine (which is DOMAIN\hers....) fails, it ends up like "DOMAINhers...) when picked up by Javascript (JQuery).
Any ideas? | When storing strings in JavaScript you should always escape the `\` character, by replacing `\` with `\\`. Just imagine when someone has the username `DOMAIN\noel`. That will end up like
```
DOMAIN
oel
``` | \h isn't an escape character in Javascript. | Is there a special meaning of "\h"? | [
"",
"javascript",
"html",
"escaping",
""
] |
java.util.Calendar.clone() returns "...a new Calendar with the same properties" and returns "a shallow copy of this Calendar".
This does not appear to be a shallow copy as answered [here](https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy) on SO. That question is tagged **language-agnostic,** Java does not seem to follow the language agnostic definition. As I step through the code I notice that the structure and the elements are copied to this new object, more than the language agnostic structure only.
In Java, what is a shallow copy?
How does it differ from a Java deep copy (if that exists)? | A shallow copy just copies the values of the references in the class. A deep copy copies the values. given:
```
class Foo {
private Bar myBar;
...
public Foo shallowCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar;
return newFoo;
}
public Foo deepCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar.clone(); //or new Bar(myBar) or myBar.deepCopy or ...
return newFoo;
}
}
Foo myFoo = new Foo();
Foo sFoo = myFoo.shallowCopy();
Foo dFoo = myFoo.deepCopy();
myFoo.myBar == sFoo.myBar => true
myFoo.myBar.equals(sFoo.myBar) => true
myFoo.myBar == dFoo.myBar => **false**
myFoo.myBar.equals(dFoo.myBar) => true
```
In this case the shallow copy has the same reference (`==`) and the deep copy only has an equivalent reference (`.equals()`).
If a change is made to the value of a shallowly copied reference, then the copy reflects that change because it shares the same reference. If a change is made to the value of a deeply copied reference, then the copy does not reflect that change because it does not share the same reference.
C-ism
```
int a = 10; //init
int& b = a; //shallow - copies REFERENCE
int c = a; //deep - copies VALUE
++a;
```
Result:
```
a is 11
*b is 11
c is 10
``` | Shallow copy is a just a set of pointers to the same memory locations. Actually it does not create a real copy so the memory usage is lower.
In a case of a deep copy, an exact copy of the memory segment is created and pointers are set to new memory locations. So theoritically the memory consumption should be twice in this case. | In Java, what is a shallow copy? | [
"",
"java",
"clone",
"shallow-copy",
""
] |
The software group I currently work in has recently decided to start documenting our codebase. The initial approach they have been taking was to use the built in triple slash /// method of documenting.
A newer issue we began to find was that the result of running this through doxygen is a very nice representation of the codebase but for a programmer to use, where we had intended for this documentation to be readable by our Systems Engineers who will often come to us asking what a task is doing exactly.
Is there an easy way to document our code using the /// method and doxygen in a manner that if we run it a certain way, we can generate a document that JUST contains the Systems engineering version of documentation without all the extra fluff of a standard programmers documentation that would scare away a systems guy such as methods and member variables etc.? Any alternative solution suggestions are also welcome.
I'm sorry if this is a little confusing as to what we are trying to accomplish, I can adjust as responses come in.
Thank you. | One thing you can do is to use doxygen's `\page` command, which gives you "Related Pages". Create a textfile with an extension that is processed by doxygen, and just put a comment in there. (I use .doc, but you might want to change that to something else to avoid confusion with Word documents. I am also putting these files in a common directory called `docsrc` to have them at one place.) These pages then show up in a seperate section in the docs.
```
/*!
\page foobar Foobar calculation
I am using the procedure outlined in the bla bla note to estimate
the foobar in our baz. Lorem ipsum dolor...
\section step1 1. Estimation of the foobar-efficiency of the baz system.
\author jdm
*/
```
You can then create links to the page or the sections with `\ref foobar` or `\ref step1`.
In our project, basically everyone who uses the program also codes around with it, so it is nice to have the usage documentation cross-linked with the code. But as the others pointed out, it might not be the best solution for a typical enduser-documentation. | I don't think this is going to get you what you want. It sounds like what you really want is to have good specification documentation that the Systems Engineers can use, and good Unit Tests that validate that the code runs according to those specifications. Inline code documentation is really more for the software engineers.
What's a little surprising and slightly frightening about your question is the implication that the Software Engineers are creating a system that the Systems Engineers will have to use, and that the Software Engineers are creating functionality from nothing. You should use extreme caution with having functionality be defined by your Software Engineers; they should be implementing specified functionality (and that specification should be what is used by the Systems Engineers). | C# In-Source Documentation Generation for NON-Programmers | [
"",
"c#",
"doxygen",
"documentation-generation",
""
] |
I would like to encrypt or obfuscate my WAR file so that reverse engineering will take a little more effort. Is there such a tool or maven plugin that will encrypt a WAR file and its contents?
Also, once the WAR is encrypted, how will the Web Application be deployed at that point? If the web server explodes the WAR, can each jar and resource still be encrypted, how will the startup behavior be modified to decrypt the nested jars and resources?
Thanks,
Walter | [Cracking Java byte-code encryption - Why Java obfuscation schemes based on byte-code encryption won't work](http://www.javaworld.com/javaworld/javaqa/2003-05/01-qa-0509-jcrypt.html) - Article from JavaWorld.
If your code is important enough to go to all this trouble it probably makes sense to host it on a private server... :\ | [DashO](http://www.preemptive.com/dasho-for-java.html) from PreEmptive Solutions will also obfuscate WAR files. | Encrypting War files | [
"",
"java",
"security",
"encryption",
""
] |
I know there are string tokenizers but is there an "int tokenizer"?
For example, I want to split the string "12 34 46" and have:
> list[0]=12
>
> list[1]=34
>
> list[2]=46
In particular, I'm wondering if Boost::Tokenizer does this. Although I couldn't find any examples that didn't use strings. | Yes there is: use a stream, e.g. a `stringstream`:
```
stringstream sstr("12 34 46");
int i;
while (sstr >> i)
list.push_back(i);
```
Alternatively, you can also use STL algorithms and/or iterator adapters combined with constructors:
```
vector<int> list = vector<int>(istream_iterator<int>(sstr), istream_iterator<int>());
``` | The [C++ String Toolkit Library (StrTk)](http://www.partow.net/programming/strtk/index.html) has the following solution to your problem:
```
#include <string>
#include <deque>
#include "strtk.hpp"
int main()
{
{
std::string data = "12 34 46";
std::deque<int> int_list;
strtk::parse(data," ",int_list);
}
{
std::string data = "12.12,34.34|46.46 58.58";
std::deque<double> double_list;
strtk::parse(data," ,|",double_list);
}
return 0;
}
```
More examples can be found [Here](http://www.codeproject.com/KB/recipes/Tokenizer.aspx)
Note: The parsing process is **EXTREMELY** fast and efficient, putting stdlib and boost based solutions to shame. | Int tokenizer | [
"",
"c++",
"tokenize",
""
] |
I've noticed some code that uses the static method:
```
Regex.IsMatch([someRegexStr], [someInputStr])
```
Is it worth replacing it with the instance method? Like:
```
private readonly Regex myRegex = new Regex([someRegexStr]);
...
myRegex.IsMatch([someInputStr]);
``` | One of the regular expression optimization recommendations in the following link:
[Regular Expression Optimization](http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=692) by [Jim Mischel](http://www.informit.com/authors/bio.aspx?a=18e9dac3-3dc6-4110-b55c-550e5f9bbfee)
*For better performance on commonly used regular expressions, construct a Regex object and call its instance methods.*
The [article](http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=692) contains interesting topics such as caching regular expressions and compiling regular expressions along with optimization recommendations. | The last 15 regular expression internal representations created from the static call are cached.
I talk about this and the internal workings in "[How .NET Regular Expressions Really Work](http://www.moserware.com/2009/03/how-net-regular-expressions-really-work.html)." | static vs. instance versions of Regex.Match in C# | [
"",
"c#",
"regex",
"performance",
""
] |
What is the meaning of Log Sequence Number? I know that it is of type binary and 10bytes long and it corresponds to the time the transaction happen in DB. But is this a high precision date-time value that is stored in some efficient binary format or is this a function of date-time and something else (for example the serial number of transactions that happen at the same milli second). I did a lot of searching but couldn't find a good answer to this.
Can any one explain with a formula or function that is used to derive the LSN from date-time or anything. | > Every record in the SQL Server
> transaction log is uniquely identified
> by a log sequence number (LSN). LSNs
> are ordered such that if LSN2 is
> greater than LSN1, the change
> described by the log record referred
> to by LSN2 occurred after the change
> described by the log record LSN.
From [here](http://msdn.microsoft.com/en-us/library/ms190411.aspx).
You should not be concerned with how these are generated. | First of all, sorry for replying on dead post. I came to this thread while searching other operations based on LSN.
LSN is nothing but sequential number, as it specifies - Log Sequence Number generated in three hexadecimal parts like **00000016:0000003c:0001** and these parts are as below:
* First part is VLF : **Virtual Log Files**
* Second/Middle part is OffSet : Offset to the VLF
* Last/Third part is Slot Number inside the block of log/bucket traced based on offset
Generally any DB operation along with start/end of transaction would be stored and each operation of the transaction, obviously with start and commit operation would get LSN in sequential order. Those are not related to any timestamp but can be mapped with timestamp based on sys function. @max has already replied for that.
Any commit operation towards transaction, force to switch to new log block and middle part would be incremented, otherwise last part would be increased based on the size of VLF. | What does LSN mean in SQL Server? | [
"",
"sql",
"sql-server",
"architecture",
"logging",
"cdc",
""
] |
According to the [its documentation](http://docs.python.org/library/csv.html#csv.Dialect.lineterminator) csv.writer should use '\r\n' as lineterminator by default.
```
import csv
with open("test.csv", "w") as f:
writer = csv.writer(f)
rows = [(0,1,2,3,4),
(-0,-1,-2,-3,-4),
("a","b","c","d","e"),
("A","B","C","D","E")]
print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n")
writer.writerows(rows)
print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n")
```
This prints
```
\r\n
\r\n
```
as expected. But, the created csv-file uses the lineterminator '\r\r\n'
```
0,1,2,3,4
0,-1,-2,-3,-4
a,b,c,d,e
A,B,C,D,E
```
Is this a bug or is there something wrong in my usage of csv.writer?
Python version:
> ActivePython 2.6.2.2 (ActiveState
> Software Inc.) based on Python 2.6.2
> (r262:71600, Apr 21 2009, 15:05:37)
> [MSC v.1500 32 bit (Intel)] on win32
on Windows Vista | In Python 2.x, always open your file in **binary** mode, as documented. `csv` writes `\r\n` as you expected, but then the underlying Windows text file mechanism cuts in and changes that `\n` to `\r\n` ... total effect: `\r\r\n`
From the [`csv.writer`](http://docs.python.org/library/csv.html#csv.writer) documentation:
> If *csvfile* is a file object, it must be opened with the `'b'` flag on platforms where that makes a difference.
There seems to be some reticence about actually uttering the name of the main culprit :-)
Edit: As mentioned by @jebob in the comments to this answer and based on @Dave Burton's [answer](https://stackoverflow.com/a/11235483/1224827), to handle this case in both Python 2 and 3, you should do the following:
```
if sys.version_info >= (3,0,0):
f = open(filename, 'w', newline='')
else:
f = open(filename, 'wb')
``` | Unfortunately, it's a bit different with the csv module for Python 3, but this code will work on both Python 2 and Python 3:
```
if sys.version_info >= (3,0,0):
f = open(filename, 'w', newline='')
else:
f = open(filename, 'wb')
``` | Python 2 CSV writer produces wrong line terminator on Windows | [
"",
"python",
"windows",
"csv",
"python-2.x",
"line-endings",
""
] |
Googling "csharp mode emacs" yields the page
> <http://www.emacswiki.org/emacs/CSharpMode>
which includes a few links to various downloadable emacs lisp files. The 2005 link (DylanMoonfire) is broken, so I downloaded:
> <http://lists.ximian.com/pipermail/mono-list/2002-May/006182.html>
as ~/.emacslib/csharp-mode.el
and added:
```
(autoload 'csharp-mode "csharp-mode"
"Major mode for editing C# code." t)
(setq auto-mode-alist (cons '( "\\.cs\\'" . csharp-mode ) auto-mode-alist ))
```
to my .emacs file (anywhere, beginning, middle or end). I attempt to edit a new text file called "t.cs" and I get the error:
> File mode specification error: (error "Buffer t.cs is not a CC Mode buffer (c-set-style)")
and no syntax highlighting. I'm not well versed in emacs-lisp but I know enough to install support for loads of language modes and csharp-mode is just not playing nice compared to every other language mode I've installed.
I was getting excited to play with Mono on my Mac and ran into this ridiculous barrier! Anyone out there know how to get decent support for C# syntax highlighting in emacs?
Note: I'm using a MacBook Pro running Emacs 22.1.1 on OS X Leopard. | I found a more recent version of csharp-mode [0.7.0](http://trac.codecheck.in/share/browser/dotfiles/emacs/k1low/.emacs.d/elisp/nxhtml/related/csharp-mode.el), go to the end of the page and download as plain text. Haven't tried loading the mode however.
Just uploaded the code to emacswiki as well: [charp-mode.el](http://www.emacswiki.org/emacs/csharp-mode.el) | What you have seems to be very outdated. It's too bad that the more up-to-date version was not hosted somewhere safer, like the Emacs core, EmacsWiki, or Github.
But anyway, you might as well try asking on #emacs (Freenode) and see if someone can send you the more up-to-date file. | Getting csharp-mode Emacs syntax highlighting working | [
"",
"c#",
"emacs",
"mono",
"elisp",
""
] |
Here I have a simple example to find an item in a list of strings. Normally I use a `for` loop or anonymous delegate to do it like this:
```
int GetItemIndex(string search)
{
int found = -1;
if ( _list != null )
{
foreach (string item in _list) // _list is an instance of List<string>
{
found++;
if ( string.Equals(search, item) )
{
break;
}
}
/* Use an anonymous delegate
string foundItem = _list.Find( delegate(string item) {
found++;
return string.Equals(search, item);
});
*/
}
return found;
}
```
LINQ is new for me. Can I use LINQ to find an item in the list? If it is possible, how? | If you want the index of the element, this will do it:
```
int index = list.Select((item, i) => new { Item = item, Index = i })
.First(x => x.Item == search).Index;
// or
var tagged = list.Select((item, i) => new { Item = item, Index = i });
int index = (from pair in tagged
where pair.Item == search
select pair.Index).First();
```
You can't get rid of the lambda in the first pass.
Note that this will throw if the item doesn't exist. This solves the problem by resorting to nullable ints:
```
var tagged = list.Select((item, i) => new { Item = item, Index = (int?)i });
int? index = (from pair in tagged
where pair.Item == search
select pair.Index).FirstOrDefault();
```
If you want the item:
```
// Throws if not found
var item = list.First(item => item == search);
// or
var item = (from item in list
where item == search
select item).First();
// Null if not found
var item = list.FirstOrDefault(item => item == search);
// or
var item = (from item in list
where item == search
select item).FirstOrDefault();
```
If you want to count the number of items that match:
```
int count = list.Count(item => item == search);
// or
int count = (from item in list
where item == search
select item).Count();
```
If you want all the items that match:
```
var items = list.Where(item => item == search);
// or
var items = from item in list
where item == search
select item;
```
And don't forget to check the list for `null` in any of these cases.
Or use `(list ?? Enumerable.Empty<string>())` instead of `list`. | There are a few ways (note that this is *not* a complete list).
1. [**Single**](http://msdn.microsoft.com/en-us/library/bb535118.aspx) will return a single result, but will throw an exception if it finds none or more than one (which may or may not be what you want):
```
string search = "lookforme";
List<string> myList = new List<string>();
string result = myList.Single(s => s == search);
```
Note that `SingleOrDefault()` will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.
2. [**Where**](http://msdn.microsoft.com/en-us/library/bb534803.aspx) will return all items which match your criteria, so you may get an IEnumerable<string> with one element:
```
IEnumerable<string> results = myList.Where(s => s == search);
```
3. [**First**](http://msdn.microsoft.com/en-us/library/bb535050.aspx) will return the first item which matches your criteria:
```
string result = myList.First(s => s == search);
```
Note that `FirstOrDefault()` will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception. | Find an item in a list by LINQ | [
"",
"c#",
"linq",
""
] |
One of the thing that has been confusing for me while learning C++ (and Direct3D, but that some time ago) is when you should use a pointer member in a class. For example, I can use a non-pointer declaration:
```
private:
SomeClass instance_;
```
Or I could use a pointer declaration
```
private:
Someclass * instance_
```
And then use new() on it in the constructor.
I understand that if SomeClass could be derived from another class, a COM object or is an ABC then it should be a pointer. Are there any other guidelines that I should be aware of? | A pointer has following advantages:
a) You can do a lazy initialization, that means to init / create the object only short before the first real usage.
b) The design: if you use pointers for members of an external class type, you can place a forward declaration above your class and thus don't need to include the headers of that types in your header - instead of that you include the third party headers in your .cpp - that has the advantage to reduce the compile time and prevents side effects by including too many other headers.
```
class ExtCamera; // forward declaration to external class type in "ExtCamera.h"
class MyCamera {
public:
MyCamera() : m_pCamera(0) { }
void init(const ExtCamera &cam);
private:
ExtCamera *m_pCamera; // do not use it in inline code inside header!
};
```
c) A pointer can be deleted anytime - so you have more control about the livetime and can re-create an object - for example in case of a failure. | The advantages of using a pointer are outlined by 3DH: lazy initialization, reduction in header dependencies, and control over the lifetime of the object.
The are also disadvantages. When you have a pointer data member, you probably have to write your own copy constructor and assignment operator, to make sure that a copy of the object is created properly. Of course, you also must remember to delete the object in the destructor. Also, if you add a pointer data member to an existing class, you must remember to update the copy constructor and operator=. In short, having a pointer data member is more work for you.
Another disadvantage is really the flip side of the control over the lifetime of the object pointed to by the pointer. Non-pointer data members are destroyed automagically when the object is destroyed, meaning that you can always be sure that they exist as long as the object exists. With the pointer, you have to check for it being `nullptr`, meaning also that you have to make sure to set it to `nullptr` whenever it doesn't point to anything. Having to deal with all this may easily lead to bugs.
Finally, accessing non-pointer members is likely to be faster, because they are contiguous in memory. On the other hand, accessing pointer data member pointing to an object allocated on the heap is likely to cause a cache miss, making it slower.
There is no single answer to your question. You have to look at your design, and decide whether the advantages of pointer data members outweigh the additional headache. If reducing compile time and header dependencies is important, use the [pimpl idiom](http://c2.com/cgi/wiki?PimplIdiom). If your data member may not be necessary for your object in certain cases, use a pointer, and allocate it when needed. If these do not sound like compelling reasons, and you do not want to do extra work, then do not use a pointer.
If lazy initialization and the reduction of header dependencies are important, then you should first consider using a smart pointer, like `std::unique_ptr` or `std::shared_ptr`, instead of a raw pointer. Smart pointers save you from many of the headaches of using raw pointers described above.
Of course, there are still caveats. `std::unique_ptr` cleans up after itself, so you do not need to add or modify the destructor of your class. However, it is non-copiable, so having a unique pointer as a data member makes your class non-copiable as well.
With `std::shared_ptr`, you do not have to worry about the destructor or copying or assignment. However, the shared pointer incurs a performance penalty for reference counting. | C++ - when should I use a pointer member in a class | [
"",
"c++",
"pointers",
""
] |
I am building an application that I want to have extended with modules that does some nr crunching and I would like to have R for that. What are my best options for extending my Java application with R? | You can use [JRI](http://rosuda.org/JRI/). From that website:
> JRI is a Java/R Interface, which
> allows to run R inside Java
> applications as a single thread.
> Basically it loads R dynamic library
> into Java and provides a Java API to R
> functionality. It supports both simple
> calls to R functions and a full
> running REPL.
This is part of the [rJava](http://www.rforge.net/rJava/) project (which allows calling of Java from R) | Talking to R from Java has been standardised using the REngine API. There are basically two implementations for this.
The first implementation is **JRI**. It is based on JNI, and executes the R dll inside the JVM. This means the connection is very fast. You can use full R functionality, including objects which live inside R but are accessible/modifiable in Java. The disadvantage is you cannot use multithreading.
The second implementation is **RServe**. RServe consists of a server written in C, together with a Java client. The server is started from the command line, and includes the R dll. The java client then makes a socket connection and calls R in a serialised manner. This implementation works well. The disadvantage is that, on Windows, the RServe component is not able to fork itself to handle multiple connections. Every RServe instance can only server one single user.
An alternative implementation to look out for is a Java RMI client which calls a Java server calling R using JRI. The idea is that you can use multithreading because you can talk to multiple servers at once. See <http://www.londonr.org/remoterengine-londonR.pdf>
In practice, we have used RServe together with a lot of boilerplate code for launching and managing the RServe instances. It's basically a major PITA, but it works well and has good performance. | Extend my Java application with R? | [
"",
"java",
"scripting",
"r",
"plugins",
"jvm",
""
] |
I need to add key/object pairs to a dictionary, but I of course need to first check if the key already exists otherwise I get a "**key already exists in dictionary**" error. The code below solves this but is clunky.
**What is a more elegant way of doing this without making a string helper method like this?**
```
using System;
using System.Collections.Generic;
namespace TestDictStringObject
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> currentViews = new Dictionary<string, object>();
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2");
StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1");
foreach (KeyValuePair<string, object> pair in currentViews)
{
Console.WriteLine("{0} {1}", pair.Key, pair.Value);
}
Console.ReadLine();
}
}
public static class StringHelpers
{
public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, view);
}
else
{
dict[key] = view;
}
}
}
}
``` | Just use the indexer - it will overwrite if it's already there, but it doesn't *have* to be there first:
```
Dictionary<string, object> currentViews = new Dictionary<string, object>();
currentViews["Customers"] = "view1";
currentViews["Customers"] = "view2";
currentViews["Employees"] = "view1";
currentViews["Reports"] = "view1";
```
Basically use `Add` if the existence of the key indicates a bug (so you want it to throw) and the indexer otherwise. (It's a bit like the difference between casting and using `as` for reference conversions.)
If you're using C# 3 *and you have a distinct set of keys*, you can make this even neater:
```
var currentViews = new Dictionary<string, object>()
{
{ "Customers", "view2" },
{ "Employees", "view1" },
{ "Reports", "view1" },
};
```
That won't work in your case though, as collection initializers always use `Add` which will throw on the second `Customers` entry. | What's wrong with...
```
dict[key] = view;
```
It'll automatically add the key if it's non-existent. | Is there a more elegant way of adding an item to a Dictionary<> safely? | [
"",
"c#",
"collections",
"dictionary",
""
] |
I have a file name, like "Foo.dll," for a library that I know is in the bin directory. I want to create an Assembly object for it. I'm trying to instantiate this object from a class that's not a page, so I don't have the Request object to get the path. How do I get the path I need to use Assembly.Load()? | Assembly.Load should not require a file path, rather it requires an AssemblyName. If you know that your assembly is in the standard search path (i.e. the bin directory), you should not need to know the disk path of the assembly...you only need to know its assembly name. In the case of your assembly, assuming you don't need a specific version, culture, etc., the assembly name should just be "Foo":
```
Assembly fooAssembly = Assembly.Load("Foo");
```
If you do need to load a specific version, you would do the following:
```
Assembly fooAssembly = Assembly.Load("Foo, Version=1.1.2, Culture=neutral");
```
Generally, you want to use Assembly.Load, rather than Assembly.LoadFrom or Assembly.LoadFile. LoadFrom and LoadFile work outside of the standard fusion process, and can lead to assemblies being loaded more than once, loaded from insecure locations, etc. Assembly.Load performs a "standard" load, searching the standard assembly locations such as bin, the GAC, etc., and applies all the standard security checks. | Does Assembly.LoadFile(...) work? | Load an Assembly from Bin in ASP.NET | [
"",
"c#",
"asp.net",
"vb.net",
"dll",
""
] |
Before this is marked as duplicate, I'm aware of [this](https://stackoverflow.com/questions/114819/how-get-a-vectorderived-into-a-function-that-expects-a-vectorbase-as-argume) question, but in my case we are talking about const containers.
I have 2 classes:
```
class Base { };
class Derived : public Base { };
```
And a function:
```
void register_objects(const std::set<Base*> &objects) {}
```
I would like to invoke this function as:
```
std::set<Derived*> objs;
register_objects(objs);
```
The compiler does not accept this. Why not? The set is not modifiable so there is no risk of non-Derived objects being inserted into it. How can I do this in the best way?
**Edit:**
I understand that now the compiler works in a way that `set<Base*>` and `set<Derived*>` are totally unrelated and therefor the function signature is not found. My question now however is: why does the compiler work like this? Would there be any objections to not see `const set<Derived*>` as derivative of `const set<Base*>` | The reason the compiler doesn't accept this is that the standard tells it not to.
The reason the standard tells it not to, is that the committee did not what to introduce a rule that `const MyTemplate<Derived*>` is a related type to `const MyTemplate<Base*>` even though the non-const types are not related. And they certainly didn't want a special rule for std::set, since in general the language does not make special cases for library classes.
The reason the standards committee didn't want to make those types related, is that MyTemplate might not have the semantics of a container. Consider:
```
template <typename T>
struct MyTemplate {
T *ptr;
};
template<>
struct MyTemplate<Derived*> {
int a;
void foo();
};
template<>
struct MyTemplate<Base*> {
std::set<double> b;
void bar();
};
```
Then what does it even mean to pass a `const MyTemplate<Derived*>` as a `const MyTemplate<Base*>`? The two classes have no member functions in common, and aren't layout-compatible. You'd need a conversion operator between the two, or the compiler would have no idea what to do whether they're const or not. But the way templates are defined in the standard, the compiler has no idea what to do even without the template specializations.
`std::set` itself could provide a conversion operator, but that would just have to make a copy(\*), which you can do yourself easily enough. If there were such a thing as a `std::immutable_set`, then I think it would be possible to implement that such that a `std::immutable_set<Base*>` could be constructed from a `std::immutable_set<Derived*>` just by pointing to the same pImpl. Even so, strange things would happen if you had non-virtual operators overloaded in the derived class - the base container would call the base version, so the conversion might de-order the set if it had a non-default comparator that did anything with the objects themselves instead of their addresses. So the conversion would come with heavy caveats. But anyway, there isn't an `immutable_set`, and const is not the same thing as immutable.
Also, suppose that `Derived` is related to `Base` by virtual or multiple inheritance. Then you can't just reinterpret the address of a `Derived` as the address of a `Base`: in most implementations the implicit conversion changes the address. It follows that you can't just batch-convert a structure containing `Derived*` as a structure containing `Base*` without copying the structure. But the C++ standard actually allows this to happen for any non-POD class, not just with multiple inheritance. And `Derived` is non-POD, since it has a base class. So in order to support this change to `std::set`, the fundamentals of inheritance and struct layout would have to be altered. It's a basic limitation of the C++ language that standard containers cannot be re-interpreted in the way you want, and I'm not aware of any tricks that could make them so without reducing efficiency or portability or both. It's frustrating, but this stuff is difficult.
Since your code is passing a set by value anyway, you could just make that copy:
```
std::set<Derived*> objs;
register_objects(std::set<Base*>(objs.begin(), objs.end());
```
[Edit: you've changed your code sample not to pass by value. My code still works, and afaik is the best you can do other than refactoring the calling code to use a `std::set<Base*>` in the first place.]
Writing a wrapper for `std::set<Base*>` that ensures all elements are `Derived*`, the way Java generics work, is easier than arranging for the conversion you want to be efficient. So you could do something like:
```
template<typename T, typename U>
struct MySetWrapper {
// Requirement: std::less is consistent. The default probably is,
// but for all we know there are specializations which aren't.
// User beware.
std::set<T> content;
void insert(U value) { content.insert(value); }
// might need a lot more methods, and for the above to return the right
// type, depending how else objs is used.
};
MySetWrapper<Base*,Derived*> objs;
// insert lots of values
register_objects(objs.content);
```
(\*) Actually, I guess it could copy-on-write, which in the case of a const parameter used in the typical way would mean it never needs to do the copy. But copy-on-write is a bit discredited within STL implementations, and even if it wasn't I doubt the committee would want to mandate such a heavyweight implementation detail. | `std::set<Base*>` and `std::set<Derived*>` are basically two different objects. Though the Base and Derived classes are linked via inheritance, at compiler template instantiation level they are two different instantiation(of set). | Why is is it not possible to pass a const set<Derived*> as const set<Base*> to a function? | [
"",
"c++",
"inheritance",
"stl",
""
] |
I was writing a setup.py for a Python package using setuptools and wanted to include a non-ASCII character in the long\_description field:
```
#!/usr/bin/env python
from setuptools import setup
setup(...
long_description=u"...", # in real code this value is read from a text file
...)
```
Unfortunately, passing a unicode object to setup() breaks either of the following two commands with a UnicodeEncodeError
```
python setup.py --long-description | rst2html
python setup.py upload
```
If I use a raw UTF-8 string for the long\_description field, then the following command breaks with a UnicodeDecodeError:
```
python setup.py register
```
I generally release software by running 'python setup.py sdist register upload', which means ugly hacks that look into sys.argv and pass the right object type are right out.
In the end I gave up and implemented a different ugly hack:
```
class UltraMagicString(object):
# Catch-22:
# - if I return Unicode, python setup.py --long-description as well
# as python setup.py upload fail with a UnicodeEncodeError
# - if I return UTF-8 string, python setup.py sdist register
# fails with an UnicodeDecodeError
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
def __unicode__(self):
return self.value.decode('UTF-8')
def __add__(self, other):
return UltraMagicString(self.value + str(other))
def split(self, *args, **kw):
return self.value.split(*args, **kw)
...
setup(...
long_description=UltraMagicString("..."),
...)
```
Isn't there a better way? | It is apparently a distutils bug that has been fixed in python 2.6: <http://mail.python.org/pipermail/distutils-sig/2009-September/013275.html>
Tarek suggests to patch post\_to\_server. The patch should pre-process all values in the
"data" argument and turn them into unicode and then call the original method. See <http://mail.python.org/pipermail/distutils-sig/2009-September/013277.html> | ```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name="fudz",
description="fudzily",
version="0.1",
long_description=u"bläh bläh".encode("UTF-8"), # in real code this value is read from a text file
py_modules=["fudz"],
author="David Fraser",
author_email="davidf@sjsoft.com",
url="http://en.wikipedia.org/wiki/Fudz",
)
```
I'm testing with the above code - there is no error from --long-description, only from rst2html; upload seems to work OK (although I cancel actually uploading) and register asks me for my username which I don't have. But the traceback in your comment is helpful - it's the automatic conversion to `unicode` in the `register` command that causes the problem.
See [the illusive setdefaultencoding](http://blog.ianbicking.org/illusive-setdefaultencoding.html) for more information on this - basically you want the default encoding in Python to be able to convert your encoded string back to unicode, but it's tricky to set this up. In this case I think it's worth the effort:
```
import sys
reload(sys).setdefaultencoding("UTF-8")
```
Or even to be correct you can get it from the `locale` - there's code commented out in `/usr/lib/python2.6/site.py` that you can find that does this but I'll leave that discussion for now. | What's the right way to use Unicode metadata in setup.py? | [
"",
"python",
"unicode",
"setuptools",
""
] |
Is there a way I can get a scripting of all tables, procs, and other objects from a database? I know there's an option to script the database but it only gave me some sort of top level script, certainly not a script to create all tables, procs, udfs, .etc. | From Management Studio
Right-click on your database.
Tasks -> Generate Scripts.
That should do it. | I wrote an open source command line utility named [SchemaZen](https://github.com/sethreno/schemazen#schemazen---script-and-create-sql-server-objects-quickly) that does this. It's much faster than scripting from management studio and it's output is more version control friendly. It supports scripting both schema and data.
To generate scripts run:
```
schemazen.exe script --server localhost --database db --scriptDir c:\somedir
```
Then to recreate the database from scripts run:
```
schemazen.exe create --server localhost --database db --scriptDir c:\somedir
``` | Script entire database SQL-Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
In c#, when we are writing a method which gets for example 6 parameters, and we want to break the parameters in 3 lines, how could we break the lines? | In C# you do not need to specify anything in particular to break a line into several on-screen lines.
So a method which would look like this in vb:
```
sub someMethod(param1 as String, _
param2 as Integer, _
param3 as Boolean)
doSomething()
end sub
```
Will look like this in C#
```
public void someMethod(string param1,
int param2,
bool param3) {
doSomething();
}
``` | In C# you can break the lines after any parameter name (either before of after the comma). [Stylecop](http://code.msdn.microsoft.com/sourceanalysis) (the Microsoft coding style guideline checker) suggests either all parameters on one line, or one per line - nothing in between. Like so:
```
public void Method(int param1, int param2, int param3, int param4, int param5, int param6)
{
}
public void Method(
int param1,
int param2,
int param3,
int param4,
int param5,
int param6)
{
}
```
But, there is no requirement to follow these guidelines, you can do whatever suits your internal style. | How do I break lines for a method definition with many parameters in C#? | [
"",
"c#",
""
] |
I want to write a little application for myself to learn C# and WPF.
The typical hello world in 2009 (twitter client) seems boring. I would like to hear your stands should I do a twitter client? Any other starters I could play around with and get used to c#? (I'm a longtime PHP programmer) | A Twitter client ends up being a good way to get started with WPF, for a few reasons:
* It's got lists of data with images, which gives you practice with formatting and styling lists
* There are a lot of options for styling what you're working on - partly due to the avatars, limited text blocks, etc.
* A Twitter app is the kind of application where you expect to see good UI
* There are some good libraries availble (I highly reccommed tweet#) so you don't need to bother with any of the plumbing
* It's something you can show off and be proud of - people will understand what it does
* There are plenty of complex things you can add on later if you want - skinning, drag and drop, autocomplete, spell checking, etc.
* There are some open source WPF clients out there, so you can find some sample code if you get stuck
And the number 1 reason why it's good idea... you can start contributing your code to the [Witty project](http://code.google.com/p/wittytwitter/). We'd love more help! | I recommend to write a native GUI (WPF) client for your most recent PHP project. | Good little project to do when learning C# WPF | [
"",
"c#",
"wpf",
"twitter-client",
""
] |
So, I'll be soon working on porting two APIs (C++ and C++/CLI) to use the VS2010 compiler. I think it'd be a good idea to have a head start on this. Any tips? | Breaking changes to C++/STL projects are outlined [here](http://blogs.msdn.com/vcblog/archive/2009/05/25/stl-breaking-changes-in-visual-studio-2010-beta-1.aspx).
vs2010 will also use a different build mechanism in the for of [MSBuild](http://msdn.microsoft.com/en-us/library/wea2sca5.aspx).
Unfortunately, the revamped Intellisense in [vs2010 won't extend to C++/CLI](http://blogs.msdn.com/vcblog/archive/2009/05/27/rebuilding-intellisense.aspx) which some people aren't too happy about, however native code developer can look forward to a more responsive environment (hopefully). | Tip #1: **it's a beta!** Don't expect RTM performance, stability, or anything else.
Tip #2: **Report bugs!** If you want it to ever stop acting like a beta, then you have to tell Microsoft about it on Connect (<http://connect.microsoft.com/visualstudio/>). | Things to keep in mind when migrating from VS2008 to VS2010 | [
"",
"c++",
"visual-studio-2008",
"visual-studio-2010",
"c++-cli",
"porting",
""
] |
I've spent two days on this so far and combed through every source at my disposal, so this is the last resort.
I have an X509 certificate whose public key I have stored in the iPhone's keychain (simulator only at this point). On the ASP.NET side, I've got the certificate in the cert store with a private key. When I encrypt a string on the iPhone and decrypt it on the server, I get a `CryptographicException` "Bad data." I tried the `Array.Reverse` suggested in the [`RSACryptoServiceProvider`](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx) page on a longshot, but it did not help.
I have compared the base-64 strings on both sides and they're equal. I've compared the raw byte arrays after decoding and they too are equal. If I encrypt on the server using the public key, the byte array is different from the iPhone's version and readily decrypts using the private key. The raw plaintext string is 115 characters so it's within the 256-byte limitation of my 2048-bit key.
Here's the iPhone encryption method (pretty much verbatim from the [CryptoExercise sample app](http://developer.apple.com/iphone/library/samplecode/CryptoExercise/listing15.html)'s `wrapSymmetricKey` method):
```
+ (NSData *)encrypt:(NSString *)plainText usingKey:(SecKeyRef)key error:(NSError **)err
{
size_t cipherBufferSize = SecKeyGetBlockSize(key);
uint8_t *cipherBuffer = NULL;
cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
memset((void *)cipherBuffer, 0x0, cipherBufferSize);
NSData *plainTextBytes = [plainText dataUsingEncoding:NSUTF8StringEncoding];
OSStatus status = SecKeyEncrypt(key, kSecPaddingNone,
(const uint8_t *)[plainTextBytes bytes],
[plainTextBytes length], cipherBuffer,
&cipherBufferSize);
if (status == noErr)
{
NSData *encryptedBytes = [[[NSData alloc]
initWithBytes:(const void *)cipherBuffer
length:cipherBufferSize] autorelease];
if (cipherBuffer)
{
free(cipherBuffer);
}
NSLog(@"Encrypted text (%d bytes): %@",
[encryptedBytes length], [encryptedBytes description]);
return encryptedBytes;
}
else
{
*err = [NSError errorWithDomain:@"errorDomain" code:status userInfo:nil];
NSLog(@"encrypt:usingKey: Error: %d", status);
return nil;
}
}
```
And here's the server-side C# decryption method:
```
private string Decrypt(string cipherText)
{
if (clientCert == null)
{
// Get certificate
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates)
{
if (certificate.GetNameInfo(X509NameType.SimpleName, false) == CERT)
{
clientCert = certificate;
break;
}
}
}
using (var rsa = (RSACryptoServiceProvider)clientCert.PrivateKey)
{
try
{
var encryptedBytes = Convert.FromBase64String(cipherText);
var decryptedBytes = rsa.Decrypt(encryptedBytes, false);
var plaintext = Encoding.UTF8.GetString(decryptedBytes);
return plaintext;
}
catch (CryptographicException e)
{
throw(new ApplicationException("Unable to decrypt payload.", e));
}
}
}
```
My suspicion was that there was some encoding problems between the platforms. I know that one is big-endian and the other is little-endian but I don't know enough to say which is which or how to overcome the difference. Mac OS X, Windows, and the iPhone are all little-endian so that's not the problem.
New theory: if you set the OAEP padding Boolean to false, it defaults to PKCS#1 1.5 padding. `SecKey` only has `SecPadding` definitions of `PKCS1`, `PKCS1MD2`, `PKCS1MD5`, and `PKCS1SHA1`. Perhaps Microsoft's PKCS#1 1.5 != Apple's PKCS1 and so the padding is affecting the binary output of the encryption. I tried using `kSecPaddingPKCS1` with the `fOAEP` set to `false`and it still didn't work. Apparently, `kSecPaddingPKCS1` is [equivalent](http://lists.apple.com/archives/Apple-cdsa/2009/Jul/msg00027.html) to PKCS#1 1.5. Back to the drawing board on theories…
Other newly-tried theories:
1. Certificate on iPhone (.cer file) is not exactly the same as the PKCS#12 bundle on the server (.pfx file) and so it could never work. Installed .cer file in different cert store and server-encrypted string roundtripped just fine;
2. Conversion to base-64 and act of POSTing to server resulted in oddness that wasn't present in same class roundtrip so I first tried some URLEncoding/Decoding and then posted raw binary from iPhone, verified that it was equal, and got same bad data;
3. My original string was 125 bytes so I thought it might be truncating in UTF-8 (long shot) so I cropped it down to a 44-byte string with no result;
4. Looked back over the System.Cryptography library to make sure I was using an appropriate class and discovered `RSAPKCS1KeyExchangeDeformatter`, became elated at new prospects, and dejected when it behaved exactly the same.
**Success!**
It turned out that I had some cruft in my Keychain on the iPhone Simulator that was muddying the waters, so to speak. I deleted the Keychain DB at `~/Library/Application Support/iPhone Simulator/User/Library/Keychains/keychain-2-debug.db` to cause it to be re-created and it worked fine. Thank you for all of your help. Figures it would have been something simple but non-obvious. (Two things I learned: 1) uninstalling the app from the simulator does not clear its Keychain entries and 2) start absolutely fresh periodically.)
NOTE: The generic path for the keychain file is dependent on the iOS version:
~/Library/Application Support/iPhone Simulator/[version]/Library/Keychains/keychain-2-debug.db
e.g.,
~/Library/Application Support/iPhone Simulator/4.3/Library/Keychains/keychain-2-debug.db | Well... the first step (as you say you have done) is to encrypt the same messages with the same initialization vectors using both the iPhone and the C# implementation. You should get the same output. You said you didn't, so there is a problem.
This means either:
* The iPhone implementation of RSA is incorrect.
* The .NET implementation of RSA is incorrect.
* The key files are different (or being interpreted differently).
I would suggest the first two are unlikely, however they are remotely possible.
You state: "Installed .cer file in different cert store and server-encrypted string roundtripped just fine"... this doesn't prove anything: all this proves is that given a particular random set of numbers you can encrypt/decrypt successfully on one platform. You are not guaranteeing that both platforms are seeing the same set of random numbers.
So I suggest you take it down to the lowest level possible here. Inspect the direct (byte array) inputs and outputs of the encryption on both platforms. If with the exact same (binary) inputs you don't get the same output, then you have a platform problem. I think this is unlikely, so I'm guessing you will find that the IVs are being interpreted differently. | this is my first answer on stackoverflow, so please forgive me if I do it wrong!
I can't give you a complete answer, however I had very similar issues when I tried to integrate with PHP - it seems that the format of Apple's certificate files is a little different from that which other software expects (including openssl).
Here's how I decrypt an encrypted signature in PHP - I actually extract the modulus and PK from the transmitted public key manually and use that for the RSA stuff, rather than trying to import the key:
```
// Public key format in hex (2 hex chars = 1 byte):
//30480241009b63495644db055437602b983f9a9e63d9af2540653ee91828483c7e302348760994e88097d223b048e42f561046c602405683524f00b4cd3eec7e67259c47e90203010001
//<IGNORE><--------------------------------------------- MODULUS --------------------------------------------------------------------------><??>< PK >
// We're interested in the modulus and the public key.
// PK = Public key, probably 65537
// First, generate the sha1 of the hash string:
$sha1 = sha1($hashString,true);
// Unencode the user's public Key:
$pkstr = base64_decode($publicKey);
// Skip the <IGNORE> section:
$a = 4;
// Find the very last occurrence of \x02\x03 which seperates the modulus from the PK:
$d = strrpos($pkstr,"\x02\x03");
// If something went wrong, give up:
if ($a == false || $d == false) return false;
// Extract the modulus and public key:
$modulus = substr($pkstr,$a,($d-$a));
$pk = substr($pkstr,$d+2);
// 1) Take the $signature from the user
// 2) Decode it from base64 to binary
// 3) Convert the binary $pk and $modulus into (very large!) integers (stored in strings in PHP)
// 4) Run rsa_verify, from http://www.edsko.net/misc/rsa.php
$unencoded_signature = rsa_verify(base64_decode($signature), binary_to_number($pk), binary_to_number($modulus), "512");
//Finally, does the $sha1 we calculated match the $unencoded_signature (less any padding bytes on the end)?
return ($sha1 == substr($unencoded_signature,-20)); // SHA1 is only 20 bytes, whilst signature is longer than this.
```
The objective-c that generates this public key is:
```
NSData * data = [[SecKeyWrapper sharedWrapper] getPublicKeyBits];
[req addValue:[data base64Encoding] forHTTPHeaderField: @"X-Public-Key"];
data = [[SecKeyWrapper sharedWrapper] getSignatureBytes:[signatureData dataUsingEncoding:NSUTF8StringEncoding]];
[req addValue:[data base64Encoding] forHTTPHeaderField: @"X-Signature"];
```
Using SecKeyWrapper from Apple's example project CryptoExercise (you can view the file here: <https://developer.apple.com/iphone/library/samplecode/CryptoExercise/listing15.html>)
I hope this helps? | Having trouble decrypting in C# something encrypted on iPhone using RSA | [
"",
"c#",
"iphone",
"rsa",
"encryption",
""
] |
I'm trying to get it so, every time someone donates a set amount on a page, another equal portion of an image is revealed. I've got most of the other logic down (PayPal provides nice unique "you've donated" identifiers and such), however, I'm having trouble with revealing the image bit by bit.
I tried breaking up the image into small chunks (person wants at least 250 donations until the image is totally revealed), however, that doesn't work because of multiple formatting images. Is there any better way (say, PHP image processing or perhaps CSS/Javascript)? | Why don't you just create 251 static images, one for each payment level and serve the correct static image dynamically, based on the proportion of funds received to date.
This seems to be the simplest way of doing it, the only code required is to query the payment level, and send the relevant image down to the client.
So have a `image0.jpg` (empty), `image1.jpg` (one segment), `image2.jpg` and so on, up to `image250.jpg` (all segments), and have your web application serve the correct one.
You'll need to make sure these images aren't accessible in the public area of your web site so people can't just figure out the URL and steal your "precious".
So, your web application will receive a request for `images/image.jpg`, query which image should be sent, and respond with the data stream from the actual image, something like:
```
if actual > desired:
number = 250
else:
number = int (actual * 250 / desired)
imagename = "image" + str(number) + ".jpg"
``` | The quickest way would be to use [Google Charts](http://code.google.com/apis/chart/) or PayPal's images and see if you can adapt one to your website. Otherwise, you're going to need to either generate the images dynamically, or statically generate them. Since it's not that many images, you may as well statically generate them.
You could do this with a number of tools, but [ImageMagick](http://www.imagemagick.org/script/index.php) is probably the most versatile. If you want to use you own image, here's how you could do it with ImageMagick.
```
# take your source image, and make it a known size.
#In this case, I'll make my image a 256 px square
convert flower.jpg -resize 256x256^ -gravity center -extent 256x256 flower_256.jpg
# run this command in a bash shell to generate the images
for i in $(seq -w 0 256);
do
convert flower_256.jpg -gravity west -background blue -crop ${i}x256+0+0 -extent 256x256 flower_seq_$i.jpg
done
```
You'll now have 256 images looking like this:
[](https://i.stack.imgur.com/0uBKW.jpg)
(source: [theeggeadventure.com](http://www.theeggeadventure.com/2009/reveal/flower_seq_064.jpg))
[](https://i.stack.imgur.com/EvYGY.jpg)
(source: [theeggeadventure.com](http://www.theeggeadventure.com/2009/reveal/flower_seq_128.jpg))
[](https://i.stack.imgur.com/cHwup.jpg)
(source: [theeggeadventure.com](http://www.theeggeadventure.com/2009/reveal/flower_seq_192.jpg))
[](https://i.stack.imgur.com/0zBpn.jpg)
(source: [theeggeadventure.com](http://www.theeggeadventure.com/2009/reveal/flower_seq_256.jpg))
Obviously, you can adjust the geometry or colors to suit. | Revealing an image bit by bit? | [
"",
"php",
"image",
"image-processing",
"donations",
""
] |
```
class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
tasks_query = Task.all()
tasks = tasks_query.fetch(1000)
if user:
url = users.create_logout_url(self.request.uri)
else:
url = users.create_login_url(self.request.uri)
template_values = {
'tasks': tasks,
'url': url
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Gadget(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
tasks_query = Task.all()
tasks = tasks_query.fetch(1000)
if user:
url = users.create_logout_url(self.request.uri)
else:
url = users.create_login_url(self.request.uri)
template_values = {
'tasks': tasks,
'url': url
}
path = os.path.join(os.path.dirname(__file__), 'gadget.xml')
self.response.out.write(template.render(path, template_values))
``` | Really it depends on what you expect to be common between the two classes in future. The purpose of refactoring is to identify common abstractions, not to minimise the number of lines of code.
That said, assuming the two requests are expected to differ only in the template:
```
class TaskListPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
tasks_query = Task.all()
tasks = tasks_query.fetch(1000)
if user:
url = users.create_logout_url(self.request.uri)
else:
url = users.create_login_url(self.request.uri)
template_values = {
'tasks': tasks,
'url': url
}
path = os.path.join(os.path.dirname(__file__), self.template_name())
self.response.out.write(template.render(path, template_values))
class MainPage(TaskListPage):
def template_name(self):
return 'index.html'
class Gadget(TaskListPage):
def template_name(self):
return 'gadget.xml'
``` | Refactor for what purposes? Are you getting errors, want to do something else, or...? Assuming the proper imports and url dispatching around this, I don't see anything here that has to be refactored for app engine -- so, don't keep us guessing!-) | How to refactor this Python code? | [
"",
"python",
"google-app-engine",
"refactoring",
""
] |
I have a piece of code that makes the Visual Studio 2008 IDE run very slow, consume vast amounts of memory and then eventually causes it to crash. I suspect VS is hitting an OS memory limit.
The following code is not my real application code, but it simulates the problem. Essentially I am trying to find the minimum value within a tree using LINQ.
```
class LinqTest
{
public class test
{
public int val;
public List<test> Tests;
}
private void CrashMe()
{
test t = new test();
//Uncomment this to cause the problem
//var x = t.Tests.Min(c => c.Tests.Min(d => d.Tests.Min(e => e.Tests.Min(f=>f.Tests.Min(g=>g.Tests.Min(h => h.val))))));
}
}
```
Has anyone else seen something similar? | A while ago I submitted a [bug report on MS Connect](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=476133). This morning I got a response:
> Thanks for the bug report for Visual Studio 2008!
>
> As you point out in your linked post from Eric Lippert's blog, we have limits on our ability to do type inference on such nested lambda expressions in a reasonable amount of time. That said, we could certainly try to timebox such inference or put a hard limit on lambda nesting to prevent this type of issue. Unfortunately, we're starting to lock down on what we can fix in Visual Studio 2010 and we won't be able to enforce such limits in this release.
>
> We'll definitely keep this issue in mind when planning for future releases!
>
> Alex Turner
>
> Program Manager
>
> Visual C# Compiler
and
> The following feedback item you submitted at Microsoft Connect has been updated: Product/Technology - Visual Studio and .NET Framework - Feedback ID – 476133 Feedback Title – Nested Linq Min() crashes Visual Studio 2008 IDE The following fields or values changed: Field Status changed from [Active] to [Resolved]
>
> Field Resolution changed from [None] to [Won't Fix] | I was able to repro this on my Visual Studio 2008 install. It looks like the language service is hitting an infinite loop and eventually running out of memory. Can you please file a bug on the connect site?
Connect: <http://connect.microsoft.com>
If you do file the bug, please add a comment to my answer with the bug number. | Nested Linq Min() crashes Visual Studio | [
"",
"c#",
"visual-studio-2008",
"linq",
"ide",
""
] |
When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.
I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.
"Mother's maiden name?"
lakdsjflkaj
Any suggestions as to how I should go about doing this?
**Note: I'm not ONLY using regular expressions on these 'security question answers'**
The 'answers' can be:
1. Selected from a db using a few basic sql regexes
2. Analyzed as many times as necessary using python regexes
3. Compared/pruned/scored as needed
**This is a technical question, not a philosophical one**
;-)
Thanks! | You're probably better off analyzing n-gram distribution, similar to language detection.
[This code](http://code.activestate.com/recipes/326576/) is an example of language detection using trigrams. My guess is the keyboard smashing trigrams are pretty unique and don't appear in normal language. | I would not do this - in my opinion these questions weaken the security, so as a user I always try to provide another semi-password as an answer - for you it would like mashed. Well, it is mashed, but that is exactly what I want to do.
Btw. I am not sure about the fact, that you can query the answers. Since they overcome your password protection they should be handled like passwords = stored as a hash!
**Edit:**
When I read [this article](http://www.newsbiscuit.com/2012/06/08/children-warned-name-of-first-pet-should-contain-8-characters-and-a-digit/) I instantly remembered this questions ;-) | Regex for keyboard mashing | [
"",
"python",
"regex",
"fraud-prevention",
""
] |
OK, this one is driving me nuts....
I have a string that is formed thus:
```
var newContent = string.Format("({0})\n{1}", stripped_content, reply)
```
newContent will display like:
(old text)
new text
I need a regular expression that strips away the text between parentheses with the parenthesis included AND the newline character.
The best I can come up with is:
```
const string regex = @"^(\(.*\)\s)?(?<capture>.*)";
var match= Regex.Match(original_content, regex);
var stripped_content = match.Groups["capture"].Value;
```
This works, but I want specifically to match the newline (`\n`), not any whitespace (`\s`)
Replacing `\s` with `\n` `\\n` or `\\\n` does NOT work.
Please help me hold on to my sanity!
EDIT: an example:
```
public string Reply(string old,string neww)
{
const string regex = @"^(\(.*\)\s)?(?<capture>.*)";
var match= Regex.Match(old, regex);
var stripped_content = match.Groups["capture"].Value;
var result= string.Format("({0})\n{1}", stripped_content, neww);
return result;
}
Reply("(messageOne)\nmessageTwo","messageThree") returns :
(messageTwo)
messageThree
``` | If you specify RegexOptions.Multiline then you can use `^` and `$` to match the start and end of a line, respectively.
If you don't wish to use this option, remember that a new line may be any one of the following: `\n`, `\r`, `\r\n`, so instead of looking only for `\n`, you should perhaps use something like: `[\n\r]+`, or more exactly: `(\n|\r|\r\n)`. | Actually it works but with opposite option i.e.
```
RegexOptions.Singleline
``` | Regex that matches a newline (\n) in C# | [
"",
"c#",
".net",
"regex",
""
] |
I have a simple django's query set like:
```
qs = AModel.objects.exclude(state="F").order_by("order")
```
I'd like to use it as follows:
```
qs[0:3].update(state='F')
expected = qs[3] # throws error here
```
But last statement throws:
"Cannot update a query once a slice has been taken."
How can I duplicate the query set? | It's the first line throwing the error: you can't do qs[0:3].update(). qs[0:3] is taking a slice; update() is updating the query.
update() is meant for bulk updates, resulting in SQL queries like
```
UPDATE app_model SET state = 'F' WHERE state <> 'F';
```
You're trying to update the first three items according to "order", but that can't be done with this type of UPDATE--you can't order or limit an SQL UPDATE. It needs to be written differently, eg.
```
UPDATE app_model SET state = 'F' WHERE id IN (
SELECT id FROM app_model WHERE state <> 'F' ORDER BY order LIMIT 3
) AS sub;
```
but Django can't do that for you. | You can do this:
`qs = AModel.objects.filter(id__in=
AModel.objects.exclude(state="F").order_by("order")[10]).update()` | Duplicate django query set? | [
"",
"python",
"django",
"django-models",
""
] |
I'm writing this small program to extract any number of email address from a text file. I am getting two errors, "Use of unassigned local variable." and I'm not sure why.
```
static void Main(string[] args)
{
string InputPath = @"C:\Temp\excel.txt";
string OutputPath = @"C:\Temp\emails.txt";
string EmailRegex = @"^(?:[a-zA-Z0-9_'^&/+-])+(?:\.(?:[a-zA-Z0-9_'^&/+-])+)*@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+(?:[a-zA-Z]){2,}\.?)$";
string Text = String.Empty;
StringBuilder Output;
List<string> Emails;
using (TextReader tr = new StreamReader(InputPath))
{
Text = tr.ReadToEnd();
}
MatchCollection Matches = Regex.Matches(Text,EmailRegex);
foreach (Match m in Matches)
{
Emails.Add(m.ToString().Trim()); // one error is here
}
foreach (String s in Emails)
{
Output.Append(s + ","); // the other error is here
}
using (TextWriter tw = new StreamWriter(OutputPath))
{
tw.Write(Output.ToString());
}
}
```
Sorry for the formatting ... I'm kind of pressed for time!
edit: **WOW. I'm an idiot - must be because I'm pressed for time!!!!** | You aren't initializing the StringBuilder and List.
```
StringBuilder Output = new StringBuilder();
List<string> Emails = new List<String>();
``` | The problem is here:
```
StringBuilder Output;
List<string> Emails;
```
You haven't initialized `Emails` and `Output`. Try:
```
StringBuilder Output = new StringBuilder();
List<string> Emails = new List<string>();
``` | Help with simple C# error | [
"",
"c#",
".net",
""
] |
I keep seeing people using doubles in C#. I know I read somewhere that doubles sometimes lose precision.
My question is when should a use a double and when should I use a decimal type?
Which type is suitable for money computations? (ie. greater than $100 million) | For money, **always** decimal. It's why it was created.
If numbers must add up correctly or balance, use decimal. This includes any financial storage or calculations, scores, or other numbers that people might do by hand.
If the exact value of numbers is not important, use double for speed. This includes graphics, physics or other physical sciences computations where there is already a "number of significant digits". | > My question is when should a use a
> double and when should I use a decimal
> type?
`decimal` for when you work with values in the range of 10^(+/-28) and where you have expectations about the behaviour based on base 10 representations - basically money.
`double` for when you need *relative* accuracy (i.e. losing precision in the trailing digits on large values is not a problem) across wildly different magnitudes - `double` covers more than 10^(+/-300). Scientific calculations are the best example here.
> which type is suitable for money
> computations?
decimal, *decimal*, **decimal**
Accept no substitutes.
The most important factor is that `double`, being implemented as a binary fraction, cannot accurately represent many `decimal` fractions (like 0.1) *at all* and its overall number of digits is smaller since it is 64-bit wide vs. 128-bit for `decimal`. Finally, financial applications often have to follow specific [rounding modes](http://en.wikipedia.org/wiki/Rounding) (sometimes mandated by law). `decimal` [supports these](http://www.blackwasp.co.uk/RoundingDecimals.aspx); `double` does not. | decimal vs double! - Which one should I use and when? | [
"",
"c#",
"double",
"decimal",
"precision",
"currency",
""
] |
There are a ton of SQL `JOIN` questions already, but I didn't see my answer so here it goes.
I am working with MySQL 5.0 and Wordpress Database using helper classes [wpdb](https://developer.wordpress.org/reference/classes/wpdb/) and [ezsql](https://github.com/ezSQL/ezsql). Trying to achieve the 'simple' desired output below has not proven to be easy.
Current output:
```
MemberID MemberName FruitName
-------------- --------------------- --------------
1 Al Apple
1 Al Cherry
```
Desired output:
```
MemberID MemberName FruitName
----------- -------------- ------------
1 Al Apple, Cherry
```
`MemberID` comes from the table `a`, `MemberName` comes from the tables `a` and `b`, and `FruitName` comes from the table `b`. Because I am outputting a lot of other columns from the table `a`, I have 'left joined' the two tables through this query:
```
$contents = $wpdb->get_results( $wpdb->prepare("SELECT * FROM a LEFT JOIN b ON a.MemberName = b.MemberName"));
```
I later print the columns using echo:
```
<td><?php echo $content->MemberID ?></td>
<td><?php echo $content->MemberName ?></td>
<td><?php echo $content->FruitName ?></td>
```
I assume I should try to query/join the two tables in a different manner though it may be possible to get creative in printing the columns. I found this [discussion here](http://www.eggheadcafe.com/conversation.aspx?messageid=34132286&threadid=34132286) and modeled my question after it but I don't understand their solutions and am hoping for something simpler. | GROUP BY MemberName and GROUP\_CONCAT(FruitName). For example,
```
SELECT MemberId, MemberName, GROUP_CONCAT(FruitName) FROM a LEFT JOIN b ON a.MemberName = b.MemberName GROUP BY a.MemberName;
``` | Given that you're using MySQL, I believe one of the [`GROUP_CONCAT`](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat) function (one of the available [*aggregate functions*](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions-and-modifiers.html)) will do exactly what you're looking for. | SQL join multiple values from column into one cell | [
"",
"sql",
"mysql",
"join",
"left-join",
""
] |
I have 2 projects in my solution:
1. Assembly (Basic Library)
2. Test Assembly (NUnit)
I had declared the test assembly as friends assembly in first project:
```
[assembly: InternalsVisibleTo ("Company.Product.Tests")]
```
Everything was working fine till I realised that I have forgot to setup the solution to sign my assemblies. So created a snk file and setup the visual studio project to sign the first assembly (Basic Library). Now when I compile the first project, I get following error:
> Friend assembly reference
> 'Company.Product.Tests' is invalid.
> Strong-name signed assemblies must
> specify a public key in their
> InternalsVisibleTo declarations.
I tried to extract the public key from my snk file using sn utility but it generates a wired binary file which I am unsure how to use. How can I fix the problem? | You need to sign *both* assemblies, because effectively both assemblies reference each other.
You have to put the public key in the InternalsVisibleTo attribute. For example, in Protocol Buffers I use:
```
[assembly:InternalsVisibleTo("Google.ProtocolBuffers.Test,PublicKey="+
"00240000048000009400000006020000002400005253413100040000010001008179f2dd31a648"+
"2a2359dbe33e53701167a888e7c369a9ae3210b64f93861d8a7d286447e58bc167e3d99483beda"+
"72f738140072bb69990bc4f98a21365de2c105e848974a3d210e938b0a56103c0662901efd6b78"+
"0ee6dbe977923d46a8fda18fb25c65dd73b149a5cd9f3100668b56649932dadd8cf5be52eb1dce"+
"ad5cedbf")]
```
The public key is retrieved by running
```
sn -Tp path\to\test\assembly.dll
```
Alternatively, get it from the .snk file:
```
sn -p MyStrongnameKey.snk public.pk
sn -tp public.pk
``` | You can directrly get publicKey from assembly which you interest,
without magic with sn.exe
```
<!-- language: c# -->
var assemblyName = Assembly.GetExecutingAssembly().GetName();
Console.WriteLine("{0}, PublicKey={1}",
assemblyName.Name,
string.Join("", assemblyName.GetPublicKey().Select(m => string.Format("{0:x2}", m))));
``` | How to declare a friend assembly? | [
"",
"c#",
"visual-studio-2008",
"assembly-signing",
""
] |
I need to recognize from an aplication in .NET if a drive has a specific non Windows partition. Can this be acchieved from C#? Logically I just need to know if the partition is present, I don't need to read in it.
Thanks a lot in advance. | Here are some prototype C# classes to get you started:
**How To: (Almost) Everything In WMI via C# - Part 3: Hardware**
<http://www.codeproject.com/KB/cs/EverythingInWmi03.aspx?msg=2310667>
There is also this:
[**An in-depth look at WMI and Instrumentation: Part II**](http://www.c-sharpcorner.com/UploadFile/klaus_salchner@hotmail.com/WMIPart211162005021718AM/WMIPart2.aspx) | I've not tried it myself, but the `System.Management.ManagementObject` class and its associated types give you access to WMI capabilities. One of these WMI types
```
Win32_DiskDrive
Win32_DiskPartition
Win32_LogicalDisk
```
might do the job. | Can i know how many partitions and their names has a drive from C#? | [
"",
"c#",
""
] |
I have a Stack object being worked on by multiple threads. One of the threads is a worker thread which performs a pop operation on the Stack object. I wanted to handle the case where the Stack is empty and I see two options
```
try{
Object obj = (Object) d_stackObj.pop();
}
catch (EmptyStackException e)
{ ...}
```
OR
```
if( ! d_stackObj.empty() )
Object obj = (Object) d_stackObj.pop();
else
{ ...}
```
My question is , which of the above is a better approach and why?
Thanks! | I would think that the better approach would be to check if the stack is empty as in your second example.
Catching exceptions is costly! | The second approach would work **only if** you have only one thread that can pop objects from your stack at all times.
If not, then your compound logic doesn't work correctly even though Stack itself is thread safe, as other threads may slice in between the empty() call and the pop() call. If you have more than one thread that may pop objects from your stack, you may need to do the following:
```
synchronized (d_stackObj) { // you must use the stack object as the lock
if (!d_stackObj.empty()) {
Object obj = (Object)d_stackObj.pop();
} else {
...
}
}
```
The first approach **does** work even in this case as it uses a single atomic call. | catching EmptyStackException vs. Testing is Stack is empty | [
"",
"java",
"exception",
"stack",
""
] |
Is there a placement new in .NET (like C++)?
In other words if I allocate some memory in VB.NET
```
Dim Foo(64) as Byte
```
I want to instance BarClass in the Foo memory (something like...)
```
Dim Bar as New BarClass(Foo)
```
*However, I don't see any syntax to do this.*
Instead I have to do something like:
```
Dim Foo(1) as BarClass
Foo(0) = new BarClass(x, y, z)
Foo(1) = new BarClass(x, y, z)
``` | No, there is no equivelent in .NET.
In addition, the GC is free to move your object around in memory whenever it wants (provided it hasn't been pinned to a location). This type of behavior is typically something that's avoided in most .NET code.
You can work around this by using native code and interop. | Take a look at [LayoutKind](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.layoutkind.aspx). Setting to explicit will give you c++ union like behaviour. | .NET Placement New | [
"",
"c#",
".net",
"vb.net",
"syntax",
"new-operator",
""
] |
any system defined user type past to ostream object is converted to a string or char\* ?
like cout<<4<<"Hello World";
works perfectly fine, how is this achieved? is the << operator overloaded for each and every type? is there a way to achieve it through just one generic overloaded function? what i mean is can i have just one overloaded operator method with one parameter(like void\*) and then decide inside that method how to typecast integer to char\*
Things worked partially if i overload operator << using Template i.e
```
class UIStream
{
private:
ofstream stream;
public:
UIStream();
~UIStream();
template <typename T>
UIStream& operator << (const T);
};
```
so this works
```
UIStream my_stream;
my_stream<<"bcd"<10;
```
however it gives compiler error when i do this
```
my_stream <<endl;
```
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'UIStream' (or there is no acceptable conversion)
Is not std::endl a type of object too? | After re-reading your question (as a result of a comment in this [answer](https://stackoverflow.com/questions/1133739/how-does-ofstream-or-ostream-type-cast-all-types-to-string/1133858#1133858)) I have realized that what you want is not only conversions into string (my assumptions in the other answer [here](https://stackoverflow.com/questions/1133739/how-does-ofstream-or-ostream-type-cast-all-types-to-string/1133805#1133805)), but rather forwarding into the internal ofstream.
Now, what you want to achieve is not simple, and may be overkill in most cases. In the implementation of `[make_string][3]` that I have (that forwards to an internal `ostringstream`), I don't allow for manipulators to be passed. If the user wants to add a new line (we develop under linux) they just pass a '\n' character.
Your problem is forwarding manipulators (`std::hex`, `std::endl`...). Your operator<< is defined as taking a constant instance of a type T, but manipulators are function pointers and the compiler is not able to match it against your methods.
Manipulators are functions that operate on the `std::basic_ostream` template. The `basic_ostream` template and `ostream` class are defined as:
```
template <typename TChar, typename TTraits = char_traits<TChar> >
class basic_ostream;
typedef basic_ostream<char> ostream;
// or
// typedef basic_ostream<wchar_t> if using wide characters
```
Then the possible manipulators that can be passed to a std::ostream are:
```
typedef std::ostream& (*manip1)( std::ostream& );
typedef std::basic_ios< std::ostream::char_type, std::ostream::traits_type > ios_type;
typedef ios_type& (*manip2)( ios_type& );
typedef std::ios_base& (*manip3)( std::ios_base& );
```
If you want to accept manipulators you must provide that overload in your class:
```
class mystream
{
//...
public:
template <typename T>
mystream& operator<<( T datum ) {
stream << datum;
return *this
}
// overload for manipulators
mystream& operator<<( manip1 fp ) {
stream << fp;
return *this;
}
mystream& operator<<( manip2 fp ) {
stream << fp;
return *this;
}
mystream& operator<<( manip3 fp ) {
stream << fp;
return *this;
}
};
```
In particular, the signature for endl (which may be the only one you require) is:
```
template <typename Char, typename Traits>
std::basic_ostream<Char,Traits>&
std::endl( std::basic_ostream<Char,Traits>& stream );
```
so it falls under the `manip1` type of functions. Others, like `std::hex` fall under different categories (`manip3` in this particular case) | > an i have just one overloaded operator
> method with one parameter(like void\*)
> and then decide inside that method how
> to typecast integer to char\*
No, you can't. A void \* carries no type information, so there is no way of working out what type it actually points to. | how does ofstream or ostream type cast all types to string? | [
"",
"c++",
"operators",
"operator-overloading",
"operator-keyword",
""
] |
I really want to learn more about C++. I know the basics, and I know the concepts, and I have even been able to create C++ projects myself, but my problem is being able to view, fix, and add to code I haven't written myself. I have looked at some open source projects on sourceforge, etc, but many of them are so big or there are soooo many projects available until I don't know what to do.
Are there any "small or simple" projects or tasks in C++ that will allow me to extend my knowledge of C++ by use of hands on experience? | If you are already able to create own projects, I think the best way to learn how to read&change someone's code is to get job in software company. They even will pay for it :) | Creating your own client / server application using socket programming is a big and fun area in programming which you should check out.
<http://subjects.ee.unsw.edu.au/tele3118/wk6_sockets.pdf> | Projects for C++ Beginner/Intermediate? | [
"",
"c++",
""
] |
In the current project I am working on I have come across a piece of code which seems to be overblown. I considered rewriting it to avoid more objects in memory than need be, and had trouble making a decision about whether the performance benefits from refactoring would be worth the time, and whether the current design will impact performance at any stage through out the application lifetime and therefore need to be changed.
I realised I did not have the knowledge to answer these questions. What knowledge do I need to make accurate assessments of the performance of a code design? Does anyone know any good resources on C#/Java internal workings that would help my understanding? | There is a huge amount of information out there, particularly by researching on MSDN - but...
The only way you'll really know whether you need to take the time to refactor is to profile this code. If it's bloated in terms of memory or run times, you may want to take the time to refactor it. If it runs quickly, and doesn't actually take as much memory as you expect, the gains may not be worth the effort.
Code design alone is never enough - most of the time, if you're projecting a performance pattern based off a design, your projection will be wrong. Yes, there are cases where code is obviously horribly designed, but most of the time, the (small) part that will be the actual problem is not the part where you expect the problem to exist - it's often some other small piece of code somewhere you never expect... | Great question!
Vance Morrison, CLR Perf architect wrote a 2 MSDN article to exactly address this question
Check them out
<http://msdn.microsoft.com/en-us/magazine/cc500596.aspx>
<http://msdn.microsoft.com/en-us/magazine/cc507639.aspx>
Hope this help
Thanks | How do programming/design decisions affect performance under the hood? | [
"",
"c#",
"performance",
"object",
""
] |
I am creating a custom CMS and have built a login system and was wandering how vulnerable hashing the passwords this way would be compared to just using the md5 php function like this:
```
<?php $token = md5($salt . $password . $pepper); ?>
```
Most people just add a salt but adding pepper just makes sense if your going to add salt :)
Here is how I am doing it
```
<?php $token = hash_hmac('sha512', $salt . $password . $pepper, $key); ?>
```
The $key would be a value in the database that is unique to each user.
The $salt and the $pepper are randomly generated strings.
The $password is the password of course.
Added on 07/24/09
Thanks for all your responses. Does anyone have an examples of how they do a hash script for creating passwords to store in a database? | Similar to: [https://stackoverflow.com/questions/1111494](https://stackoverflow.com/questions/1111494/are-hashed-and-salted-passwords-secure-against-dictionary-attacks)
Make sure you read this:
<http://www.matasano.com/log/958/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes/>
And this:
[bcrypt is obsolete](http://www.daemonology.net/blog/2009-05-09-scrypt-key-derivation.html) | Your method is using a stronger hash.
I don't see you opening yourself to any extra vulnerabilities. | Creating hashes for passwords | [
"",
"php",
"passwords",
"hash",
""
] |
I've seen many tutorials online that says you need to check `$_SERVER['HTTPS']` if the server is connection is secured with HTTPS. My problem is that on some of the servers I use, `$_SERVER['HTTPS']` is an undefined variable that results in an error. Is there another variable I can check that should always be defined?
Just to be clear, I am currently using this code to resolve if it is an HTTPS connection:
```
if(isset($_SERVER['HTTPS'])) {
if ($_SERVER['HTTPS'] == "on") {
$secure_connection = true;
}
}
``` | This should always work even when `$_SERVER['HTTPS']` is undefined:
```
function isSecure() {
return
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| $_SERVER['SERVER_PORT'] == 443;
}
```
The code is compatible with IIS.
From the [PHP.net documentation and user comments](http://www.php.net/manual/en/reserved.variables.server.php) :
> 1. Set to a non-empty value if the script was queried through the HTTPS protocol.
> 2. Note that when using ISAPI with IIS, the value will be "off" if the request was not made through the HTTPS protocol. (Same behaviour has been reported for IIS7 running PHP as a Fast-CGI application).
Also, Apache 1.x servers (and broken installations) might not have `$_SERVER['HTTPS']` defined even if connecting securely. Although not guaranteed, connections on port 443 are, by [convention](https://www.rfc-editor.org/rfc/rfc2818#section-2.3), likely using [secure sockets](http://en.wikipedia.org/wiki/Secure_Sockets_Layer), hence the additional port check.
Additional note: if there is a load balancer between the client and your server, this code doesn't test the connection between the client and the load balancer, but the connection between the load balancer and your server. To test the former connection, you would have to test using the `HTTP_X_FORWARDED_PROTO` header, but it's much more complex to do; see [latest comments](https://stackoverflow.com/questions/1175096/how-to-find-out-if-youre-using-https-without-serverhttps/2886224#comment102520055_2886224) below this answer. | My solution (because the standard conditions [$\_SERVER['HTTPS'] == 'on'] do not work on servers behind a load balancer) is:
```
$isSecure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$isSecure = true;
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$isSecure = true;
}
$REQUEST_PROTOCOL = $isSecure ? 'https' : 'http';
```
HTTP\_X\_FORWARDED\_PROTO: a *de facto* standard for identifying the originating protocol of an HTTP request, since a reverse proxy (load balancer) may communicate with a web server using HTTP even if the request to the reverse proxy is HTTPS
<http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Common_non-standard_request_headers> | How to find out if you're using HTTPS without $_SERVER['HTTPS'] | [
"",
"php",
"https",
""
] |
I'm trying to code a very rudimentary GTD app for myself, not only to get organized, but to get better at coding and get better at Python. I'm having a bit of trouble with the classes however.
Here are the classes I have so far:
```
class Project:
def __init__(self, name, actions=[]):
self.name = name
self.actions = actions
def add(self, action):
self.actions.append(action)
class Action:
def __init__(self, do='', context=''):
self.do = do
self.context = context
```
Each project has actions to it, however I want to make it so that projects can also consist of other projects. Say daily I wanted to print out a list of everything. I'm having trouble coming up with how I would construct a list that looked like this
```
> Project A
> Actions for Project A
> Project B
> Sub project A
> Actions for Sub project A
> Sub project B
> Actions for Sub project B
> Sub project C
> Sub sub project A
> Actions for sub sub project A
> Sub sub project B
> Actions for sub sub project B
> Actions for Sub project C
> Actions for Project B
```
It's quite clear to me that recursion is going to be used. I'm struggling with whether to create another class called SubProject and subclass Project to it. Something there just makes my brain raise an exception.
I have been able to take projects and add them to the actions attribute in the Project class, however then I run into where MegaProject.actions.action.actions.action situations start popping up.
If anyone could help out with the class structures, it would be greatly appreciated! | You could create a subprojects member, similar to your actions list, and assign projects to it in a similar way. No subclassing of Project is necessary.
```
class Project:
def __init__(self, name, actions=[], subprojects=[]):
self.name = name
self.actions = actions
self.subprojects = subprojects
def add(self, action):
self.actions.append(action)
def add_project(self, project)
self.subprojects.append(project)
```
Even better, you may want to implement a composite pattern, where Projects are composites and Actions are leaves.
```
class Project:
def __init__(self, name, children=[]):
self.name = name
self.children = children
def add(self, object):
self.children.append(object)
def mark_done(self):
for c in self.children:
c.mark_done()
class Action:
def __init__(self, do):
self.do = do
self.done = False
def mark_done(self):
self.done = True
```
They key here is that the projects have the same interface as the actions (with the exception of the add/delete methods). This allows to to call methods on entire tree recursively. If you had a complex nested structure, you can call a method on the top level, and have it filter down to the bottom.
If you'd like a method to get a flat list of all leaf nodes in the tree (Actions) you can implement a method like this in the Project class.
```
def get_action_list(self):
actions = []
for c in self.children:
if c.__class__ == self.__class__:
actions += c.get_action_list()
else:
actions.append(c)
return actions
``` | I suggest you look at the [composite pattern](http://en.wikipedia.org/wiki/Composite_pattern) which can be applied to the "Project" class. If you make your structure correctly, you should be able to make action be a leaf of that tree, pretty much like you described in your example.
You could, for instance, do a Project class (abstract), a ProjectComposite class (concrete) and your action class as a leaf. | Python classes for simple GTD app | [
"",
"python",
"recursion",
"gtd",
""
] |
I recently developed an interop user control in .NET (Visual Studio 2008, project targetting .NET 2.0) to be used in a VB6 application. The assembly exposes 1 control, 1 class, and a few enums and structs. I developed it using C# translations of the [Interop Forms Toolkit 2.0](http://www.microsoft.com/downloads/details.aspx?FamilyId=934DE3C5-DC85-4065-9327-96801E57B81D&displaylang=en) project template [found here](http://www.codeproject.com/KB/vb-interop/VB6InteropToolkit2.aspx). The assembly has a strong name and gets installed in the GAC and registered with regasm with the following script:
```
@"C:\gacutil.exe" /i "C:\Program Files\AppName\Control.dll" /f
@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm.exe" "C:\Program Files\AppName\Control.dll" /tlb:"C:\Program Files\AppName\Control.tlb"
```
**The Problem:** When I compile the VB6 app on my machine, it will run just fine on any other machine (control installed, of course). However, when the app is compiled on a different machine, it will run on that machine, but not on any other machine. And when I say it doesn't run, I mean you try to run it and absolutely nothing happens.
I used OleView to examine the control on both my machine and the other machine, and all GUIDs are the same in the type information. The only difference was one had the line importlib("stdole2.tlb") and the other had importlib("STDOLE2.TLB").
My machine has: Visual Studio 6.0 sp6, VB6 interop user control templates, Windows SDK 6.0 and 6.0A, Visual Studio 2008 sp1. This machine is the one that works.
Coworkers machine: Visual Studio 6.0 sp6, Visual Studio 2005
Another machine: Visual Studio 6.0 sp6, Visual Studio 2008. 2008 was installed on this this morning and did not rectify the problem.
How do I get these other machines to compile the VB6 app correctly so that it runs on machines other than the one on which it was compiled?
(Put requests for more information in comments and I'll edit this to provide answers.)
**Edits:**
A suggestion was made regarding permissions in relation to registering the control. I'd like to clarify that the control seems to work well. I register it in the exact same way on the machine that works and the ones that don't. The problem manifests itself when the VB6 app that references the control is compiled on a machine other than my own.
I should also add that I had a small VB6 host app that had 1 form and the interop control and a couple buttons. This one does not exhibit the same problem as the main VB6 app.
**Possibly a clue**
If anybody is familiar with using OleView.exe, I think I may have discovered a clue. When I view the Type Libraries list, there is "OrderControl (Ver 0.1)" as well as "OrderControlCtl (Ver 0.1)". The first uses the GUID defined for the assembly and the path shows the OrderControl.tlb generated from using RegAsm.exe. The second has different GUIDs on the different machines and the path on mine is "C:\Program Files\Microsoft Visual Studio\VB98\vbc00305.oca", the path on the other machine is "C:\Program Files\Microsoft Visual Studio\VB98\mscoree.oca", and on the coworker's machine is "C:\windows\system32\mscoree.oca". Both mscoree.oca are the same size, but the vbc00305.oca on my machine is several KB smaller.
I looked again at the VB6 project's references. The references list both OrderControl and OrderControlCtl, but only OrderControlCtl is checked. OrderControl's location is the TLB file, but OrderControlCtl's location is the OCA file that's different on each station.
**Dependency Walker**
I ran profiles in DW for a version of the exe compiled on my machine and one compiled on our build machine (which won't run on mine). They diverge at the following 2 lines. Both have the first line, but the one that runs continues on with more calls/loads, while the one that does not run immediately begins detaching after the first line here:
```
GetProcAddress(0x7E720000 [SXS.DLL], "SxsOleAut32RedirectTypeLibrary") called from "OLEAUT32.DLL" at address 0x7712A637 and returned 0x7E746129.
GetProcAddress(0x7E720000 [SXS.DLL], "SxsOleAut32MapConfiguredClsidToReferenceClsid") called from "OLEAUT32.DLL" at address 0x7712A637 and returned 0x7E745C0D.
``` | I've since discovered that it had to do with 3 particular methods on my control that were 'returning' (via `ref` parameter) structs. I ended up using a workaround involving returning classes instead of structs. But I'm still curious, so I asked a [different question](https://stackoverflow.com/questions/1183167/exposing-c-struct-to-com-breaks-for-vb6-app). | Not sure, but I had also issues like that. Try using regasm with /codebase. | Compiling VB6 app w/ .NET interop, only runs if compiled on my machine | [
"",
"c#",
".net",
"com",
"vb6",
"interop",
""
] |
When there is a JS error in IE7, the text displayed is not helpful mainly because it says "error at line X" but the line doesn't really correspond to anything if you start including multiple javascript files.
Is there an option or add-on that could maybe improve this? | I haven't found anything in IE7. However, if you have the option, IE8 + web developer toolbar makes it a lot easier, as the web dev toolbar includes a javascript debugger. Most of the time I see the same errors in IE 7 and 8, so debugging them in 8 usually leads to fixing it in 7 as well. | The only extra detail you can get is by turning on the script debugging. You can do this through Internet Options - Advanced - uncheck Disable Script Debugging (Internet Explorer). This will pop up an alert whenever you get an error and you can see the line of code that created it as well as step through the code's execution. | Is there a way to get more detailled JS error messages in IE7? | [
"",
"javascript",
"internet-explorer-7",
""
] |
I'm new to programming, but I'm preparing to write a Java program. As I'm planning it, I'm trying to find the right GUI for it. I found [this](http://javabyexample.wisdomplug.com/java-concepts/37-core-java/65-20-free-look-and-feel-libraries-for-java-swings.html) page with GUI options. I have two questions:
1. Will these just plug into the Java GUI builder?
2. How easy (or hard) is it to change the GUI look and feel after the program is built? | Changing the look and feel of a program is as simple as:
```
UIManager.setLookAndFeel("fully qualified name of look and feel");
```
before any GUI-creating code has been created. So you can easily create all your GUI with your GUI builder and then simply call this at the start of your program.
(Note that some look and feels, like Substance, are very strict when it comes to threading issues, so you better make sure that all your GUI code is run from the event dispatching thread.)
As a suggestion, two very good looking (and professional looking enough) look and feels in my opinion are Substance and also Nimbus which will ship with later releases of the JRE as the default look-N-feel (at least that's the plan) and which can be downloaded separately from java.net.
So if you opt for Nimbus the code would be:
```
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
```
And one example of Substance (Substance has many skins and themes, if you want to know more read their documentation in their site) would be:
```
UIManager.setLookAndFeel(new org.jvnet.substance.skin.SubstanceBusinessBlackSteelLookAndFeel());
```
Also note that you can use the cross platform skin (Metal) like this:
```
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
```
And finally if you are on windows you can use the system look and feel like this:
```
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
``` | Building on what Uri said, you may want to stick with one of the more well-known look and feels.
If you use Swing, you may want to look into using the [Nimbus](http://java.sun.com/javase/6/docs/technotes/guides/jweb/otherFeatures/nimbus_laf.html) look and feel... it's included with Java 6u10 and newer. Nimbus is built on the [Synth](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/synth/package-summary.html) framework included with Java 5 and newer.
Of course, if the end user is using a lower version, it will throw an UnsupportedLookAndFeelException and default to whatever the JVM default is (usually the Metal/Ocean (cross-platform) theme).
As a side note, if you use Swing, you can switch which look and feel is being used on the fly. You just have to call
```
// "lnfName" is the look and feel name.
// "frame" is the window's JFrame.
// A try/catch block is omitted here.
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
``` | Java GUI look and feel changes | [
"",
"java",
"user-interface",
""
] |
I am writing a desktop utility application to manage a small set of data. This application will be used by a singular person so I'd like to keep the database as simple as possible. I am considering XML or [SQL Server Compact 3.5](http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx) (SQL CE). I am leaning towards SQL CE because it will probably be easier/quicker to develop than XML. Are there any other worthwhile solutions worth considering? Is SQL CE the way to go?
Edit - Here are some more specifics on the data:
* Maybe a half a dozen tables
* No more than 5000 records
* Mostly CRUD operations
* Basic reporting/exporting to excel | I've had good experiences with Sql CE, that seems like a very reasonable solution given the scenario you're describing. It has the added advantage of being much simpler to deploy than a separate solution as well, and I think that is a *very* big deal for a simple app like you describe.
I'm using it with Linq2Sql right now in my personal project, in fact. :) | SQLite would be my choice. | Recommendations for single user access Database | [
"",
"c#",
"sql-server",
"database",
""
] |
I have a DateTime object with a person's birthday. I created this object using the person's year, month and day of birth, in the following way:
```
DateTime date = new DateTime(year, month, day);
```
I would like to know how many days are remaining before this person's next birthday. What is the best way to do so in C# (I'm new to the language)? | ```
// birthday is a DateTime containing the birthday
DateTime today = DateTime.Today;
DateTime next = new DateTime(today.Year,birthday.Month,birthday.Day);
if (next < today)
next = next.AddYears(1);
int numDays = (next - today).Days;
```
This trivial algorithm fails if the birthday is Feb 29th. This is the alternative (which is essentially the same as the answer by Seb Nilsson:
```
DateTime today = DateTime.Today;
DateTime next = birthday.AddYears(today.Year - birthday.Year);
if (next < today)
next = next.AddYears(1);
int numDays = (next - today).Days;
``` | Using today's year and the birthday's month and day **will not work with leap-years**.
After a little bit of testing, this is what I get to work:
```
private static int GetDaysUntilBirthday(DateTime birthday) {
var nextBirthday = birthday.AddYears(DateTime.Today.Year - birthday.Year);
if(nextBirthday < DateTime.Today) {
nextBirthday = nextBirthday.AddYears(1);
}
return (nextBirthday - DateTime.Today).Days;
}
```
Tested with 29th February on a leap-year and also when the birthday is the same day. | Calculate days remaining to a birthday? | [
"",
"c#",
"datetime",
""
] |
All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.
The list of things I've tried:
* [Apache Thrift](http://incubator.apache.org/thrift/) doesn't have any actual releases, just snapshots. I'd like to use something stable.
* [JSON-RPC](http://json-rpc.org/) is interesting, and it should be able to run over sockets, but in practice most of the [implementations](http://json-rpc.org/wiki/implementations) only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.
* [Protocol Buffers](http://code.google.com/p/protobuf/) is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and [faster](http://www.eishay.com/2009/03/thrift-vs-protocol-buffers-in-python.html).
* [Pyro](http://pyro.sourceforge.net/) doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.
* [pysage](http://code.google.com/p/pysage/) Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions.
* [Candygram](http://candygram.sourceforge.net/) is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?
* [Twisted Perspective Broker](http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html) Twisted doesn't work on Jython.
I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.
Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC. | How about using sockets, but with the help of `asyncore` and `asynchat`?
Some links:
* [An example](http://effbot.org/librarybook/asynchat.htm)
* <http://docs.python.org/library/asyncore.html>
* <http://docs.python.org/library/asynchat.html> | Have you considered [Hessian](http://hessian.caucho.com/)? From the blurb:
> The Hessian binary web service
> protocol makes web services usable
> without requiring a large framework,
> and without learning yet another
> alphabet soup of protocols. Because it
> is a binary protocol, it is
> well-suited to sending binary data
> without any need to extend the
> protocol with attachments.
It has Python client and Java server (and more besides).
**Update:** If you're dead against HTTP, why not just use `SocketServer` and `pickle`? Not much of a protocol needed, hard to get wrong. Send / receive pickled strings with length prefixes. | fast-ish python/jython IPC? | [
"",
"python",
"ipc",
"jython",
"twisted",
"rpc",
""
] |
I'm looking for a way to automatically determine the natural language used by a website page, given its URL.
In Python, a function like:
```
def LanguageUsed (url):
#stuff
```
Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...)
Summary of Results:
I have a reasonable solution working in Python using [code from the PyPi for oice.langdet](http://pypi.python.org/pypi/oice.langdet/1.0dev-r781).
It does a decent job in discriminating English vs. Non-English, which is all I require at the moment. Note that you have to fetch the html using Python urllib. Also, oice.langdet is GPL license.
For a more general solution using Trigrams in Python as others have suggested, see this [Python Cookbook Recipe from ActiveState](http://code.activestate.com/recipes/326576/).
The Google Natural Language Detection API works very well (if not the best I've seen). However, it is Javascript and their TOS forbids automating its use. | This is usually accomplished by using character n-gram models. You can find [here](http://alias-i.com/lingpipe/demos/tutorial/langid/read-me.html) a state of the art language identifier for Java. If you need some help converting it to Python, just ask. Hope it helps. | Your best bet really is to use [Google's natural language detection](http://www.google.com/uds/samples/language/detect.html) api. It returns an iso code for the page language, with a probability index.
See <http://code.google.com/apis/ajaxlanguage/documentation/> | Automatically determine the natural language of a website page given its URL | [
"",
"python",
"url",
"web",
"nlp",
""
] |
I'm trying to execute an external function on click of a DOM element without wrapping it in another function.
Say I have a function called `sayHello()`, as follows:
```
function sayHello(){
alert("hello");
};
```
To execute it on click, I currently have to do this:
```
$("#myelement").click(function(){
sayHello();
});
```
Notice I am forced to wrap the single function call in yet another function.
What I am trying to do is something like this
```
$("#myelement").click(sayHello());
```
Except that simply doesn't work.
Can I avoid wrapping the single function call in another function in any way?
Thanks!
.
Additional information:
How would I achieve the same thing when I need to pass parameters to the function?
..
Additional information:
Like Chris Brandsma and Jani Hartikainen pointed out, one should be able to use the bind function to pass parameters to the function without wrapping it in another anonymous function as such:
```
$("#myelement").bind("click", "john", sayHello);
```
with `sayHello()` now accepting a new parameter, as such:
```
function sayHello(name){
alert("Hello, "+name);
}
```
This, unfortunately, does not seem to work... Any ideas?
The Events/bind documentation is located [here](http://docs.jquery.com/Events/bind)
Thanks! | To pick up from a question you had in there.
Obviously, you need to call it this way to work:
```
$("#myelement").click(sayHello);
```
Calling it the way you had it actually executes the method instead of sending the method to the click handler.
If you need to pass data you can also call the method this way:
```
$("#myelement").click(function(){ sayHello("tom");});
```
Or you can pass data via the [`bind()`](http://docs.jquery.com/Events/bind) function
```
function sayHello(event){ alert("Hello, "+event.data); }
$("#myelement").bind("click", "tom", sayHello);
```
Or you can retrieve data from the element that was clicked
```
$("#myelement").click(function(){sayHello($(this).attr("hasData");});.
```
Hope that helps. | You are calling the sayHello-function, you can pass it by reference by removing the parenthesis:
```
$("#myelement").click(sayHello);
```
*Edit:* If you need to pass parameters to the sayHello-function, you will need to wrap it in another function. This defines a parameter-less new function that calls your function with the parameters provided at creation-time:
```
$("#myelement").click(function () {
sayHello('name');
// Creates an anonymous function that is called when #myelement is clicked.
// The anonymous function invokes the sayHello-function
});
``` | How can I execute an external function when an element is clicked? | [
"",
"javascript",
"jquery",
"event-handling",
""
] |
I realize it's possible to create a PHP Web Service using SOAP, however, are there classes within PHP that make this easier than hand creating the SOAP messages?
I want to use php has a webservice using wsdl
with this link
<https://qa-api.ukmail.com/Services/UKMAuthenticationServices/UKMAuthenticationService.svc?wsdl>
to integrate uk mail api in to my php web application
but dont now how to do it ?? any help | There are:
* The PHP [SOAP](http://php.net/SOAP) functions
* The [PEAR::SOAP](http://pear.php.net/package/SOAP) module
* [nusoap](http://sourceforge.net/projects/nusoap/)
They *should* all interoperate fine with .NET - it's just XML after all... | You want to try nuSOAP which you can get from here <http://sourceforge.net/projects/nusoap/>
Very easy as I had to create a PHP SOAP service and I didnt know PHP as I'm a C# .net person!
And just to add to that, as long as you implement the wsdl and SOAP methods correctly you should be fine. I had it working with .net with no trouble at all | PHP Web Service with SOAP | [
"",
"php",
"web-services",
"api",
"soap",
"wsdl",
""
] |
The Problem:
> A box can hold 53 items. If a person has 56 items, it will require 2 boxes to hold them. Box 1 will hold 53 items and box 2 will hold 3.
How do I repeat the above where 53 is a constant, unchanging, value and 56 is a variable for each box:
```
Math.Ceiling(Convert.ToDecimal(intFeet / 53))
```
what I have so far for that is:
```
int TotalItems = 56;
int Boxes = Math.Ceiling(Convert.ToDecimal(intFeet / 53));
for (int i = 0; i < Boxes; i++)
{
int itemsincurrentbox=??
}
``` | Where the integers `capacity` and `numItems` are your box capacity (53 in the example) and the total number of items you have, use the following two calculations:
```
int numBoxes = numItems / capacity;
int remainder = numItems % capacity;
```
This will give you the number of boxes that are filled (`numBoxes`), and the number of items in an additional box (`remainder`) if any are needed, since this value could be 0.
Edit: As Luke pointed out in the comments, you can get the same result with the .NET class library function [Math.DivRem](http://msdn.microsoft.com/en-us/library/yda5c8dx.aspx).
```
int remainder;
int numBoxes = Math.DivRem( numItems, capacity, out remainder );
```
This function returns the quotient and puts the remainder in an output parameter. | simple, overly imperative example:
```
int itemsPerBox = 53;
int totalItems = 56;
int remainder = 0;
int boxes = Math.DivRem(totalItems, itemsPerBox, out remainder);
for(int i = 0; i <= boxes; i++){
int itemsincurrentbox = i == boxes ? remainder : itemsPerBox;
}
``` | Given a total, determine how many times a value will go into it | [
"",
"c#",
"math",
""
] |
I have problems displaying the Unicode character of U+009A.
It should look like "š", but instead looks like a rectangular block with the numbers 009A inside.
Converting it to the entity "š" displays the character correctly, but I don't want to store entities in the database.
The encoding of the webpage is in UTF-8.
The character is URL-encoded as "%C2%9A".
Reproduce:
# php -E 'echo urldecode("%C2%9A");' > /tmp/test ; less /tmp/test
This gives me <U+009A> in less or <9A> in vim. | The Unicode character "š" is U+0161, not U+009A
I suspect that it's 0x9A in another character set.
The box with 009A is usually shown when you don't have a font installed with that character. | If you’re using UTF-8 as your input encoding, then you can simply use the plain `š`. Or you could use the hexadecimal representation `"\xC2\x9A"` (in double quotes) that’s independent from the input encoding. Or `utf8_encode("\x9A")` since the first 256 characters of Unicode and ISO 8859-1 are identical. | PHP UTF-8 encoding problem of U+009A | [
"",
"php",
"encoding",
"utf-8",
""
] |
Does anyone know why sometimes an `@` is used preceding a commandText string?
both seem to work fine.
```
command.CommandText = @"SELECT id FROM users";
```
or
```
command.CommandText = "SELECT id FROM users";
``` | That is C#'s verbatim string literal notation.
A verbatim string literal is preceded by a leading **`@`** and anything between the quotes that follow that **`@`** will be considered part of the string literal without any need for escaping.
Please see [String literals](http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx):
> C# supports two forms of string
> literals: regular string literals and
> verbatim string literals.
>
> A regular string literal consists of
> zero or more characters enclosed in
> double quotes, as in "hello", and may
> include both simple escape sequences
> (such as \t for the tab character) and
> hexadecimal and Unicode escape
> sequences.
>
> ***A verbatim string literal consists of
> an @ character followed by a
> double-quote character, zero or more
> characters, and a closing double-quote
> character. A simple example is
> `@"hello"`. In a verbatim string
> literal, the characters between the
> delimiters are interpreted verbatim,
> the only exception being a
> quote-escape-sequence. In particular,
> simple escape sequences and
> hexadecimal and Unicode escape
> sequences are not processed in
> verbatim string literals. A verbatim
> string literal may span multiple
> lines.***
Most likely a query was spanning multiple lines and whomever wrote the code wanted to put it on multiple lines like this:
```
command.CommandText = @"SELECT id
FROM users";
```
Whereas without a verbatim string literal you would have to do this:
```
command.CommandText = "SELECT id"
+ " FROM users";
``` | & = ampersand
@ = at (or at the rate of) | ADO CommandText syntax | [
"",
"c#",
"string",
""
] |
We are trying to develop a timeout feature in application where we want alert user saying that the application log out will happen in x time will display the count down timer. Once the timeout we will be force fully logging out the user. For displaying the log out information we thought of displaying a pop-up with relevant message which can close itself and initiate log out on timeout. The problem with display of pop-up is we have to send a request to the server which will reset the session timeout set at server level.
For achieving the above requirement is there any way to open a pop-up without sending the request to server. We will decide the content of the pop-up using DHTML. | I agree with Guillaume that a DHTML window would be better, but this should work if you want a real popup window.
```
var win = window.open('about:blank');
win.document.body.innerHTML = '[Window body content here]';
``` | You could use jQuery both to display an alert with a count down and to send an ajax request to the server resetting the session timeout, without having to refresh the screen.
Kind regards,
Guillaume Hanique | Opening popup without a server request | [
"",
"javascript",
"modalpopupextender",
""
] |
I have a java project I want to create which will be built on top of some vendor APIs. The APIs connect to servers running said vendor's software and perform various actions.
I have 2 different versions of the servers supported by 2 different API versions. Any changes to the API's are in internal implementation only. I.E. The classes, interfaces, methods, etc. available to me in the older version exist in the newer version. Therefore the code I write should compile and run with either API version. There is a version number in the API presented to the servers when using the API to connect that prevents you from using a different version API on that particular server.
1. Is there a way to switch JAR files on the fly at runtime? (something like a c/c++ DLL??)
2. If switching API versions at runtime isn't possible, what is the most elegant way to handle the problem. Build the code 2x (one for each api version)?
I hope I'm missing something but approach 2 doesn't seem ideal. Here's a more concrete example of why:
```
package org.myhypotheticalwrapper.analyzer;
import org.myhypothetical.worker;
import org.myhypothetical.comparator;
public class Analyzer {
Worker w1 = new Worker();
Worker w2 = new Worker();
Comparator c = new Comparator(w1.connectAndDoStuff(),w2.connectAndDoStuff());
c.generateReport();
}
```
This is my dilema. I want w1 to be built with the old API and w2 be built with the new API so they can connect to the appropriate servers. Other than the API's they sit on top of, they are the same (identical code). Do I have to create two uniquely named Class types for W1 and W2 even though their code is identical, simply to accommodate different API versions? It seems like that could get unwieldy fast, if I had many API versions that I wanted to interact with.
Any suggestions and comments greatly appreciated.
-new guy | You can't really change out a class file once it's been loaded, so there's really no way to replace a class at runtime. Note that projects like [JavaRebel](http://www.zeroturnaround.com/javarebel/) get around this with some clever use of instrumentation via the javaagent - but even what you can do with that is limited.
From the sounds of it you just need to have two parallel implementations in your environment at the same time, and don't need to reload classes at runtime. This can be accomplished pretty easily. Assume your runtime consists of the following files:
* analyzer.jar - this contains the analyzer / test code from above
* api.jar - this is the common forward-facing api code, e.g. interfaces
* api-impl-v1.jar - this is the older version of the implementation
* api-impl-v2.jar - this is the newer version of the implementation
Assume your worker interface code looks like this:
```
package com.example.api;
public interface Worker {
public Object connectAndDoStuff();
}
```
And that your implementations (both in v1 and v2) look like this:
```
package com.example.impl;
import com.example.api.Worker;
public class WorkerImpl implements Worker {
public Object connectAndDoStuff() {
// do stuff - this can be different in v1 and v2
}
}
```
Then you can write the analyzer like this:
```
package com.example.analyzer;
import com.example.api.Worker;
public class Analyzer {
// should narrow down exceptions as needed
public void analyze() throws Exception {
// change these paths as need be
File apiImplV1Jar = new File("api-impl-v1.jar");
File apiImplV2Jar = new File("api-impl-v2.jar");
ClassLoader apiImplV1Loader =
new URLClassLoader(new URL[] { apiImplV1Jar.toURL() });
ClassLoader apiImplV2Loader =
new URLClassLoader(new URL[] { apiImplV2Jar.toURL() });
Worker workerV1 =
(Worker) apiImplV1Loader.loadClass("com.example.impl.WorkerImpl")
.newInstance();
Worker workerV2 =
(Worker) apiImplV2Loader.loadClass("com.example.impl.WorkerImpl").
.newInstance();
Comparator c = new Comparator(workerV1.connectAndDoStuff(),
workerV2.connectAndDoStuff());
c.generateReport();
}
}
```
To run the analyzer you would then include analyzer.jar and api.jar in the classpath, but **leave out** the api-impl-v1.jar and api-impl-v2.jar. | The easiest is probably having a classloader loading in classes not in the default classpath.
From <http://www.exampledepot.com/egs/java.lang/LoadClass.html>
```
// Convert File to a URL
URL url = file.toURL(); // file:/c:/myclasses/
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
// Load in the class; MyClass.class should be located in
// the directory file:/c:/myclasses/com/mycompany
Class cls = cl.loadClass("com.mycompany.MyClass");
``` | Is it possible to switch Class versions at runtime with Java? | [
"",
"java",
"dll",
"build",
"classloader",
""
] |
I tried doing this but then it is not working
```
<?php
if ($_SERVER['SERVER_NAME']=='http://www.testground.idghosting.com/idi' && $_SERVER['REQUEST_URI'] == 'our-production/') {
echo '<div id="services">
<h1>Our services</h1>
<a href="<?php bloginfo(\'url\'); ?>" id="serv_productions" title="Our Productions"><span>Our Productions</span></a>
<a href="<?php bloginfo(\'url\'); ?>" id="serv_services" title="Production Services"><span>Production Services</span></a>
<a href="<?php bloginfo(\'url\'); ?>" id="serv_equipment" title="Equipment & Facilities"><span>Equipment & Facilities</span></a>
<a href="<?php bloginfo(\'url\'); ?>" id="serv_pr" title="PR & Media"><span>PR & Media</span></a>
</div>';
} else {
echo '<div> do not show</div>';
} ;
?>
```
to see the sample [click here](http://www.testground.idghosting.com/idi/) see the block where it says Our services in the bottom I don't want it to be shown on ths page but visible to all other pages.... | Always indent your code — it's simplier to see errors
```
<?php
if ($url == "http://www.sample.com/test.php") {
echo "<div>whatever</div>";
} else {
echo "<div> do not show</div>";
};
?>
```
Note the placement of curly brackets. | Or you could use the ternary operator. All on one line if you like - I broke it up to avoid the evil scrollbars.
```
echo ($url == "http://www.sample.com/test.php")
? "<div>Whatever</div>"
: "";
``` | PHP if else Request URI help | [
"",
"php",
"syntax",
""
] |
I have an XML string as such:
```
<?xml version='1.0'?><response><error code='1'> Success</error></response>
```
There are no lines between one element and another, and thus is very difficult to read. I want a function that formats the above string:
```
<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response>
```
Without resorting to manually write the format function myself, is there any .Net library or code snippet that I can use offhand? | You will have to parse the content somehow ... I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here's a working example using LINQ to format an input XML string.
```
string FormatXml(string xml)
{
try
{
XDocument doc = XDocument.Parse(xml);
return doc.ToString();
}
catch (Exception)
{
// Handle and throw if fatal exception here; don't just ignore them
return xml;
}
}
```
[using statements are ommitted for brevity] | Use [`XmlTextWriter`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmltextwriter)...
```
public static string PrintXML(string xml)
{
string result = "";
MemoryStream mStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
XmlDocument document = new XmlDocument();
try
{
// Load the XmlDocument with the XML.
document.LoadXml(xml);
writer.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
document.WriteContentTo(writer);
writer.Flush();
mStream.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
mStream.Position = 0;
// Read MemoryStream contents into a StreamReader.
StreamReader sReader = new StreamReader(mStream);
// Extract the text from the StreamReader.
string formattedXml = sReader.ReadToEnd();
result = formattedXml;
}
catch (XmlException)
{
// Handle the exception
}
mStream.Close();
writer.Close();
return result;
}
``` | Format XML string to print friendly XML string | [
"",
"c#",
"xml",
"formatting",
""
] |
In my ASP.NET application, I have a line in the global application start event that configures the client remoting channel by calling RemotingConfiguration.Configure().
This works well the first time, but when my web application gets recycled, the application start event is fired again causing the following remoting exception:
Remoting configuration failed with the exception 'System.Runtime.Remoting.RemotingException: The channel 'tcp' is already registered.
I would like to detect if the channel is already configured so that I can avoid getting this exception. | Try ChannelServices.RegisteredChannels
<http://msdn.microsoft.com/en-us/library/system.runtime.remoting.channels.channelservices.registeredchannels(VS.71).aspx> | I've been having this problem too.
The trouble is that you can stop the application that called RemotingConfiguration.Configure() but that doesn't make the channel available. Its something to do with ports or it might just be the name of the channel, I'm not sure.
The solution I found which seems to work is to get the registered channels and unregister the channel you want to remove.
Here is some code
```
RemotingConfiguration.Configure(appConfig, false);
// do this to unregister the channel
IChannel[] regChannels = ChannelServices.RegisteredChannels;
IChannel channel = (IChannel)ChannelServices.GetChannel(regChannels[0].ChannelName);
ChannelServices.UnregisterChannel(channel);
RemotingConfiguration.Configure(appConfig, false); // this is just a test to see if we get an error
```
I hope this works for you, it has for me | How to determine if remoting channel is already registered | [
"",
"c#",
".net",
"remoting",
""
] |
Is it possible to access values of non-type template parameters in specialized template class?
If I have template class with specialization:
```
template <int major, int minor> struct A {
void f() { cout << major << endl; }
}
template <> struct A<4,0> {
void f() { cout << ??? << endl; }
}
```
I know it the above case it is simple to hardcode values 4 and 0 instead of using variables but what I have a larger class that I'm specializing and I would like to be able to access the values.
Is it possible in A<4,0> to access `major` and `minor` values (4 and 0)? Or do I have to assign them on template instantiation as constants:
```
template <> struct A<4,0> {
static const int major = 4;
static const int minor = 0;
...
}
``` | This kind of problem can be solved by having a separate set of "Traits" structs.
```
// A default Traits class has no information
template<class T> struct Traits
{
};
// A convenient way to get the Traits of the type of a given value without
// having to explicitly write out the type
template<typename T> Traits<T> GetTraits(const T&)
{
return Traits<T>();
}
template <int major, int minor> struct A
{
void f()
{
cout << major << endl;
}
};
// Specialisation of the traits for any A<int, int>
template<int N1, int N2> struct Traits<A<N1, N2> >
{
enum { major = N1, minor = N2 };
};
template <> struct A<4,0>
{
void f()
{
cout << GetTraits(*this).major << endl;
}
};
``` | Not really an answer to your question, but you could enumerate them, viz:
```
enum{
specialisationMajor=4,
specialisationMinor=0
};
template <> struct A<specialisationMajor,specialisationMinor> {
static const int major = specialisationMajor;
static const int minor = specialisationMinor;
...
}
``` | Is it possible to access values of non-type template parameters in specialized template class? | [
"",
"c++",
"templates",
"template-specialization",
""
] |
I am using hibernate as a persistence layer. There are 2 entities that live in the same table extending one superclass with single table inheritance strategy.
```
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class A {
@Id
@GeneratedValue
protected Long id;
// some common fields for B and C
}
@Entity
public class B extends A {
// B-specific fields
}
@Entity
public class C extends A {
// C-specific fields
}
```
I have an instance of B with id=4. How do I change the type of this instance to C preserving it's ID (4)?
```
B b = em.find(B.class, 4L);
C c = convertToC(b);
c.setId(b.getId());
em.remove(b);
em.persist(c);
```
The code above fails with
```
org.hibernate.PersistentObjectException: detached entity passed to persist: C
```
Is it possible at all? | Hibernate attempts to make persistence as transparent as it possibly can - which means it tries to follow the same principles as normal Java objects. Now, rephrasing your question in Java, you'd get:
> How can I convert an instance of B class into an instance of (incompatible) C class?
And you know the answer to that - you can't. You can create a **new** instance of C and copy necessary attributes, but B will *always* be B, never C. Thus the answer to your original question is - it cannot be done via JPA or Hibernate API.
However, unlike plain Java, with Hibernate you can cheat :-) `InheritanceType.SINGLE_TABLE` is mapped using `@DiscriminatorColumn` and in order to convert B into C you need to update its value from whatever's specified for B into whatever's specified for C. The trick is - you cannot do it using Hibernate API; you need to do it via plain SQL. You can, however, map this update statement as named SQL query and execute it using Hibernate facilities.
The algorithm, therefore, is:
1. **Evict** B from session if it's there (this is important)
2. Execute your named query.
3. Load what-is-now-known-as-C using former B's id.
4. Update / set attributes as needed.
5. Persist C | In this case, "c" is an object which the hibernate session knows nothing about, but it has an ID, so it assumes that the object has already been persisted. In that context, persist() makes no sense, and so it fails.
The javadoc for Hibernate Session.persist() (I know you're not using the Hibernate API, but the semantics are the same, and the hibernate docs are better) says "Make a transient instance persistent". If your object already has an ID, it's not transient. Instead, it thinks it's a detached instance (i.e. an instance that has been persisted, but is not associated with the current session).
I suggest you try merge() instead of persist(). | Changing the type of an entity preserving its ID | [
"",
"java",
"hibernate",
"persistence",
""
] |
I have a object cache class like this:
```
#include "boost/thread/mutex.hpp"
#include "boost/unordered_map.hpp"
template <typename type1, typename type2>
class objectCache
{
public:
objectCache()
{
IDCounter = 0;
}
~objectCache()
{
for ( it=free_objects.begin() ; it != free_objects.end(); it++ )
delete (*it).second;
for ( it=busy_objects.begin() ; it != busy_objects.end(); it++ )
delete (*it).second;
}
type1* objectCache::Get()
{
boost::mutex::scoped_lock(io_mutex);
if(free_objects.size() > 0)
{
it = free_objects.begin();
type1 *temp = (*it).second;
busy_objects[(*it).first] = temp;
free_objects.erase(free_objects.begin());
return temp;
}
type1 * temp = new type2;
++IDCounter;
busy_objects[IDCounter] = temp;
return temp;
}
void objectCache::Pushback(type1)
{
boost::mutex::scoped_lock(io_mutex);
free_objects[ID] = socket;
it = busy_objects.find(ID);
busy_objects.erase(it);
}
protected:
private:
boost::mutex io_mutex;
long long IDCounter;
boost::unordered_map<long long, type1*> free_objects;
boost::unordered_map<long long, type1*> busy_objects;
typename boost::unordered_map<long long, type1*>::iterator it;
};
class A{
public:
A(int num){
number = num;
}
int number;
};
int main(int argc, char* argv[])
{
objectCache<a, a(1)> intcache;
A* temp = intcache.Get();
cout <<temp->number <<endl;
system("pause");
return 0;
}
```
I known that "typename type2" was unnecessary but I need a way to pass a class object that have a constructor with parameter like class A to the template.
or their was another way to do this ? please help. | Rather than passing an explicit value, pass in an object that creates your instance for you:
```
template <typename type1>
struct DefaultInstanceCreator {
type1 * operator ()() const {
return new type1;
}
};
template < typename type1
, typename InstanceCreator = DefaultInstanceCreator<type1> >
class objectCache {
public:
objectCache (InstanceCreator const & instCreator)
: instCreator_ (instCreator) {
}
type1* Get() {
type1 * temp = instCreator_ ();
}
private:
InstanceCreator instCreator_;
};
```
Then your object can have it's own specific creator:
```
class A {
public:
A(int num){
number = num;
}
int number;
public:
struct CreateInstance {
CreateInstance (int value)
: value_ (value) {
}
A * operator ()() const {
return new A(value_);
}
int value_;
};
};
int main(int argc, char* argv[]) {
objectCache<A, A::CreateInstance> intcache ( A::CreateInstance (1) );
A* temp = intcache.Get();
return 0;
}
```
The advantage of this approach is that you can use your cache with objects that have different numbers of arguments to their constructors. | You can have the template parameter on the method:
```
template <typename type2>
type1* objectCache::Get()
``` | Constructor of class in template | [
"",
"c++",
"templates",
"constructor",
""
] |
Coming from C#, where class instances are passed by reference (that is, a copy of the reference is passed when you call a function, instead of a copy of the value), I'd like to know how this works in C++.
In the following case, `_poly = poly`, is it copying the value of `poly` to `_poly`, or what?
```
#include <vector>
class polynomial {
std::vector<int> _poly;
public:
void Set(std::vector<int> poly) { poly_ = poly; }
};
``` | `poly`'s values will be copied into `_poly` -- but you will have made an extra copy in the process. A better way to do it is to pass by const reference:
```
void polynomial::Set(const vector<int>& poly) {
_poly = poly;
}
```
**EDIT** I mentioned in comments about copy-and-swap. Another way to implement what you want is
```
void polynomial::Set(vector<int> poly) {
_poly.swap(poly);
}
```
This gives you the additional benefit of having the [strong exception guarantee](http://en.wikipedia.org/wiki/Exception_safety#Exception_safety) instead of the basic guarantee. In some cases the code might be faster, too, but I see this as more of a bonus. The only thing is that this code might be called "harder to read", since one has to realize that there's an implicit copy. | This will do a shallow-copy of the vector of ints. This will generally work as you would expect (\_poly will end up containing the same values as poly).
You would see some strange behaivor if you had pointers (as they would be copied by value).
In general, you would want to pass that parameter by const reference:
```
void polynomial::Set( const vector<int>& poly )
```
In this case, passing by const reference will not affect the outcome and will be more efficient since it will eliminate an unneeded copy of the vector being passed into the method. | By default, are objects passed by value or by reference? | [
"",
"c++",
"pass-by-reference",
"pass-by-value",
""
] |
I have a Visual Studio C++ based program that uses pre-compiled headers (`stdafx.h`). Now we are porting the application to Linux using gcc 4.x.
The question is how to handle pre-compiled header in both environments.
I've googled but can not come to a conclusion.
Obviously I want leave `stdafx.h` in Visual Studio since the code base is pretty big and pre-compiled headers boost compilation time.
But the question is what to do in Linux. This is what I found:
1. Leave the `stdafx.h` as is. gcc compiles code considerable faster than VC++ (or it is just my Linux machine is stronger ... :) ), so I maybe happy with this option.
2. Use approach from [here](http://gamesfromwithin.com/?p=39) - make `stdafx.h` look like (set `USE_PRECOMPILED_HEADER` for VS only):
```
#ifdef USE_PRECOMPILED_HEADER
... my stuff
#endif
```
3. Use the approach from [here](http://chadaustin.me/2009/05/unintrusive-precompiled-headers-pch/) - compile VC++ with `/FI` to **implicitly** include `stdafx.h` in each cpp file. Therefore in VS your code can be switched easily to be compiled without pre-compiled headers and no code will have to be changed.
I personally dislike dependencies and the mess `stdafx.h` is pushing a big code base towards. Therefore the option is appealing to me - on Linux you don't have `stdafx.h`, while still being able to turn on pre-compiled headers on VS by `/FI` only.
4. On Linux compile `stdafx.h` only as a precompiled header (mimic Visual Studio)
Your opinion? Are there other approaches to treat the issue? | You're best off using precompiled headers still for fastest compilation.
You can use precompiled headers in gcc as well. [See here](http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html).
The compiled precompiled header will have an extension appended as `.gch` instead of `.pch`.
So for example if you precompile stdafx.h you will have a precompiled header that will be automatically searched for called `stdafx.h.gch` anytime you include `stdafx.h`
Example:
stdafx.h:
```
#include <string>
#include <stdio.h>
```
a.cpp:
```
#include "stdafx.h"
int main(int argc, char**argv)
{
std::string s = "Hi";
return 0;
}
```
Then compile as:
> `> g++ -c stdafx.h -o stdafx.h.gch`
> `> g++ a.cpp`
> `> ./a.out`
Your compilation will work even if you remove stdafx.h after step 1. | I used [option 3](http://chadaustin.me/2009/05/unintrusive-precompiled-headers-pch/) last time I needed to do this same thing. My project was pretty small but this worked wonderfully. | Handling stdafx.h in cross-platform code | [
"",
"c++",
"visual-studio",
"gcc",
"cross-platform",
"stdafx.h",
""
] |
That is the question. Is there anything you can do with c++ unions that you can't with c# Explicit structs? | C# explicit structs have some problems when it comes to references / pointer-sized members.
Because you must explicitly specify the location, but "sizeof(IntPtr)" is not a compile-time constant (unlike C++ sizeof), it is impossible to use pointer-sized members in explicit structs when your assembly should be usable in both 32-bit and 64-bit processes.
Also, it is possible to use explicit structs to "convert" between references and pointers:
```
[StructLayout(LayoutKind.Explicit)]
struct Test
{
[FieldOffset(0)]
public IntPtr ptr;
[FieldOffset(0)]
public string str;
}
```
When you do this, your assembly will require unsafe code permission; and there's the problem that the GC won't know what to do with the struct content - is it a pointer the GC should track, or is it just an integer?
So to answer your question:
"Is there anything you can do with c++ unions that you can't with c# Explicit structs?"
Yes, it's sometimes useful in C++ to squeeze two bits of data into the lower bits of a pointer. That is possible because the two lowermost bits of pointers will always be 0 when the pointer is aligned.
Heck, if you're writing a doubly-linked list of two-bit integers, you could even store both pointers and the data in 32 bits! ("prev ^ next ^ data", see [XOR linked list](http://en.wikipedia.org/wiki/XOR_linked_list))
However, you cannot do anything like that in C#, as you'd confuse the GC. | No, not really. The LayoutKind attribute is a way to Marshall data into C++ unions in interop. It's actually far more flexible than the union keyword in C++, since you have complete control over the layout in C# with structs. | (.net) Is there any intrinsic difference between .net Explicit structs and c++ unions? | [
"",
"c#",
".net",
"vb.net",
"struct",
"unions",
""
] |
Why should default parameters be added last in C++ functions? | To simplify the language definition and keep code readable.
```
void foo(int x = 2, int y);
```
To call that and take advantage of the default value, you'd need syntax like this:
```
foo(, 3);
```
Which was probably felt to be too weird. Another alternative is specifying names in the argument list:
```
foo(y : 3);
```
A new symbol would have to be used because this already means something:
```
foo(y = 3); // assign 3 to y and then pass y to foo.
```
The naming approach was considered and rejected by the ISO committee because they were uncomfortable with introducing a new significance to parameter names outside of the function definition.
If you're interested in more C++ design rationales, read [The Design and Evolution of C++](http://www.research.att.com/~bs/dne.html) by Stroustrup. | If you define the following function:
```
void foo( int a, int b = 0, int c );
```
How would you call the function and supply a value for a and c, but leave b as the default?
```
foo( 10, ??, 5 );
```
Unlike some other languages (eg, Python), function arguments in C/C++ can not be qualified by name, like the following:
```
foo( a = 10, c = 5 );
```
If that were possible, then the default arguments could be anywhere in the list. | Why should default parameters be added last in C++ functions? | [
"",
"c++",
"function",
"default",
"calling-convention",
""
] |
Suppose i have
```
> ID FromDate ToDate
> -- -------- -------
> 1 01/01/2005 30/6/2007
> 2 01/01/2008 31/12/2009
```
I want to count the years that are included on this 2 rows. Here is 1,5 years for the first row + 2 years from second row = Total of 3,5 years. How can i do this with SQL? | I would recommend using 365.25 for the days in the SQL DateDiff function to avoid issues with leap year.
```
select
SUM((DATEDIFF(d, FromDate, ToDAte)) / 365.25) as 'years-count'
from
mytableofdates
``` | If you're using Oracle:
```
SELECT TRUNC(SUM(MONTHS_BETWEEN(t.todate, t.fromDate)) / 12, 1)
FROM TABLE t
```
The second parameter in TRUNC is the number of decimal places - the query, as is, would be to one decimal place. | SQL Count Years on FromDATE to ToDate fields | [
"",
"sql",
""
] |
I have an interesting bit of logic that I can't seem to get my head around.
We have a Purchase table, where each Purchase is linked to a Customer and a Date. We want to pull out the Purchase that each customer made closest to the end of each month.
For instance,
```
CustomerID | Date
1 | 01/20/2009
2 | 01/26/2009
1 | 01/21/2009
1 | 02/02/2009
```
Should return....
```
CustomerID | Date
2 | 01/26/2009
1 | 01/21/2009
1 | 02/02/2009
```
Any ideas for a simple way to do this using SQL Server? | How about this?
```
SELECT CustomerID, MAX(Date)
FROM Purchase
GROUP BY CustomerID, YEAR(Date), MONTH(Date)
``` | ```
SELECT CustomerID, MAX(Date)
FROM Purchases
GROUP BY CustomerID, MONTH(Date), YEAR(Date)
``` | SQL Latest Date | [
"",
"sql",
"sql-server",
""
] |
The following C# program (built with `csc hello.cs`) prints just `Hello via Console!` on the console and `Hello via OutputDebugString` in the DebugView window. However, I cannot see either of the `System.Diagnostics.*` calls. Why is that?
```
using System;
using System.Runtime.InteropServices;
class Hello {
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern void OutputDebugString(string message);
static void Main() {
Console.Write( "Hello via Console!" );
System.Diagnostics.Debug.Write( "Hello via Debug!" );
System.Diagnostics.Trace.Write( "Hello via Trace!" );
OutputDebugString( "Hello via OutputDebugString" );
}
}
```
Is there maybe some special command-line switches required for `csc`?
I'm not using Visual Studio for any of my development, this is pure commandline stuff. | As others have pointed out, listeners have to be registered in order to read these streams. Also note that `Debug.Write` will only function if the `DEBUG` build flag is set, while `Trace.Write` will only function if the `TRACE` build flag is set.
Setting the `DEBUG` and/or `TRACE` flags is easily done in the project properties in Visual Studio or by supplying the following arguments to csc.exe
> `/define:DEBUG;TRACE` | While debugging `System.Diagnostics.Debug.WriteLine` will display in the output window (`Ctrl`+`Alt`+`O`), you can also add a `TraceListener` to the `Debug.Listeners` collection to specify `Debug.WriteLine` calls to output in other locations.
Note: `Debug.WriteLine` calls may not display in the output window if you have the Visual Studio option "Redirect all Output Window text to the Immediate Window" checked under the menu *Tools* → *Options* → *Debugging* → *General*. To display "*Tools* → *Options* → *Debugging*", check the box next to "*Tools* → *Options* → *Show All Settings*". | Where does System.Diagnostics.Debug.Write output appear? | [
"",
"c#",
"debugging",
""
] |
Are there any C# open-source components that allow me to delete files via SFTP? | Try [SharpSSH](http://www.tamirgal.com/blog/page/SharpSSH.aspx). | Tamir Gal's [Sharp SSH](http://www.tamirgal.com/blog/page/SharpSSH.aspx) is quite popular open source implementation of SFTP for .NET. Give it a try.
If you preffer fully supported commercial component can try our [Rebex SFTP](http://www.rebex.net/sftp.net/). Following code ilustrates the concept:
```
using Rebex.Net;
// create client and connect
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);
// delete the file
client.DeleteFile("/path/to/the/file");
// disconnect
client.Disconnect();
``` | Deleting files via SFTP | [
"",
"c#",
"sftp",
""
] |
I have a div on page, which content will change by javascript, I want get its value from c# code. but, its always returns empty or initial value, not changed value.
If I changed from div to hidden, it works well. I don't know why?
here is the code:
```
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
foo = function()
{
var d = document.getElementById('divTest');
d.innerHTML = 'my value';
var e = document.getElementById('hiddenTest');
e.value = 'my value';
}
</script>
</head>
<body>
<form id="form1" runat="server" >
<div>
<div id="divTest" runat="server" />
<input type="hidden" runat="server" id="hiddenTest" />
<input type="button" value="test" onclick="javascript:foo();" />
<asp:Button ID="btnTest" runat="server" Text="ASP.NET Button" OnClick="OnbtnTest" />
</div>
</form>
</body>
```
here is the c# code:
```
protected void OnbtnTest(object sender, EventArgs e)
{
Response.Write( string.Format("alert('{0}');", hiddenTest.Value) );
}
``` | Form input elements inside a form element posted to server, all other content is static and not posted to server. It's fundamental rule of HTTP, you can see details [from here](http://www.w3.org/TR/html401/interact/forms.html#submit-format).
You have two option, while preparing your div's content, write the same content inside a hidden field. And at server side get the hidden field's value.
Or make an AJAX call while preparing your content to get it at server side. | That's because only the form elements are submitted back to the server-side. | How to get div content which changed by javascript? | [
"",
"asp.net",
"javascript",
""
] |
I am still confused about passing by ref.
If I have a Cache object which I want to be accessed/available to a number of objects, and I inject it using constructor injection. I want it to affect the single cache object I have created. eg.
```
public class Cache {
public void Remove(string fileToRemove) {
...
}
}
public class ObjectLoader {
private Cache _Cache;
public ObjectLoader(Cache cache) {
}
public RemoveFromCacheFIleThatHasBeenDeletedOrSimilarOperation(string filename) {
_Cache.Remove(fileName);
}
}
```
Should I be using ref when I pass the Cache into the ObjectLoader constructor? | No you do not need to use the ref keyword in this situation.
Cache is a class, it is a reference type. When a reference is passed into a method, a copy of the reference (not the object itself) is placed into your parameter. Both references, inside and outside, of the method are pointing to the same object on the heap, and modification of the object's fields using one will be reflected in the other.
Adding ref to your method call passes in the original reference. This is useful in a situation where you would be reassigning (ie. by calling `new`) the location the reference points to from within a calling method. | Use the 'ref' keyword when the you need to modify *what the reference is pointing to*. When you pass a reference type into a method it *is* passed by value, but the value is a *copy* of that reference which is passed to the method. This means that you can change the general state (i.e., properties/fields) of the referred to object, but if you attempt to change what the reference points to you will only affect the copy.
For example, given this method...
```
private void Foo( MyClass obj )
{
obj = new MyClass( );
obj.SomeProperty = true;
}
```
We can pass in the argument and then see if it was affected:
```
MyClass test = new MyClass( );
test.SomeProperty = false;
Foo( test );
Console.WriteLine( test.SomeProperty ); // prints "False"
```
Now, if we had defined the method using the 'ref' keyword...
```
private void Foo( ref MyClass obj )
{
obj = new MyClass( );
obj.SomeProperty = true;
}
```
The output would be "True", because the actual reference was passed to the method, not a copy. We changed what that reference points to within the function and we see the effects of those changes.
You are just creating a new pointer to the object on the heap when you omit the 'ref' keyword. If you change one pointer you will not change the other.
...
So, to answer your question; no, you do not need to use the 'ref' keyword to change the state of your single Cache object when it is passed to a method. | Passing by ref? | [
"",
"c#",
".net",
""
] |
I was asked by my boss to create a module for calculating reverse compound.
The question is: if I want to achieve $1.000.000,00 in 24 months with interest rate 18%/year (or 1.5%/month). how much money do I have to save every month?
I searched on the internet, but found nothing except people referring to the Excel formula.
Do you know what the mathematical formula is for this case?
I am using Java for this module. Is there any Java library or API? | Let us say that you are investing `D` dollars at the beginning of each month for `M` months earning an interest rate of `r` compounded monthly. We will set `i = r / 12`. At the end of `M` months you will have
```
D * (1 + i)^M + D * (1 + i)^(M - 1) + D * (1 + i)^(M - 2) + ...
D * (1 + i)
```
in your account. This is because the `D` dollars in the first month are invested for `M` months, the `D` dollars in the second month are invested for `M-1` months, and so on. This is a [geometric progression](http://en.wikipedia.org/wiki/Geometric_progression) and simplifies to
```
D * (1 + i) * ((1 + i)^M - 1) / i.
```
Therefore, if you want `X` in your account at the end of `M` months you solve
```
X = D * (1 + i) * ((1 + i)^M - 1) / i
```
for `D` to obtain
```
D = X * i / ((1 + i) * ((1 + i)^M - 1)).
```
You don't really need an API here to solve this as you can see the solution is quite simple. The concept that you might want to read about here is that of [annuities](http://en.wikipedia.org/wiki/Annuity_(finance_theory)). | If you are not doing it for lending purposes, the simple formulae posted in other answers will probably be good enough.
If this is for any kind of financial activity, beware of any simple calculation for compound interest. If it is for any lending you are probably required to conform to strict rules (e.g in the UK the rate must be quoted in the form of an APR).
The calculations need to take into account:
* the variable days in a month
* whether interest is applied daily or monthly
* what day the borrowing was drawn down
* the day of the month payment has been taken.
* other stuff I can't remember but you'd better look up for your contract to be legally binding
In practice this needs a form of iteration to find the regular and final payments. | Is there a Java API or built-in function for solving annuity problems? | [
"",
"java",
"math",
"finance",
"formula",
""
] |
I'm a low-level algorithm programmer, and databases are not really my thing - so this'll be a n00b question if ever there was one.
I'm running a simple SELECT query through our development team's DAO. The DAO returns a System.Data.DataTable object containing the results of the query. This is all working fine so far.
The problem I have run into now:
I need to pull a value out of one of the fields of the first row in the resulting DataTable - and I have no idea where to even start. Microsoft is so confusing about this! Arrrg!
Any advice would be appreciated. I'm not providing any code samples, because I believe that context is unnecessary here. I'm assuming that all DataTable objects work the same way, no matter how you run your queries - and therefore any additional information would just make this more confusing for everyone. | Just the basics....
```
yourDataTable.Rows[ndx][column]
```
where ndx is the row number (starting at 0)
where column can be a DataColumn object, an index (column n), or the name of the column (a string)
```
yourDataTable.Rows[0][0]
yourDataTable.Rows[0][ColumObject]
yourDataTable.Rows[0]["ColumnName"]
```
to test for null, compare to DBNull.Value; | You mean like `table.Rows[0]["MyColumnName"]`? | How do You Get a Specific Value From a System.Data.DataTable Object? | [
"",
".net",
"sql",
"database",
"datatable",
"system.data",
""
] |
I am getting the following Compiler Warning:
```
'Resources.Foo.GetType()' hides inherited member 'object.GetType()'. Use the new keyword if hiding was intended. Resources.NET\Resources\Class1.cs 123 20 Resources
```
for this (very simplified) code:
```
public interface IFoo
{
int GetType();
string GetDisplayName();
}
public class Foo : IFoo
{
public int GetType() { return 3; } *** Warning: points to here (line 123)***
public string GetDisplayName() { return "Foo"; }
}
```
Note, what I don't get is why the GetDisplayName() function does NOT get a warning. I am clearly overlooking something.
I have poked around Stack Overflow and googled this error and it seems to apply to class inheritance, not interfaces. I am really confused why this would be triggered for the interface (which defines its methods as virtual).
Thanks in advance for the insight. | The [GetType](http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx) method is defined on the [System.Object](http://msdn.microsoft.com/en-us/library/system.object%28VS.71%29.aspx) class, which is the ultimate base class of all classes of the Framework.
This method is used to get the [Type](http://msdn.microsoft.com/en-us/library/system.type.aspx) of the current instance in runtime, and I think that you are not intending to override it (you have a int return type).
I suggest you to rename the method to GetFooType or something else, or implement your interface [explicitly](http://msdn.microsoft.com/en-us/library/aa288461%28VS.71%29.aspx) to avoid runtime problems. | It refers to your method hiding [`GetType`](http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx) from object, not from your interface. Since your class inherits object and implements `IFoo`, and both provide a `GetType` method, by *implicitly* implementing the interface you will hide the `GetType` inherited from object. If you still want your interface method to be called `GetType`, you can implement it *explicitly* instead in `Foo`:
```
int IFoo.GetType()
{
return 3;
}
``` | does Inheritance really hide methods? | [
"",
"c#",
"inheritance",
"interface",
"method-hiding",
""
] |
I have a JS script, in this JS script I have 1 functions which creates an Object or an instance.
Is the object/instance created when the page loads or is it created when I call the function?
If the latter, how can I make it so that it creates the instance when I want it to?
Apologies for a nooby question.
Thanks all
## Update
```
<input type='button' name='submit' onclick='videoUpload();' value='Upload' />
```
Here is the function:
```
function videoUpload(){
$.get("getUploader.php", function(data){
var viduploader = new AjaxUpload('#vidup', {
action: data,
name: 'userfile',
responseType: 'xml',
onSubmit: function() {
// allow only 1 upload
alert('onSubmit' + data);
this.disable();
},
onComplete: function(file, response){
alert('Response' + response);
}
});
});
}
``` | It depends on how you call the function and if there is a var or not.
Reading from these two webpages will teach you most of what you need to know about javascript.
<https://developer.mozilla.org/en/a_re-introduction_to_javascript>
<http://www.hunlock.com/blogs/Mastering_Javascript_Arrays> | There are a couple ways to do that, I couldn't tell you if one is particularly better than the other, but here are a few ways.
```
//create a function
function SomeObject() {
var self = this;
}
//and create it using 'new'
var a = new SomeObject();
//create an object of a function
var SomeOtherObject = function() {
var self = this;
};
//and in similar fashion
var b = new SomeOtherObject();
//or just create a function that creates new object
var YetAnother = function() {
var gen = {};
return gen;
};
//and create by calling the function
var c = YetAnother();
``` | When are objects/instances created in JavaScript? | [
"",
"javascript",
"object",
""
] |
I've set up a JSF application on JBoss 5.0.1GA to present a list of Users in a table and allow deleting of individual users via a button next to each user.
When deleteUser is called, the call is passed to a UserDAOBean which gets an EntityManager injected from JBoss.
I'm using the code
```
public void delete(E entity)
{
em.remove(em.merge(entity));
}
```
to delete the user (code was c&p from a JPA tutorial). Just calling em.remove(entity) has no effect and still causes the same exception.
When this line is reached, I'm getting a TransactionRequiredException:
(skipping apparently irrelevant stacktrace-stuff)
> ...
>
> 20:38:06,406 ERROR [[Faces Servlet]]
> Servlet.service() for servlet Faces
> Servlet threw exception
> javax.persistence.TransactionRequiredException:
> EntityManager must be access within a
> transaction at
> org.jboss.jpa.deployment.ManagedEntityManagerFactory.verifyInTx(ManagedEntityManagerFactory.java:155)
> at
> org.jboss.jpa.tx.TransactionScopedEntityManager.merge(TransactionScopedEntityManager.java:192)
> at
> at.fhj.itm.utils.DAOImplTemplate.delete(DAOImplTemplate.java:54)
> at
> at.fhj.itm.UserBean.delete(UserBean.java:53)
> at
> sun.reflect.NativeMethodAccessorImpl.invoke0(Native
> Method)
>
> ...
I already tried to wrap a manually managed transaction (em.getTransaction().begin() + .commit() ) around it, but this failed because it is not allowed within JBoss container. I had no success with UserTransaction either. Searches on the web for this issue also turned up no similar case and solution.
Has anyone experienced something similar before and found a solution to this? | Found the missing link.
It was indeed a missing transaction but the solution was not to use the EntityManager to handle it but to add an injected UserTransaction.
```
@Resource
UserTransaction ut;
...
public void delete(E entity)
{
ut.begin();
em.remove(em.merge(entity));
ut.commit();
}
```
Thanks to all suggestions which somehow over 100 corners lead to this solution. | Know this is an old question, but just in case somebody stumbles on this like me.
Try
```
em.joinTransaction();
em.remove(bean);
em.flush();
```
That's what we use in all our @Stateful beans.
If you are using Seam, you can also use `@Transactional(TransactionPropagationType.REQUIRED)` annotation. | EntityManager throws TransactionRequiredException on merge() in JBoss JSF bean | [
"",
"java",
"jsf",
"jpa",
"jboss",
"entitymanager",
""
] |
I need to parse some HTML files, however, they are not well-formed and PHP prints out warnings to. I want to avoid such debugging/warning behavior programatically. Please advise. Thank you!
Code:
```
// create a DOM document and load the HTML data
$xmlDoc = new DomDocument;
// this dumps out the warnings
$xmlDoc->loadHTML($fetchResult);
```
This:
```
@$xmlDoc->loadHTML($fetchResult)
```
can suppress the warnings but how can I capture those warnings programatically? | You can install a temporary error handler with [`set_error_handler`](http://www.php.net/set_error_handler)
```
class ErrorTrap {
protected $callback;
protected $errors = array();
function __construct($callback) {
$this->callback = $callback;
}
function call() {
$result = null;
set_error_handler(array($this, 'onError'));
try {
$result = call_user_func_array($this->callback, func_get_args());
} catch (Exception $ex) {
restore_error_handler();
throw $ex;
}
restore_error_handler();
return $result;
}
function onError($errno, $errstr, $errfile, $errline) {
$this->errors[] = array($errno, $errstr, $errfile, $errline);
}
function ok() {
return count($this->errors) === 0;
}
function errors() {
return $this->errors;
}
}
```
Usage:
```
// create a DOM document and load the HTML data
$xmlDoc = new DomDocument();
$caller = new ErrorTrap(array($xmlDoc, 'loadHTML'));
// this doesn't dump out any warnings
$caller->call($fetchResult);
if (!$caller->ok()) {
var_dump($caller->errors());
}
``` | Call
```
libxml_use_internal_errors(true);
```
prior to processing with with `$xmlDoc->loadHTML()`
This tells libxml2 [not to send](http://www.php.net/manual/en/function.libxml-use-internal-errors.php) errors and warnings through to PHP. Then, to check for errors and handle them yourself, you can consult [libxml\_get\_last\_error()](http://www.php.net/manual/en/function.libxml-get-last-error.php) and/or [libxml\_get\_errors()](http://www.php.net/manual/en/function.libxml-get-errors.php) when you're ready:
```
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$errors = libxml_get_errors();
foreach ($errors as $error) {
// handle the errors as you wish
}
``` | Disable warnings when loading non-well-formed HTML by DomDocument (PHP) | [
"",
"php",
"html",
"warnings",
"domdocument",
""
] |
Reads and writes to certain primitive types in C# such as `bool` and `int` are atomic.
(See section 5.5, "5.5 Atomicity of variable references", in the C# Language Spec.)
But what about accessing such variables via properties? Is it reasonable to assume that they will also be atomic and thread-safe? E.g. Is a read of `MyProperty` below atomic and thread-safe?:
```
public bool MyProperty { get { return _foo; } }
```
And what about auto-implemented properties?
```
public bool MyProperty { get; }
``` | You need to distinguish between "atomic" and "thread-safe" more closely. As you say, writes are atomic for most built-in value types and references.
However, that doesn't mean they're thread-safe. It just means that if values "A" and "B" are both written, a thread will never see something in between. (e.g. a change from 1 to 4 will never show 5, or 2, or any value other than 1 or 4.) It *doesn't* mean that one thread will see value "B" as soon as it's been written to the variable. For that, you need to look at the memory model in terms of volatility. Without memory barriers, usually obtained through locking and/or volatile variables, writes to main memory may be delayed and reads may be advanced, effectively assuming that the value hasn't changed since the last read.
If you had a counter and you asked it for its latest value but never *received* the latest value because of a lack of memory barriers, I don't think you could reasonably call that thread-safe even though each operation may well be atomic.
This has nothing to do with properties, however - properties are simply methods with syntactic sugar around them. They make no extra guarantees around threading. The .NET 2.0 memory model *does* have more guarantees than the ECMA model, and it's possible that it makes guarantees around method entry and exit. Those guarantees should apply to properties as well, although I'd be nervous around the interpretation of such rules: it can be very difficult to reason about memory models sometimes. | If you examine the auto-generated code, you'll see that auto-generated properties are *NOT* thread safe - they are simple get/set to a generated field. In fact, it would be too much of a performance hit to do so (especially when not needed).
In addition, if you are planning on access int/bool values from multiple threads then you should mark it (the field) as [volatile](http://msdn.microsoft.com/en-us/library/x13ttww7(loband).aspx). This basically prevents multithreading issues related to CPU registers. (This is in *addition* to locking, not an alternative) | Are reads and writes to properties atomic in C#? | [
"",
"c#",
"multithreading",
"properties",
"atomic",
""
] |
I'm looking for a method that returns a boolean if the String it is passed is a valid number (e.g. "123.55e-9", "-333,556"). I *don't* want to just do:
```
public boolean isANumber(String s) {
try {
BigDecimal a = new BigDecimal(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
```
Clearly, the function should use a state machine (DFA) to parse the string to make sure invalid examples don't fool it (e.g. "-21,22.22.2", "33-2"). Do you know if any such library exists? I don't really want to write it myself as it's such an obvious problem that I'm sure I'd be re-inventing the wheel.
Thanks,
Nick | I would avoid re-inventing this method and go with Apache Commons. If your using Spring, Struts or many other commonly used java libraries, they often have Apache commons included. You will want the commons-lang.jar file. Here is the method in [NumberUtils](http://commons.apache.org/lang/api-release/org/apache/commons/lang/math/NumberUtils.html#isNumber(java.lang.String)) you would want:
```
isNumber[1]
public static boolean isNumber(java.lang.String str)
Checks whether the String a valid Java number.
Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).
Null and empty String will return false.
Parameters:
str - the String to check
Returns:
true if the string is a correctly formatted number
``` | The exact regular expression is specified in the Javadocs for [`Double.valueOf(String)`](http://java.sun.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)).
> To avoid calling this method on an invalid string and having a `NumberFormatException` be thrown, the regular expression below can be used to screen the input string:
>
> ```
> final String Digits = "(\\p{Digit}+)";
> final String HexDigits = "(\\p{XDigit}+)";
> // an exponent is 'e' or 'E' followed by an optionally
> // signed decimal integer.
> final String Exp = "[eE][+-]?"+Digits;
> final String fpRegex =
> ("[\\x00-\\x20]*"+ // Optional leading "whitespace"
> "[+-]?(" + // Optional sign character
> "NaN|" + // "NaN" string
> "Infinity|" + // "Infinity" string
>
> // A decimal floating-point string representing a finite positive
> // number without a leading sign has at most five basic pieces:
> // Digits . Digits ExponentPart FloatTypeSuffix
> //
> // Since this method allows integer-only strings as input
> // in addition to strings of floating-point literals, the
> // two sub-patterns below are simplifications of the grammar
> // productions from the Java Language Specification, 2nd
> // edition, section 3.10.2.
>
> // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
> "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
>
> // . Digits ExponentPart_opt FloatTypeSuffix_opt
> "(\\.("+Digits+")("+Exp+")?)|"+
>
> // Hexadecimal strings
> "((" +
> // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
> "(0[xX]" + HexDigits + "(\\.)?)|" +
>
> // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
> "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
>
> ")[pP][+-]?" + Digits + "))" +
> "[fFdD]?))" +
> "[\\x00-\\x20]*"); // Optional trailing "whitespace"
>
> if (Pattern.matches(fpRegex, myString))
> Double.valueOf(myString); // Will not throw NumberFormatException
> else {
> // Perform suitable alternative action
> }
> ``` | Java library to check whether a String contains a number *without* exceptions | [
"",
"java",
"format",
"numbers",
"bigdecimal",
"state-machine",
""
] |
Is there a way to trap the browser closing event from JavaScript? I don't want to do this in Page Unload event or anything. It must be handled on clicking the browser close button.
Is it possible? | No. You only have `onbeforeunload` event, available as raw javascript (jquery doesn't include this event).
If you want to try it, try to post here an answer and, without pressing "post your answer" try to close the browser window.
This is the closest way to access the "close window" event. | onbeforeunload event captures every unload event but there is some trick way to handle if user closing browser by clicking close button, here is a sample code
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
//handle if your mouse is over the document body,
//if not your mouse is outside the document and if you click close button return message or do what you want
var out = false;
$("body").mouseover(function(){
out=false;
}).mouseout(function(){
out=true;
});
$(window).bind('beforeunload', function(e){
if(out)
{return "Do you really want to leave this page now?"}
});
});
</script>
</head>
<body>
<p>
<a href="http://cssbased.com">go outside</a>
<br>
<a href="test.html">reload page</a>
<span> </span>
</p>
</body>
</html>
``` | Handle Browser close in JavaScript? | [
"",
"javascript",
""
] |
```
document.click = check;
function check(e)
{
var obj = document.getElementById('calendar_widget');
if (obj != 'null')
{
if (e.target.id != 'show_calender')
obj.style.display='none';
}
}
```
Error is in Internet Explorer: e.target.id is undefined. | IE doesn't support the target property, they use srcElement instead.
Change:
```
if (e.target.id != 'show_calender')
```
to:
```
if ((e.target || e.srcElement).id != 'show_calender')
```
You may also need to add this to the beginning of your function:
```
if (!e) e = window.event
```
Your final code would look like this:
```
function check(e) {
if (!e) e = window.event;
var obj = document.getElementById('calendar_widget');
if (obj != 'null') {
if ((e.target || e.srcElement).id != 'show_calender')
obj.style.display='none';
}
}
``` | Internet Explorer doesn't pass the event object to the event handler - it sets it as a property of the window object instead. Also, it uses `srcElement` instead of `target`. Try
```
document.click = check;
function check(e)
{
var target = e ? e.target : window.event.srcElement;
var obj = document.getElementById('calendar_widget');
if (obj != 'null')
{
if (target.id != 'show_calender')
obj.style.display='none';
}
}
``` | IE e.target.id is not working | [
"",
"javascript",
"internet-explorer",
""
] |
I have a database class which is constructed so that it opens a connection to the database when the first query is run. Should each of the other classes, used for the site's users, groups and so on, create one database object each? This makes the classes easy to deploy elsewhere; they will only depend on the database class. This will however need me to put the credentials in each class. Another approach which seems less messy for me is create a database object and keep it in a global variable. This reduces the active database connections at the same time as it makes it easier to config; the credentials only have to be set once.
Somewhere I've heard that global variables should be avoided. What's the best practice approach to this? | You could get your other classes to take a database connection object in their constructor. That way they don't have to know the credentials.
Another common way is to use singletons for database connections. Essentially this is still a global variable though, but it does mean that you can control the database object instantiation in one place. | I would make a base class that only contains the connection management stuff and nothing table-specific. You can then put the credentials there.
Another option is using a static variable on such a base class for storing the credentials (instead of hardcoding them in a function, which is kind of dirty).
So `BaseDBConnection::$username` and `BaseDBConnection::$password` would contain the credentials, and your other DBConnection classes derive from BaseDBConnection and refer to `self::$username`, etc. | Database object for each class or site-wide? | [
"",
"php",
"database",
""
] |
Earlier, I asked this question:
[How can I perform a ping or traceroute using native python?](https://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python)
However because python is not running as root it doens't have the ability to open the raw ICMP sockets needed to perform the ping/traceroute in native python.
This brings me back to using the system's ping/traceroute shell commands. This question has a couple examples using the `subprocess` module which seem to work well:
[Ping a site in Python?](https://stackoverflow.com/questions/316866/ping-a-site-in-python)
I still have one more requirement though: I need to be able to access the output as it is produced (eg. for a long running traceroute.)
The examples above all run the shell command and then only give you access to the complete output once the command has completed. Is there a way to access the command output as it is produced?
**Edit:** Based on Alex Martelli's answer, here's what worked:
```
import pexpect
child = pexpect.spawn('ping -c 5 www.google.com')
while 1:
line = child.readline()
if not line: break
print line,
``` | [pexpect](http://pexpect.sourceforge.net/pexpect.html) is what I'd reach for, "by default", for any requirement such as yours -- there are other similar modules, but pexpect is almost invariably the richest, most stable, and most mature one. The one case where I'd bother looking for alternatives would be if I had to run correctly under Windows too (where ping and traceroute may have their own problems anyway) -- let us know if that's the case for you, and we'll see what can be arranged!-) | You should read the documentation for the [subprocess](http://docs.python.org/library/subprocess.html) module, it describes how to run an external process and access its output in real time.
Basically, you do
```
from subprocess import Popen, PIPE
p = Popen(['tracert', host], stdout=PIPE)
while True:
line = p.stdout.readline()
if not line:
break
# Do stuff with line
```
Actually, the answers in the SO question you linked to are very close to what you need. [Corey Goldberg's answer](https://stackoverflow.com/questions/316866/ping-a-site-in-python/318142#318142) uses a pipe and `readline`, but since it runs ping with `-n 1` it doesn't last long enough to make a difference. | How can I perform a ping or traceroute in python, accessing the output as it is produced? | [
"",
"python",
"ping",
"traceroute",
""
] |
When I use VSTS debugger to see the properties of instance of class `Process`, many of the properties are marked with `InvalidOperationException`. Why? Am I doing anything wrong?
I am using VSTS 2008 + C# + .Net 2.0 to develop a console application.
Here is my code:
```
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "IExplore.exe";
myProcess.StartInfo.Arguments = @"www.google.com";
myProcess.StartInfo.Verb = "runas";
myProcess.Start();
```
And a screenshot of the debugger:
[](https://i.stack.imgur.com/SrHEj.png) | Had you actually started the process when the debugger picture was taken? That's the screenshot I'd expect to see before the `Start()` method is called.
Note that the common pattern is to create a `ProcessStartInfo`, populate it, and then call the static `Process.Start(startInfo)` method. That makes it conceptually simpler: you don't see the `Process` object until it's been started. | Many of the properties are marked with InvalidOperationException because until you start the process . The object 'myProcess' is not associated with any running process and hence it cannot get the information.
Try adding these statements, after the code to start the process
```
if (myProcess != null)
{
myProcess.WaitForExit();
//or any other statements for that matter
}
```
Now, when you are inside the if statement, the VSTS debugger will be able to show most of the properties associated with the object myProcess. This happens because, myProcess object is now associated with a running process "IExplore.exe". | Invalid Operation Exception from C# Process Class | [
"",
"c#",
".net",
"visual-studio-2008",
"process",
"invalidoperationexception",
""
] |
Our web application (.net/C#) formats currency amounts using amount.ToString("c"), shown localized to a few different regions.
Our French Candian users prefer all amounts to be the US format (123,456.99 vs. the default windows way for fr-CA of 123 456,99).
What is the best way to handle that ? Can I simply modify the regional settings on each webserver in windows for fr-ca? or do I need to create a custom culture? | You may want to look into creating a custom culture, providing the mix of formatting rules that you requre. [There is an article at MSDN describing how to do it](http://msdn.microsoft.com/en-us/library/ms172469.aspx).
In short, you create a [`CultureAndRegionInfoBuilder`](http://msdn.microsoft.com/en-us/library/system.globalization.cultureandregioninfobuilder.aspx) object, define the name, set properties, and register it. Check the article for details. | You can modify the current culture like so:
```
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-CA")
```
You could pull the value from web.config, sure.
EDIT:
Ok, sorry I misunderstood.
This might work:
```
decimal d = 1232343456.99M;
CultureInfo USFormat = new CultureInfo("en-US");
Console.Out.WriteLine(d.ToString(USFormat));
```
This should allow you to just use the USFormat when you're outputting numeric vals. | how to change default culture settings in a .net web application? | [
"",
"c#",
"windows",
"internationalization",
""
] |
I was using a foreach loop to go through a list of data to process (removing said data once processed--this was inside a lock). This method caused an ArgumentException now and then.
Catching it would have been expensive so I tried tracking down the issue but I couldn't figure it out.
I have since switched to a for loop and the problem seems to have went away. Can someone explain what happened? Even with the exception message I don't quite understand what took place behind the scenes.
Why is the for loop apparently working? Did I set up the foreach loop wrong or what?
This is pretty much how my loops were set up:
```
foreach (string data in new List<string>(Foo.Requests))
{
// Process the data.
lock (Foo.Requests)
{
Foo.Requests.Remove(data);
}
}
```
and
```
for (int i = 0; i < Foo.Requests.Count; i++)
{
string data = Foo.Requests[i];
// Process the data.
lock (Foo.Requests)
{
Foo.Requests.Remove(data);
}
}
```
EDIT: The for\* loop is in a while setup like so:
```
while (running)
{
// [...]
}
```
EDIT: Added more information about the exception as requested.
```
System.ArgumentException: Destination array was not long enough. Check destIndex and length, and the array's lower bounds
at System.Array.Copy (System.Array sourceArray, Int32 sourceIndex, System.Array destinationArray, Int32 destinationIndex, Int32 length) [0x00000]
at System.Collections.Generic.List`1[System.String].CopyTo (System.String[] array, Int32 arrayIndex) [0x00000]
at System.Collections.Generic.List`1[System.String].AddCollection (ICollection`1 collection) [0x00000]
at System.Collections.Generic.List`1[System.String]..ctor (IEnumerable`1 collection) [0x00000]
```
EDIT: The reason for the locking is that there is another thread adding data. Also, eventually, more than one thread will be processing data (so if the entire setup is wrong, please advise).
EDIT: It was hard to pick a good answer.
I found Eric Lippert's comment deserving but he didn't really answer (up-voted his comment anyhow).
Pavel Minaev, Joel Coehoorn and Thorarin all gave answers I liked and up-voted. Thorarin also took an extra 20 minutes to write some helpful code.
I which I could accept all 3 and have it split the reputation but alas.
Pavel Minaev is the next deserving so he gets the credit.
Thanks for the help good people. :) | Your problem is that the constructor of `List<T>` that creates a new list from `IEnumerable` (which is what you call) isn't thread-safe with respect to its argument. What happens is that while this:
```
new List<string>(Foo.Requests)
```
is executing, another thread changes `Foo.Requests`. You'll have to lock it for the duration of that call.
### [EDIT]
As pointed out by Eric, another problem `List<T>` isn't guaranteed safe for readers to read while another thread is changing it, either. I.e. concurrent readers are okay, but concurrent reader and writer are not. And while you lock your writes against each other, you don't lock your reads against your writes. | After seeing your exception; it looks to me that Foo.Requests is being changed while the shallow copy is being constructed. Change it to something like this:
```
List<string> requests;
lock (Foo.Requests)
{
requests = new List<string>(Foo.Requests);
}
foreach (string data in requests)
{
// Process the data.
lock (Foo.Requests)
{
Foo.Requests.Remove(data);
}
}
```
---
## Not the question, but...
That being said, I somewhat doubt the above is what you want either. If new requests are coming in during processing, they will not have been processed when your foreach loop terminates. Since I was bored, here's something along the lines that I think you're trying to achieve:
```
class RequestProcessingThread
{
// Used to signal this thread when there is new work to be done
private AutoResetEvent _processingNeeded = new AutoResetEvent(true);
// Used for request to terminate processing
private ManualResetEvent _stopProcessing = new ManualResetEvent(false);
// Signalled when thread has stopped processing
private AutoResetEvent _processingStopped = new AutoResetEvent(false);
/// <summary>
/// Called to start processing
/// </summary>
public void Start()
{
_stopProcessing.Reset();
Thread thread = new Thread(ProcessRequests);
thread.Start();
}
/// <summary>
/// Called to request a graceful shutdown of the processing thread
/// </summary>
public void Stop()
{
_stopProcessing.Set();
// Optionally wait for thread to terminate here
_processingStopped.WaitOne();
}
/// <summary>
/// This method does the actual work
/// </summary>
private void ProcessRequests()
{
WaitHandle[] waitHandles = new WaitHandle[] { _processingNeeded, _stopProcessing };
Foo.RequestAdded += OnRequestAdded;
while (true)
{
while (Foo.Requests.Count > 0)
{
string request;
lock (Foo.Requests)
{
request = Foo.Requests.Peek();
}
// Process request
Debug.WriteLine(request);
lock (Foo.Requests)
{
Foo.Requests.Dequeue();
}
}
if (WaitHandle.WaitAny(waitHandles) == 1)
{
// _stopProcessing was signalled, exit the loop
break;
}
}
Foo.RequestAdded -= ProcessRequests;
_processingStopped.Set();
}
/// <summary>
/// This method will be called when a new requests gets added to the queue
/// </summary>
private void OnRequestAdded()
{
_processingNeeded.Set();
}
}
static class Foo
{
public delegate void RequestAddedHandler();
public static event RequestAddedHandler RequestAdded;
static Foo()
{
Requests = new Queue<string>();
}
public static Queue<string> Requests
{
get;
private set;
}
public static void AddRequest(string request)
{
lock (Requests)
{
Requests.Enqueue(request);
}
if (RequestAdded != null)
{
RequestAdded();
}
}
}
```
There are still a few problems with this, which I will leave to the reader:
* Checking for \_stopProcessing should probably be done after every time a request is processed
* The Peek() / Dequeue() approach won't work if you have multiple threads doing processing
* Insufficient encapsulation: Foo.Requests is accessible, but Foo.AddRequest needs to be used to add any requests if you want them processed.
* In case of multiple processing threads: need to handle the queue being empty inside the loop, since there is no lock around the Count > 0 check. | Why doesn't a foreach loop work in certain cases? | [
"",
"c#",
"exception",
"foreach",
"for-loop",
""
] |
I have a table which have a single field. and it have a values like (3,7,9,11,7,11)
Now I want a query which will pick the value that occurred least number of times and if there is a tie with minimum occurrences then use the smallest number
In this case the answer will be 3. | Something like this:
```
SELECT TOP 1 COUNT(*), myField
FROM myTable
GROUP BY (myField)
ORDER BY COUNT(*) ASC
```
**ADDITIONAL:** And to taking into account the tie-breaker situation:
```
SELECT TOP 1 COUNT(*), myField
FROM myTable
GROUP BY (myField)
ORDER BY COUNT(*) ASC, myField ASC
``` | In `MySQL` and `PostgreSQL`:
```
SELECT *
FROM (
SELECT field, COUNT(*) AS cnt
FROM mytable
GROUP BY
field
) q
ORDER BY
cnt, field
LIMIT 1
``` | SQL: Retrieve value from a column that occurred least number of times | [
"",
"sql",
"sql-server",
""
] |
What are the considerations of using [`Iterable<T>`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html) vs. [`Collection<T>`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html) in Java?
For example, consider implementing a type that is primarily concerned with containing a collection of `Foo`s, and some associated metadata. The constructor of this type allows one-time initialisation of the object list. (The metadata can be set later.) What type should this constructor accept? `Iterable<Foo>`, or `Collection<Foo>`?
What are the considerations for this decision?
Following the pattern set forth by library types such as `ArrayList` (which can be initialised from any `Collection`, but *not* an `Iterable`) would lead me to use `Collection<Foo>`.
But why not accept `Iterable<Foo>`, given that this is is sufficient for the initialisation needs? Why demand a higher level of functionality (`Collection`) from the consumer, than what is strictly necessary (`Iterable`)? | Many of the collection types existed before [`Iterable<T>`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html) (which was only introduced in 1.5) - there was little reason to add a constructor to accept `Iterable<T>` *as well as* [`Collection<T>`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html) but changing the existing constructor would have been a breaking change.
Personally I would use `Iterable<T>` if that allows you to do everything you want it to. It's more flexible for callers, and in particular it lets you do *relatively* easy filtering/projection/etc using the Google Java Collections (and no doubt similar libraries). | An `Iterable` produces `Iterator` objects. An `Iterator` object, by definition, *iterates*. Notice, that the `Iterator` interface makes no promise as to how many times `next()` can be called before `hasNext()` returns `false`. An `Iterator` could possibly iterate over `Integer.MAX_VALUE + 1` values before its `hasNext()` method returns `false`.
However, a `Collection` is a special form of `Iterable`. Because a `Collection` cannot have more than `Integer.MAX_VALUE` elements (by virtue of the `size()` method), it is naturally presumed that its `Iterator` objects will not iterate over this many elements.
Therefore, by accepting a `Collection` rather than an `Iterable`, your class can have some guarantee over how many elements are being passed in. This is especially desirable if your class is itself a `Collection`.
Just my two cents... | When should I accept a parameter of Iterable<T> vs. Collection<T> in Java? | [
"",
"java",
"collections",
""
] |
This question is a bit of a "best-practice" question, my team is new to Maven and I am looking for the best way forward on this topic:
When working on a project that has packaging = `war`, what's the best way to deploy it to your Maven repository (such as a company-wide Nexus installation)?
For example, let's say you have a webapp where the environment-specific properties files (such as database connection strings, logging configuration, etc., which differ based on dev/QA/production environments) are included in the final packaged app based on properties or environment variables. When building this type of app, what makes the most sense to deploy to your repository? Should it be the WAR file with production settings, or a JAR of all of the classes and none of the resources?
The reason I am asking is that when you are building a webapp such as this, you really have a codebase plus a set of environment-specific resource files. The former makes a lot of sense to deploy to your repository so it is available to other projects, but the latter doesn't make much sense to share and make available to others. | I suggest you build a raw war project with perhaps some default files for development and deploy that to the repository.
Then you can build multiple projects which depend on the war project and provide their own specific resources.
---
The JavaOne 2009 presentation [Getting Serious About Build Automation: Using Maven in the Real World](http://developers.sun.com/learning/javaoneonline/j1online.jsp?track=javaee&yr=2009) has a good example on how this can be done
1. Create a 'myapp-deploy' maven project
2. In the deploy project, reference the war project
```
<dependency>
<groupId>myorg.myapp</groupId>
<groupId>myapp-web</groupId>
<version>${webapp.version}</version>
<type>war</type>
</dependency>
```
3. In the deploy project, use an overlay to import the files from the web project
```
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>myapp-web</warName>
<overlays>
<overlay>
<groupId>myorg.myapp</groupId>
<artifactId>myapp-web</artifactId>
<excludes>
<exclude>WEB-INF/classes/config.properties</exclude>
</excludes>
</overlay>
</overlays>
<!-- some config elements not shown here -->
</plugin>
```
4. In the deploy project, include the extra resources from the deploy project into the web project
```
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<!-- some config elements not shown here -->
<webResources>
<resource>
<directory>${patch.path}</directory>
</resource>
</webResources>
</configuration>
</plugin>
``` | I think you should build one war. Mucking about with overlays is too much of a temptation for developers to "just drop this fix in for that environment".
Use [JNDI resources](http://docs.sun.com/source/819-0076/jndi.html) for environment variables and [attach](http://mojo.codehaus.org/build-helper-maven-plugin/attach-artifact-mojo.html) external JNDI resource file(s) (you can attach one for each type of environment if needed).
Of course you then need a process to retrieve the correct resource file and apply it to your environment (tweaking it with passwords and other sensitive variables), but that is a fairly straightforward scripting exercise. | Deploying webapp's resources to maven repository? | [
"",
"java",
"maven-2",
""
] |
`java.io` has many different [I/O](http://en.wikipedia.org/wiki/Input/output) streams, (FileInputStream, FileOutputStream, FileReader, FileWriter, BufferedStreams... etc.) and I am confused in determining the differences between them. What are some examples where one stream type is preferred over another, and what are the real differences between them? | This is a big topic! I would recommend that you begin by reading [I/O Streams](https://docs.oracle.com/javase/tutorial/essential/io/streams.html):
> An I/O Stream represents an input
> source or an output destination. A
> stream can represent many different
> kinds of sources and destinations,
> including disk files, devices, other
> programs, and memory arrays.
>
> Streams support many different kinds
> of data, including simple bytes,
> primitive data types, localized
> characters, and objects. Some streams
> simply pass on data; others manipulate
> and transform the data in useful ways. | **Streams:** one byte at a time. Good for binary data.
**Readers/Writers:** one character at a time. Good for text data.
**Anything "Buffered":** many bytes/characters at a time. Good almost all the time. | Java I/O streams; what are the differences? | [
"",
"java",
"io",
"stream",
"java-io",
""
] |
Through using IntelliSense and looking at other people's code, I have come across this `IntPtr` type; every time it has needed to be used I have simply put `null` or `IntPtr.Zero` and found most functions to work. What exactly is it and when/why is it used? | It's a "native (platform-specific) size integer." It's internally represented as `void*` but exposed as an integer. You can use it whenever you need to store an unmanaged pointer and don't want to use `unsafe` code. `IntPtr.Zero` is effectively `NULL` (a null pointer). | It's a value type large enough to store a memory address as used in native or unsafe code, but not directly usable as a memory address in safe managed code.
You can use `IntPtr.Size` to find out whether you're running in a 32-bit or 64-bit process, as it will be 4 or 8 bytes respectively. | Just what is an IntPtr exactly? | [
"",
"c#",
"intptr",
""
] |
If I have two divs, one shown, the other hidden, I want the images in the visible div to load first and only then for the other hidden images to load.
Is there a way to do this?
```
<div class="shown">
<img src="a.jpg" class="loadfirst">
<img src="b.jpg" class="loadfirst">
<img src="c.jpg" class="loadfirst">
<img src="d.jpg" class="loadfirst">
<img src="e.jpg" class="loadfirst">
</div
<div style="display:none" class="hidden">
<img src="1.jpg" class="loadsecond">
<img src="2.jpg" class="loadsecond">
<img src="3.jpg" class="loadsecond">
<img src="4.jpg" class="loadsecond">
<img src="5.jpg" class="loadsecond">
</div>
``` | As others have said, it all comes down to which images are listed first in the html markup.
But, something that may help with this problem is to display a loading spinner until all of your images are fully loaded.
You could do this with JQuery, as in this example.
<http://jqueryfordesigners.com/image-loading/> | The browser should be requesting the images in the order that the markup lists them in. So it would ask for a.jpg, b.jpg, etc.
If you don't want the hidden DIV images to load with the page then you would have to insert that HTML from the client side once you want the images loaded. | Can you control the order in which images (hidden vs visible) on a web page are loaded? | [
"",
"javascript",
"css",
"html",
"visibility",
""
] |
I have my own edit in place function for jquery which looks like this
```
$('.editRow').live('click', function() {
var row = $(this).parent('td').parent('tr');
row.find('.1u').slideUp('fast');
row.find('.1p').slideUp('fast');
row.find('.inputTxt').slideDown('fast');
$(this).parent('td').empty().append('<a href=# class=cancel>Cancel</a> / <a href=# class=save>Save</a>');
});
$('.cancel').live('click', function () {
var row = $(this).parent('td').parent('tr');
row.find('.1u').slideDown('fast');
row.find('.1p').slideDown('fast');
row.find('.inputTxt').slideUp('fast');
$(this).parent('td').empty().append('<a href=# class=editRow>Edit</a>');
});
$('.save').live('click', function () {
var thisParam = $(this);
var row = $(this).parent('td').parent('tr');
var id = row.attr('id');
var userid = row.find('#1ui').val();
var pass = row.find('#1pi').val();
$.ajax({
type: 'post',
url: 'filefetch_update.php',
data: 'action=updateUser&pass=' + pass + '&id=' + id + '&userid=' + userid,
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
var row = thisParam.parent('td').parent('tr');
row.find('.1u').text(userid).slideDown('fast');
row.find('.1p').text(pass).slideDown('fast');
row.find('.inputTxt').slideUp('fast');
thisParam.parent('td').empty().append('<a href=# class=editRow>Edit</a>');
}
});
});
```
Now i want to run the **save** function when the user clicks Save and also when enter is pressed on keyboard. | This should work for you:
```
$(document).keypress(function(e) {
if (e.which == 13) {
$('.save').click();
}
)};
``` | Not sure but this might work
```
<input type="text" onkeypress="return runScript(event)" />
function runScript(e) {
if (e.keyCode == 13) {
// do some thing like
$('.save').click();
}
}
``` | How to fire the same function when user presses enter or makes a click | [
"",
"javascript",
"jquery",
""
] |
I'm having a general discussion with one of my developers about philosophy of structuring TSQL stored procedures.
Let's make a couple assumptions (to avoid responses along the line of "don't put business logic in SPs", etc):
1. Business Logic can be in SPs
2. There is no standard scripted layer of CRUD SPs
3. Complex procedures are executed in single scope within an SP
4. Dynamic SQL is allowed
Essentially my coworker has hit his head against the SQL Server wall of nested inserts in SQL Server. You can nest them beyond a single level.
i.e. :
* PROC C is called by PROC B, the
results of which are INSERTED into a
temp table #X and operations are
performed and then a result set is
returned
* PROC B is called by PROC A, the
results (our original final select
from PROC C + Transformations) of
which are INSERTED into a temp table #Z and operations are performed and then a result set is returned
This results in SQL Server throwing an error saying you can't nest inserts into temp tables.
I agree with this logic, assuming our four original premises, it would then simply be permissible to include the logic executed in PROC C directly in PROC B.
My coworker however feels, being a good Object Orientated encapsulator, that by encapsulating the final nested insert the code is more maintainable.
I on the other hand feel that encapsulating code into CRUD operations, which use temp tables, is fundamentally opposed to the declarative and procedural approach to data management inherent in SQL and relational databases.
Ultimately, his argument is that if the logic was simply in one SP, then should the table schema change, all SPs addressing the table would have to change. A valid point, however I feel that is unlikely as once our development has bedded down tables are not subject to ad-hoc change.
My argument is that by encapsulating temp table inserts, for use in n-th degree nesting (if possible - thankfully its not), would result in a case in which all SPs which call that encapsulated procedure (or should we now rather call it a method?) would have to be retested anyway in the event that the centralized encapsulated procedure changes, since unless its outputs are the same, it may well result in a break in the calling parent SP.
I suppose my ultimate question is this, fundamentally is T-SQL a declarative, a procedural or an imperative language. In my opinion it is clearly a mixture --> I suppose if I had to create the recipe I'd say:
10% Declarative (since in principle its declarative)
70% Procedural (In our case, the case in which business processes are in procs)
20% Imperative (Imperative constructs exist - esp. in newer SQL Server versions)
---
p.s. At the moment he's suggesting using OUTPUT parameter in the SP call, rather than:
insert into #temp
exec spInsertUpdateTable
I have a whole other dislike for OUTPUT parameters, but I suppose that might have to fly. Any other suggestions? | Not an answer, just some off the top of my head ideas:
Single-values are passed back more efficiently via OUTPUT parameters than by result sets. The value of this decreases as the number of returned values increases, however.
In SQL 2008, you can pass temp tables as parameters. Ok, there's a lot of setup you have to do in order to enable this, but even so it could be worth the effort, as you'd then get your N levels of nested calls.
Easily maintainable code is a holy grail that we should all strive for, since--if there's any justice--the person who supports the code should be its original creator. [Insert Dr. Frankenstien joke here.] This should underscore the benefits of modularized code ("sub-procedures"); if you only have to modify the one nested procedure, and you don't have to change the inputs or outputs, then you shouldn't have to worry (i.e. refactor) about procedures that call or are called by it.
As for declarative vs. procedural vs. imperative, sorry, its been years since college, and I've been in the trenches too long to be able to discuss high-falutin' theories without working Google for an hour. | I guess perhaps this avoids instead of answering the question, but the first thing I would do is examine why there are all these temp tables that need passing around. Most often a well constructed select, insert or update statement can replace reams of temp tables. This is actually the intent of T-SQL - to be able to write a single statement to act on a whole set. So where you say "+ transformations" I go straight to "ah, refactor those temp tables right out of the solution by making a select that *does* the transformations." Make sense?
Example: see if you can produce the result you want with two nested views instead of stored procs. No problem passing results between views (that's a bit of a misnomer anyway) PLUS you get query optimization across the whole operation (SQL Server will expand the view defs and optimize the whole thing at once) | Nested Insert within SQL Server (To Encapsulate or not to Encapsulate) | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am making an application which will retrieve all mailboxes from Domino Server.
And Display them in List.
After that i want to extract( display) emails of each mailbox into another list.
eg:
Consider example of outlook.When we click on particular pst folder. all mails in selected folder get displayed.
Kindly send me code if possible.As i am new to C#.
Or send me related links. | I guess the simplest way to enumerate all the mailboxes without turning to Domino development is via LDAP. Then, as reto suggests, the IMAP interface should be able to show you the contents of each mailbox.
Of course, you'll need an account with access to each users mailbox. | I'd try using IMAP to fetch the necessary information. This should be easier than trying to use some Domino specific API. One of many [examples](http://www.example-code.com/csharp/imap_readMail.asp) | Reading domino server' mailbox using C# | [
"",
"c#",
"lotus-notes",
"lotus-domino",
""
] |
What am I doing wrong here?
```
i = 0
cursor.execute("insert into core_room (order) values (%i)", (int(i))
```
Error:
```
int argument required
```
The database field is an int(11), but I think the %i is generating the error.
**Update:**
Here's a more thorough example:
```
time = datetime.datetime.now()
floor = 0
i = 0
```
try:
booster\_cursor.execute('insert into core\_room (extern\_id, name, order, unit\_id, created, updated) values (%s, %s, %s, %s, %s, %s)', (row[0], row[0], i, floor, time, time,))
except Exception, e:
print e
Error:
```
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order, unit_id, created, updated) values ('99', '99', '235', '12', '2009-07-24 1' at line 1")
``` | Two things. First, use `%s` and not `%i`. Second, parameters must be in a tuple - so you need `(i,)` (with comma after `i`).
Also, `ORDER` is a keyword, and should be escaped if you're using it as field name. | I believe the second argument to execute() is expected to be an iterable. IF this is the case you need to change:
```
(int(i))
```
to:
```
(int(i),)
```
to make it into a tuple. | Python error: int argument required | [
"",
"python",
"mysql",
"mysql-error-1064",
""
] |
I have 2 DIVs on an HTML page:
```
<div id="divDebug" />
<div id="divResult" />
```
I have a script that hits a web service and fills them up with data:
```
document.getElementById("divDebug").innerHtml = rawResult;
document.getElementById("divResult").innerHtml = processResult(rawResult);
```
Here's my problem:
1. The above code works nicely in IE 8
2. The above code sometimes works and sometimes doesn't in Chrome 3.
3. Only the first line works in FF 3.51. Upon testing with FireBug, I can see that the expression `document.getElementById("divResult")` evaluates to `null`.
After much trial and error, I found out that if I change the HTML code to:
```
<div id="divDebug"></div>
<div id="divResult"></div>
```
Everything works well in all 3 browsers.
My questions are:
1. Why do I have to close the DIVs in order for them to be available?
2. Is this a JavaScript thing, or an FF bug?
3. Are there any other HTML elements that will become unavailable if they are not closed properly?
Thanks! | `<div/>` is the XML way of closing tags, basically. `<div></div>` is HTML (and XML).
What DOCTYPE are you using?
From [C. HTML Compatibility Guidelines](http://www.w3.org/TR/xhtml1/guidelines.html#C_3) in [XHTML™ 1.0 The Extensible HyperText Markup Language (Second Edition)](http://www.w3.org/TR/xhtml1/Cover.html):
> ## C.3. Element Minimization and Empty Element Content
>
> Given an empty instance of an element whose content model is not
> EMPTY (for example, an empty title or
> paragraph) do not use the minimized
> form (e.g. use `<p> </p>` and not `<p
> />`). | What's the DOCTYPE that you are using? DOCTYPE defines how the browser should interpret the HTML.
Browser uses Content-type header to decide how to parse the content being served. If content-type is text/html, it will be parsed as HTML and if content type is application/xhtml+xml, it will be parsed as XHTML. [Thanks Miles for the correction.]
[HTML4 spec requires that you close the DIV tag with proper end tag](http://www.w3.org/TR/html401/struct/global.html#h-7.5.4). There are certain tags e.g. img, br, meta, which could be self-closing.
If you are using XHTML, you can [self close the tag if it's empty otherwise closing tag is required](http://www.w3.org/TR/xhtml1/#h-4.3).
Another tip: Always validate your HTML/XHTML against the DOCTYPE you have used, you can eliminate these kind of bugs. | document.getElementById fails for single-tag DIV | [
"",
"javascript",
"firefox",
"html",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.