qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
34,128 | <p>We are trying to create a web-service that we plan to pass a variable amount of variables to it.</p>
<p>Can this be done?</p>
<p>Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service.</p>
<p>Here is an example of the XML we are looking to send, we would sent an unknown amount of functions depending on the needed return.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<WebMethod xmlns="http://tempuri.org/">
<domains>
<function1>
<title>Some Title</title>
<type>25</type>
</function1>
<function2 />
<function3>
<param>13</param>
</function3>
</domains>
</WebMethod>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>Will this work or should we do a different way?</p>
| [
{
"answer_id": 34132,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply pass a variable-length array as a parameter.</p>\n"
},
{
"answer_id": 34138,
"author": "... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3582/"
] | We are trying to create a web-service that we plan to pass a variable amount of variables to it.
Can this be done?
Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service.
Here is an example of the XML we are looking to send, we would sent an unknown amount of functions depending on the needed return.
```
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<WebMethod xmlns="http://tempuri.org/">
<domains>
<function1>
<title>Some Title</title>
<type>25</type>
</function1>
<function2 />
<function3>
<param>13</param>
</function3>
</domains>
</WebMethod>
</soap:Body>
</soap:Envelope>
```
Will this work or should we do a different way? | I would pass in an xml document instead of doing concreate functions for this.
The webservice in your example is leaky - the consumer needs to know too much about this interface and the implementation of the webservice internally.
XML Document and then tie that with an XSD. That way you can prevalidte the input to the webservice.
Take a look at these
[IBM Developer](http://www.ibm.com/developerworks/webservices/library/ws-docstyle.html)
[ASP.NET Forum](http://forums.asp.net/p/1253455/2323689.aspx#2323689)
I would also recommend using this for testing webservices and its free
[WSStudio](http://www.codeplex.com/wsstudioexpress) |
34,144 | <p>I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.</p>
<p>To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that.</p>
| [
{
"answer_id": 34156,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 6,
"selected": false,
"text": "<p>Using the <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/\" rel=\"noreferrer\">Maven Dependency Plug... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] | I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.
To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that. | To add to @David Crow, here's [a dependency:tree example](http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html) from the Maven site:
```
mvn dependency:tree -Dincludes=velocity:velocity
```
might output
```
[INFO] [dependency:tree]
[INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT
[INFO] \- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile
[INFO] \- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile
[INFO] \- velocity:velocity:jar:1.4:compile
``` |
34,155 | <p>I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the <a href="http://en.wikipedia.org/wiki/Continuation" rel="noreferrer">Wikipedia article</a>:</p>
<pre><code>(define the-continuation #f)
(define (test)
(let ((i 0))
; call/cc calls its first function argument, passing
; a continuation variable representing this point in
; the program as the argument to that function.
;
; In this case, the function argument assigns that
; continuation to the variable the-continuation.
;
(call/cc (lambda (k) (set! the-continuation k)))
;
; The next time the-continuation is called, we start here.
(set! i (+ i 1))
i))
</code></pre>
<p>I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate. </p>
<p>So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer.</p>
<p>Cheers!</p>
| [
{
"answer_id": 34173,
"author": "A. Rex",
"author_id": 3508,
"author_profile": "https://Stackoverflow.com/users/3508",
"pm_score": 2,
"selected": false,
"text": "<p>Continuations can be used in \"real-life\" examples whenever the program flow is not linear, or not even pre-determined. A... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] | I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the [Wikipedia article](http://en.wikipedia.org/wiki/Continuation):
```
(define the-continuation #f)
(define (test)
(let ((i 0))
; call/cc calls its first function argument, passing
; a continuation variable representing this point in
; the program as the argument to that function.
;
; In this case, the function argument assigns that
; continuation to the variable the-continuation.
;
(call/cc (lambda (k) (set! the-continuation k)))
;
; The next time the-continuation is called, we start here.
(set! i (+ i 1))
i))
```
I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate.
So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer.
Cheers! | In Algo & Data II we used these all the times to "exit" or "return" from a (long) function
for example the BFS algorthm to traverse trees with was implemented like this:
```
(define (BFS graph root-discovered node-discovered edge-discovered edge-bumped . nodes)
(define visited (make-vector (graph.order graph) #f))
(define q (queue.new))
(define exit ())
(define (BFS-tree node)
(if (node-discovered node)
(exit node))
(graph.map-edges
graph
node
(lambda (node2)
(cond ((not (vector-ref visited node2))
(when (edge-discovered node node2)
(vector-set! visited node2 #t)
(queue.enqueue! q node2)))
(else
(edge-bumped node node2)))))
(if (not (queue.empty? q))
(BFS-tree (queue.serve! q))))
(call-with-current-continuation
(lambda (my-future)
(set! exit my-future)
(cond ((null? nodes)
(graph.map-nodes
graph
(lambda (node)
(when (not (vector-ref visited node))
(vector-set! visited node #t)
(root-discovered node)
(BFS-tree node)))))
(else
(let loop-nodes
((node-list (car nodes)))
(vector-set! visited (car node-list) #t)
(root-discovered (car node-list))
(BFS-tree (car node-list))
(if (not (null? (cdr node-list)))
(loop-nodes (cdr node-list)))))))))
```
As you can see the algorithm will exit when the node-discovered function returns true:
```
(if (node-discovered node)
(exit node))
```
the function will also give a "return value": 'node'
why the function exits, is because of this statement:
```
(call-with-current-continuation
(lambda (my-future)
(set! exit my-future)
```
when we use exit, it will go back to the state before the execution, emptying the call-stack and return the value you gave it.
So basically, call-cc is used (here) to jump out of a recursive function, instead of waiting for the entire recursion to end by itself (which can be quite expensive when doing lots of computational work)
another smaller example doing the same with call-cc:
```
(define (connected? g node1 node2)
(define visited (make-vector (graph.order g) #f))
(define return ())
(define (connected-rec x y)
(if (eq? x y)
(return #t))
(vector-set! visited x #t)
(graph.map-edges g
x
(lambda (t)
(if (not (vector-ref visited t))
(connected-rec t y)))))
(call-with-current-continuation
(lambda (future)
(set! return future)
(connected-rec node1 node2)
(return #f))))
``` |
34,161 | <p>I have the following situation: I built an Access form with a subform (which records are linked to the records of main form via certain key). When I try to delete any record in the subform, I get the following message: “Access has suspended the action because you and another user tried to change the data” (approximate translation from German). Does anyone know how to delete those records from the subform (and, respectively, from the table behind the form).</p>
| [
{
"answer_id": 34172,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": true,
"text": "<p>If you are currently 'editing' the current form then it will not allow the action. Editing a record can sometimes be trig... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717/"
] | I have the following situation: I built an Access form with a subform (which records are linked to the records of main form via certain key). When I try to delete any record in the subform, I get the following message: “Access has suspended the action because you and another user tried to change the data” (approximate translation from German). Does anyone know how to delete those records from the subform (and, respectively, from the table behind the form). | If you are currently 'editing' the current form then it will not allow the action. Editing a record can sometimes be triggered by simply clicking inside a field, or other simple actions you wouldn't normally consider 'editing'.
This is usually avoided in Access by using the RunCommand method to undo any edits before deleting the record:
```
DoCmd.RunCommand acCmdUndo
``` |
34,183 | <p>I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:</p>
<pre><code>SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "builder";
psi.Password = password;
Process.Start(psi);
</code></pre>
<p>If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).</p>
<p>The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?</p>
<p><strong>EDIT:</strong> See my answer below for the contents of the batch file.</p>
<ul>
<li>The output.txt never gets created.</li>
</ul>
<p>I added these lines: </p>
<pre><code>psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
String outp = p.StandardOutput.ReadLine();
</code></pre>
<p>and stepped through them in debug mode. The code hangs on the <code>ReadLine()</code>. I'm stumped!</p>
| [
{
"answer_id": 34187,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>My guess would be that the build.cmd is waiting for some sort of user-interaction/reply. If you log the output of the command... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] | I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:
```
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "builder";
psi.Password = password;
Process.Start(psi);
```
If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).
The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?
**EDIT:** See my answer below for the contents of the batch file.
* The output.txt never gets created.
I added these lines:
```
psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
String outp = p.StandardOutput.ReadLine();
```
and stepped through them in debug mode. The code hangs on the `ReadLine()`. I'm stumped! | I believe I've found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:
<http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx>
That won't work for me, because my batch file uses IF and GOTO, but it would definitely work for simple batch files. |
34,194 | <p>Where can I find some good pointers on best practices for running ASP.NET MVC on IIS6?</p>
<p>I haven't seen any realistic options for web-hosts who provide IIS7-hosting yet. Mostly because I don't live in the U.S.</p>
<p>So I was wondering on how you best build applications in ASP.NET MVC and make it easily available to deploy on both IIS6 and IIS7. Keep in mind that this is for standard web-hosts, so there is no access to ISAPI-filters or special settings inside IIS6.</p>
<p>Are there anything else one should think about when developing ASP.NET MVC-applications to target IIS6? Any functions that doesn't work?</p>
<p>UPDATE: One of the bigger issues is the thing with routes. The pattern {controller}/{action} will work on IIS7, but not IIS6 which needs {controller}.mvc/{action}. So how do I make this transparent? Again, <strong>no ISAPI</strong> and <strong>no IIS-settings</strong>, please.</p>
| [
{
"answer_id": 34206,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p>With IIS6 you can do one of two things:</p>\n\n<ol>\n<li>Setup an ISAPI filter to map MVC URLs to ASP.NET</li>\n<li><a href=\... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] | Where can I find some good pointers on best practices for running ASP.NET MVC on IIS6?
I haven't seen any realistic options for web-hosts who provide IIS7-hosting yet. Mostly because I don't live in the U.S.
So I was wondering on how you best build applications in ASP.NET MVC and make it easily available to deploy on both IIS6 and IIS7. Keep in mind that this is for standard web-hosts, so there is no access to ISAPI-filters or special settings inside IIS6.
Are there anything else one should think about when developing ASP.NET MVC-applications to target IIS6? Any functions that doesn't work?
UPDATE: One of the bigger issues is the thing with routes. The pattern {controller}/{action} will work on IIS7, but not IIS6 which needs {controller}.mvc/{action}. So how do I make this transparent? Again, **no ISAPI** and **no IIS-settings**, please. | It took me a bit, but I figured out how to make the extensions work with IIS 6. First, you need to rework the base routing to include .aspx so that they will be routed through the ASP.NET ISAPI filter.
```
routes.MapRoute(
"Default", // Route name
"{controller}.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
```
If you navigate to Home.aspx, for example, your site should be working fine. But Default.aspx and the default page address of <http://[website]/> stop working correctly. So how is that fixed?
Well, you need to define a second route. Unfortunately, using Default.aspx as the route does not work properly:
```
routes.MapRoute(
"Default2", // Route name
"Default.aspx", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
```
So how do you get this to work? Well, this is where you need the original routing code:
```
routes.MapRoute(
"Default2", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
```
When you do this, Default.aspx and <http://[website]/> both start working again, I think because they become successfully mapped back to the Home controller. So the complete solution is:
```
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"Default2", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
```
And your site should start working just fine under IIS 6. (At least it does on my PC.)
And as a bonus, if you are using Html.ActionLink() in your pages, you should not have to change any other line of code throughout the entire site. This method takes care of properly tagging on the .aspx extension to the controller. |
34,204 | <p>How do I get the latest version of my solution recursively like its done in the solution explorer context menu of Visual Studio? I want to do this from the command line or via a macro. I'm trying to automate a part of my daily routine by using a set of batch files. I am sure a lot of developers would love to have something like this.</p>
<p><code>tf get</code> only gets contents of a folder recursively (not solution). It does not look at project dependencies and so on. That won't work.</p>
| [
{
"answer_id": 35169,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 1,
"selected": false,
"text": "<p>Well... It looks like you have three options.</p>\n\n<ol>\n<li><p>In your batch file, issue a tf get at each directory branc... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
] | How do I get the latest version of my solution recursively like its done in the solution explorer context menu of Visual Studio? I want to do this from the command line or via a macro. I'm trying to automate a part of my daily routine by using a set of batch files. I am sure a lot of developers would love to have something like this.
`tf get` only gets contents of a folder recursively (not solution). It does not look at project dependencies and so on. That won't work. | TFS has a [.Net SDK](http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx) that allows you to create your own custom programs that interact with a TFS Server. You could write a small program that performs the task you need:
```
TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer("MyServer");
VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
WorkSpace[] myWorkSpaces = vcs.QueryWorkSpaces("MyWorkSpaceName", "MyLoginName", "MyComputer");
myWorkSpaces[0].Get(VersionSpec.Latest, GetOptions.GetAll);
``` |
34,209 | <p>In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.</p>
<p>I get the following error:</p>
<pre><code>TypeError: __init__() got an unexpected keyword argument 'core'
</code></pre>
<p>[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?</p>
| [
{
"answer_id": 34391,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 2,
"selected": false,
"text": "<p>This is simple. I started getting this problems a few revisions ago. Basically, just remove the \"core=True\" parameter... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.
I get the following error:
```
TypeError: __init__() got an unexpected keyword argument 'core'
```
[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin? | To get rid of "This field is required," you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField). |
34,249 | <p>What's the best (halting) algorithm for determining if a linked list has a cycle in it?</p>
<p>[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.</p>
<p>[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph".</p>
| [
{
"answer_id": 34253,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 0,
"selected": false,
"text": "<p>What about using a hash table to store the already seen nodes (you look at them in order from the start of the list)? In p... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | What's the best (halting) algorithm for determining if a linked list has a cycle in it?
[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.
[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph". | Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like:
```
node* tortoise(begin), * hare(begin);
while(hare = hare->next)
{
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
hare = hare->next;
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
tortoise = tortoise->next;
}
```
O(n), which is as good as you can get. |
34,312 | <p>I was wondering if anyone that has experience in both this stuff can shed some light on the <em>significant</em> difference between the two if any?</p>
<p>Any specific strength of each that makes it suitable for any specific case?</p>
| [
{
"answer_id": 34338,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 3,
"selected": false,
"text": "<p>I found SimpleTest was even easier than PHPUnit to set up. Just extract it and you are good to go. A benefit of this is i... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2976/"
] | I was wondering if anyone that has experience in both this stuff can shed some light on the *significant* difference between the two if any?
Any specific strength of each that makes it suitable for any specific case? | This question is quite dated but as it is still getting traffic and answers I though I state my point here again even so I already did it on some other (newer) questions.
I'm ***really really*** baffled that SimpleTest **still** is considered an alternative to phpunit. Maybe i'm just misinformed but as far as I've seen:
* PHPUnit is the standard; most frameworks use it (like Zend Framework (1&2), Cake, Agavi, even Symfony is dropping their own Framework in Symfony 2 for phpunit).
* PHPUnit is integrated in every PHP IDE (Eclipse, Netbeans, Zend Stuide, PHPStorm) and works nicely.
* Simpletest has an eclipse extension for PHP 5.1 (a.k.a. old) and nothing else.
* PHPUnit works fine with every continuous integration server since it outputs all standard log files for code coverage and test reports.
* Simpletest does not. While this is not a big problem to start with it will bite you big time once you stop "just testing" and start developing software (Yes that statement is provocative :) Don't take it too seriously).
* PHPUnit is actively maintained, stable and works great for every codebase, every scenario and every way you want to write your tests.
* (Subjective) [PHPUnit provides much nicer](http://www.phpunit.de/manual/3.6/en/code-coverage-analysis.html) code coverage reports [than Simpletest](http://www.simpletest.org/en/reporter_documentation.html)
* With PHPUnit you also get these reports inside your IDE ([Netbeans](http://netbeans.org/kb/docs/php/phpunit.htm%60), Eclipse, ...)
* Also there are a couple of suggestings for a [**`web interface to phpunit tests`**](https://stackoverflow.com/questions/2424457/web-interface-to-phpunit-tests).
I've yet to see any argument in favor of SimpleTest. It's not even simpler to install since PHPUnit is available via pear:
```
pear channel-discover pear.phpunit.de
pear install phpunit/PHPUnit
```
and the "first test" looks pretty much the same.
As of `PHPUnit 3.7` it's **even easier to install** it by just using the [**`PHAR Archive`**](http://www.phpunit.de/manual/current/en/installation.html#installation.phar)
```
wget http://pear.phpunit.de/get/phpunit.phar
chmod +x phpunit-3.7.6.phar
```
or for windows just [downloading](http://pear.phpunit.de/get/phpunit.phar) the phar and running:
```
php phpunit-.phar
```
or when using the [supported composer install](http://www.phpunit.de/manual/current/en/installation.html#installation.composer) ways like
```
"require-dev": {
"phpunit/phpunit": "3.7.*"
}
```
to your composer.json.
---
For everything you want to test PHPUnit will have a solution and you will be able to find help pretty much anywhere (SO, #phpunit irc channel on freenode, pretty much every php developer ;) )
Please correct me if I've stated something wrong or forgot something :)
Overview of PHP Testing tools
=============================
Video: <http://conference.phpnw.org.uk/phpnw11/schedule/sebastian-bergmann/>
Slides: <http://www.slideshare.net/sebastian_bergmann/the-php-testers-toolbox-osi-days-2011>
It mentions stuff like [Atoum](https://github.com/mageekguy/atoum) which calls its self: "A simple, modern and intuitive unit testing framework for PHP!"
---
### Full disclosure
I've originally written this answer Jan. 2011 where I had no affiliation with any PHP Testing project. Since then I became a contributor to PHPUnit. |
34,365 | <p>Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to <code>HttpContext.Current.Request.QueryString</code>. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module?</p>
| [
{
"answer_id": 34375,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "<p>Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1735/"
] | Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to `HttpContext.Current.Request.QueryString`. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module? | Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object in order to modify the querystring.
Using an [IHttpModule](http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx), it might look something like:
```
context.RewritePath(context.Request.Path, context.Request.PathInfo, newQueryStringHere!);
```
Hope this helps! |
34,390 | <p>Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?</p>
<p>Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView?</p>
| [
{
"answer_id": 34432,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>If you are creating composite UserControl, then you can set the <a href=\"http://msdn.microsoft.com/en-us/library/system.... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?
Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView? | Here's what I did:
```
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" />
```
It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.
---
Here's an even more concise way to do this with multiple references;
```
<% if (false) { %>
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" />
<script type="text/javascript" src="js/jquery-1.2.6.js" />
<% } %>
```
As seen in [this blog post](http://haacked.com/archive/2008/11/21/combining-jquery-form-validation-and-ajax-submission-with-asp.net.aspx) from Phil Haack. |
34,394 | <p>How would you programmacially abbreviate <code>XHTML</code> to an arbitrary number of words without leaving unclosed or corrupted tags?</p>
<p>i.e.</p>
<pre><code><p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget,
hendrerit, <em>justo</em>.
</p>
</code></pre>
<p>Abbreviated to 25 words would be:</p>
<pre><code><p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue...</span>
</p>
</code></pre>
| [
{
"answer_id": 34432,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>If you are creating composite UserControl, then you can set the <a href=\"http://msdn.microsoft.com/en-us/library/system.... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3187/"
] | How would you programmacially abbreviate `XHTML` to an arbitrary number of words without leaving unclosed or corrupted tags?
i.e.
```
<p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget,
hendrerit, <em>justo</em>.
</p>
```
Abbreviated to 25 words would be:
```
<p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue...</span>
</p>
``` | Here's what I did:
```
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" />
```
It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.
---
Here's an even more concise way to do this with multiple references;
```
<% if (false) { %>
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" />
<script type="text/javascript" src="js/jquery-1.2.6.js" />
<% } %>
```
As seen in [this blog post](http://haacked.com/archive/2008/11/21/combining-jquery-form-validation-and-ajax-submission-with-asp.net.aspx) from Phil Haack. |
34,395 | <p>I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit?</p>
| [
{
"answer_id": 34431,
"author": "otsdr",
"author_id": 321238,
"author_profile": "https://Stackoverflow.com/users/321238",
"pm_score": 4,
"selected": true,
"text": "<p>In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this:</p>\n\n<pre... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2348/"
] | I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit? | In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this:
```
static string Truncate(string s, int maxLength) {
if (Encoding.UTF8.GetByteCount(s) <= maxLength)
return s;
var cs = s.ToCharArray();
int length = 0;
int i = 0;
while (i < cs.Length){
int charSize = 1;
if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))
charSize = 2;
int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);
if ((byteSize + length) <= maxLength){
i = i + charSize;
length += byteSize;
}
else
break;
}
return s.Substring(0, i);
}
```
The returned string can then be safely transferred to a byte array of length maxLength. |
34,398 | <p>I have a new database table I need to create...<br>
It logically contains an <code>ID</code>, a <code>name</code>, and a <code>"value"</code>.<br>
That value field could be either numeric or a character string in nature. </p>
<p>I don't think I want to just make the field a <code>varchar</code>, because I also want to be able to query with filters like <code>WHERE value > 0.5</code> and such.</p>
<p>What's the best way to model this concept in SQL Server 2005?</p>
<p><strong>EDIT:</strong>
I'm not opposed to creating multiple fields here (one for numbers, one for non-numbers), but since they're all really the same concept, I wasn't sure that was a great idea.<br>
I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column. </p>
<p>Any opinions on that?</p>
<p>What I want to achieve is really pretty simple... usually this data will just be blindly displayed in a grid-type view.<br>
I want to be also able to filter on the numeric values in that grid. This table will end up being in the tens of millions of records, so I don't want to paint myself into a corner with querying performance.<br>
That querying performance is my main concern.</p>
| [
{
"answer_id": 34402,
"author": "Tundey",
"author_id": 1453,
"author_profile": "https://Stackoverflow.com/users/1453",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to store numeric and string values in the same column, I am not sure you can avoid doing a lot of casts and con... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] | I have a new database table I need to create...
It logically contains an `ID`, a `name`, and a `"value"`.
That value field could be either numeric or a character string in nature.
I don't think I want to just make the field a `varchar`, because I also want to be able to query with filters like `WHERE value > 0.5` and such.
What's the best way to model this concept in SQL Server 2005?
**EDIT:**
I'm not opposed to creating multiple fields here (one for numbers, one for non-numbers), but since they're all really the same concept, I wasn't sure that was a great idea.
I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column.
Any opinions on that?
What I want to achieve is really pretty simple... usually this data will just be blindly displayed in a grid-type view.
I want to be also able to filter on the numeric values in that grid. This table will end up being in the tens of millions of records, so I don't want to paint myself into a corner with querying performance.
That querying performance is my main concern. | Your issue with mixing data may be how Sql 2005 sorts text data. It's not a 'natural' sort.
If you have a varchar field and you do:
```
where value > '20.5'
```
Values like "5" will be in your result (as in a character based sort "5" comes after "20.5")
You're going to be better off with separate columns for storage.
Use Coalesce to merge them into one column if you need them merged in your results:
```
select [ID], [Name], Coalesce( [value_str], [value_num] )
from [tablename]
``` |
34,401 | <p>Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine?</p>
<pre><code><?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="elmah">
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
<add name="elmah-sql" connectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***" />
</connectionStrings>
<elmah>
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sql" >
</errorLog>
<errorMail from="test@test.com"
to="test@test.com"
subject="Application Exception"
async="false"
smtpPort="25"
smtpServer="***"
userName="***"
password="***">
</errorMail>
</elmah>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="CustomError.aspx">
<error statusCode="403" redirect="NotAuthorized.aspx" />
<!--<error statusCode="404" redirect="FileNotFound.htm" />-->
</customErrors>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
</httpModules>
</system.web>
</configuration>
</code></pre>
| [
{
"answer_id": 34434,
"author": "Rob Bazinet",
"author_id": 2305,
"author_profile": "https://Stackoverflow.com/users/2305",
"pm_score": 3,
"selected": false,
"text": "<p>I have used Elmah myself in this configuration and I had to setup the server with SMTP locally. It is a straight-forw... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] | Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by \* \* \*. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine?
```
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="elmah">
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
<add name="elmah-sql" connectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***" />
</connectionStrings>
<elmah>
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sql" >
</errorLog>
<errorMail from="test@test.com"
to="test@test.com"
subject="Application Exception"
async="false"
smtpPort="25"
smtpServer="***"
userName="***"
password="***">
</errorMail>
</elmah>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="CustomError.aspx">
<error statusCode="403" redirect="NotAuthorized.aspx" />
<!--<error statusCode="404" redirect="FileNotFound.htm" />-->
</customErrors>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
</httpModules>
</system.web>
</configuration>
``` | You need the ErrorMail httpModule.
add this line inside the <httpModules> section
```
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
```
If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server. |
34,411 | <p>I always tend to forget these built-in <strong>Symfony</strong> functions for making links.</p>
| [
{
"answer_id": 34426,
"author": "andyuk",
"author_id": 2108,
"author_profile": "https://Stackoverflow.com/users/2108",
"pm_score": 1,
"selected": false,
"text": "<p>This advice is for symfony 1.0. It probably will work for later versions.</p>\n\n<p><strong>Within your sfAction class</str... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108/"
] | I always tend to forget these built-in **Symfony** functions for making links. | If your goal is to have user-friendly URLs throughout your application, use the following approach:
1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (using a pager):
```
recent_questions:
url: questions/recent/:page
param: { module: questions, action: recent, page: 1 }
```
2) Once the routing rule is set, use the `url_for()` helper in your template to format outgoing URLs.
```
<a href="<?php echo url_for('questions/recent?page=1') ?>">Recent Questions</a>
```
In this example, the following URL will be constructed: `http://myapp/questions/recent/1.html`.
3) Incoming URLs (requests) will be analyzed by the routing system, and if a pattern match is found in the routing rule configuration, the named wildcards (ie. the `:/page` portion of the URL) will become request parameters.
You can also use the `link_to()` helper to output a URL without using the HTML `<a>` tag. |
34,439 | <p>Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?</p>
<p>Or,</p>
<p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
| [
{
"answer_id": 34452,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 10,
"selected": true,
"text": "<p><strong>For many objects</strong>, you can use this code, replacing 'object' with the object you're interested in:</p>\n<pre c... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3587/"
] | Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?
Or,
if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? | **For many objects**, you can use this code, replacing 'object' with the object you're interested in:
```py
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
```
I discovered it at [diveintopython.net](https://web.archive.org/web/20180901124519/http://www.diveintopython.net/power_of_introspection/index.html) (now archived), that should provide some further details!
**If you get an `AttributeError`, you can use this instead**:
`getattr()` is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.
```py
import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
methodList = []
for method_name in dir(object):
try:
if callable(getattr(object, method_name)):
methodList.append(str(method_name))
except Exception:
methodList.append(str(method_name))
processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
for method in methodList:
try:
print(str(method.ljust(spacing)) + ' ' +
processFunc(str(getattr(object, method).__doc__)[0:90]))
except Exception:
print(method.ljust(spacing) + ' ' + ' getattr() failed')
get_methods(df['foo'])
``` |
34,486 | <p>I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?</p>
<pre><code>function loadPage(pagePath, displayElement)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(displayElement).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", pagePath, true);
xmlHttp.send(null);
}
</code></pre>
| [
{
"answer_id": 34538,
"author": "MattGrommes",
"author_id": 3098,
"author_profile": "https://Stackoverflow.com/users/3098",
"pm_score": 5,
"selected": true,
"text": "<p>I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the o... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?
```
function loadPage(pagePath, displayElement)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(displayElement).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", pagePath, true);
xmlHttp.send(null);
}
``` | I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page.
Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax. |
34,488 | <p>Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result?</p>
<p>for example</p>
<pre><code> select * from people where name = "Re0sless" limit 1
</code></pre>
<p>if there is only one record with that name? and what about if <code>name</code> was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal?</p>
| [
{
"answer_id": 34499,
"author": "Owen Fraser-Green",
"author_id": 3382,
"author_profile": "https://Stackoverflow.com/users/3382",
"pm_score": 0,
"selected": false,
"text": "<p>I believe the LIMIT is something done after the data set is found and the result set is being built up so I woul... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
] | Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result?
for example
```
select * from people where name = "Re0sless" limit 1
```
if there is only one record with that name? and what about if `name` was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal? | If the column has
**a unique index: no,** it's no faster
**a non-unique index: maybe,** because it will prevent sending any additional rows beyond the first matched, if any exist
**no index: sometimes**
* if 1 or more rows match the query, **yes**, because the full table scan will be halted after the first row is matched.
* if no rows match the query, **no**, because it will need to complete a full table scan |
34,490 | <p><a href="http://en.wikipedia.org/wiki/SHA-1" rel="noreferrer">SHA Hash functions</a></p>
| [
{
"answer_id": 34514,
"author": "devstopfix",
"author_id": 3366,
"author_profile": "https://Stackoverflow.com/users/3366",
"pm_score": 10,
"selected": true,
"text": "<pre><code>require 'digest/sha1'\nDigest::SHA1.hexdigest 'foo'\n</code></pre>\n"
},
{
"answer_id": 5269105,
"a... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] | [SHA Hash functions](http://en.wikipedia.org/wiki/SHA-1) | ```
require 'digest/sha1'
Digest::SHA1.hexdigest 'foo'
``` |
34,493 | <p>We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values.</p>
<p>Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook.</p>
<p>(The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.)</p>
<p><strong>Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move?</strong></p>
<p>I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable.</p>
<p>Be aware that the .Precedent, .Dependent, etc methods only track direct formulas.</p>
<p>(Also, rewriting the spreadsheets in <em>whatever</em> is not an option for us).</p>
<p>Thanks!</p>
| [
{
"answer_id": 34719,
"author": "sdfx",
"author_id": 3445,
"author_profile": "https://Stackoverflow.com/users/3445",
"pm_score": 4,
"selected": true,
"text": "<p>You could iterate over the entire Workbook using vba (i've included the code from @PabloG and @euro-micelli ):</p>\n\n<pre><co... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2230/"
] | We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values.
Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook.
(The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.)
**Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move?**
I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable.
Be aware that the .Precedent, .Dependent, etc methods only track direct formulas.
(Also, rewriting the spreadsheets in *whatever* is not an option for us).
Thanks! | You could iterate over the entire Workbook using vba (i've included the code from @PabloG and @euro-micelli ):
```
Sub iterateOverWorkbook()
For Each i In ThisWorkbook.Worksheets
Set rRng = i.UsedRange
For Each j In rRng
If (Not IsEmpty(j)) Then
If (j.HasFormula) Then
If InStr(oCell.Formula, "INDIRECT") Then
j.Value = Replace(j.Formula, "INDIRECT(D4)", "INDIRECT(C4)")
End If
End If
End If
Next j
Next i
End Sub
```
This example substitues every occurrence of "indirect(D4)" with "indirect(C4)". You can easily swap the replace-function with something more sophisticated, if you have more complicated indirect-functions. Performance is not that bad, even for bigger Workbooks. |
34,505 | <p>The MSDN documentation on <a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx" rel="noreferrer">Object.GetHashCode()</a> describes 3 contradicting rules for how the method should work. </p>
<ol>
<li>If two objects of the same type represent the same value, the hash function must return the same constant value for either object.</li>
<li>For the best performance, a hash function must generate a random distribution for all input.</li>
<li>The hash function must return exactly the same value regardless of any changes that are made to the object.</li>
</ol>
<p>Rules 1 & 3 are contradictory to me.</p>
<p>Does Object.GetHashCode() return a unique number based on the <strong>value</strong> of an object, or the <strong>reference</strong> to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.</p>
| [
{
"answer_id": 34511,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>By default it does it based on the reference to the object, but that means that it's the exact same object, so both would ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | The MSDN documentation on [Object.GetHashCode()](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx) describes 3 contradicting rules for how the method should work.
1. If two objects of the same type represent the same value, the hash function must return the same constant value for either object.
2. For the best performance, a hash function must generate a random distribution for all input.
3. The hash function must return exactly the same value regardless of any changes that are made to the object.
Rules 1 & 3 are contradictory to me.
Does Object.GetHashCode() return a unique number based on the **value** of an object, or the **reference** to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows. | >
> Rules 1 & 3 are contradictory to me.
>
>
>
To a certain extent, they are. The reason is simple: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. It is important that while objects are stored in a hash table, they retain their hash value.
To realize this it is often simplest to make hashable objects immutable, thus evading the whole problem. It is however sufficient to make only those fields immutable that determine the hash value.
Consider the following example:
```
struct Person {
public readonly string FirstName;
public readonly string Name;
public readonly DateTime Birthday;
public int ShoeSize;
}
```
People rarely change their birthday and most people never change their name (except when marrying). However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this:
```
public int GetHashCode() {
return FirstName.GetHashCode() ^ Name.GetHashCode() ^ Birthday.GetHashCode();
}
``` |
34,506 | <p>Is there anyway to have a sort of virtual static member in C++?</p>
<p>For example:</p>
<pre><code>class BaseClass {
public:
BaseClass(const string& name) : _name(name) {}
string GetName() const { return _name; }
virtual void UseClass() = 0;
private:
const string _name;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass("DerivedClass") {}
virtual void UseClass() { /* do something */ }
};
</code></pre>
<p>I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?</p>
<pre><code>class BaseClass {
public:
BaseClass() {}
virtual string GetName() const = 0;
virtual void UseClass() = 0;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
virtual string GetName() const { return _name; }
virtual void UseClass() { /* do something */ }
private:
static const string _name;
};
string DerivedClass::_name = "DerivedClass";
</code></pre>
<p>This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes.</p>
<p>Any idea?</p>
| [
{
"answer_id": 34591,
"author": "Hershi",
"author_id": 1596,
"author_profile": "https://Stackoverflow.com/users/1596",
"pm_score": 2,
"selected": false,
"text": "<p>It seems like the answer is in the question - the method you suggested seems to be the right direction to go, except that i... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3373/"
] | Is there anyway to have a sort of virtual static member in C++?
For example:
```
class BaseClass {
public:
BaseClass(const string& name) : _name(name) {}
string GetName() const { return _name; }
virtual void UseClass() = 0;
private:
const string _name;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass("DerivedClass") {}
virtual void UseClass() { /* do something */ }
};
```
I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?
```
class BaseClass {
public:
BaseClass() {}
virtual string GetName() const = 0;
virtual void UseClass() = 0;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
virtual string GetName() const { return _name; }
virtual void UseClass() { /* do something */ }
private:
static const string _name;
};
string DerivedClass::_name = "DerivedClass";
```
This solution does not satify me because I need reimplement the member \_name and its accessor GetName() in every class. In my case I have several members that follows \_name behavior and tenths of derived classes.
Any idea? | Here is one solution:
```
struct BaseData
{
const string my_word;
const int my_number;
};
class Base
{
public:
Base(const BaseData* apBaseData)
{
mpBaseData = apBaseData;
}
const string getMyWord()
{
return mpBaseData->my_word;
}
int getMyNumber()
{
return mpBaseData->my_number;
}
private:
const BaseData* mpBaseData;
};
class Derived : public Base
{
public:
Derived() : Base(&sBaseData)
{
}
private:
static BaseData sBaseData;
}
BaseData Derived::BaseData = { "Foo", 42 };
``` |
34,509 | <p>We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.</p>
<p>Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text.</p>
<p>While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.</p>
<p>For instance, sorting by a string record id gives something like:</p>
<pre><code>rec1
rec10
rec14
rec2
rec20
rec3
rec4
</code></pre>
<p>...and so on.</p>
<p>I want this to take account of the number, so:</p>
<pre><code>rec1
rec2
rec3
rec4
rec10
rec14
rec20
</code></pre>
<p>I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".</p>
<p>I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.</p>
<p>Does anyone know a way to quickly apply a natural sort in Sql server?</p>
<hr>
<p>We're using:</p>
<pre><code>ROW_NUMBER() over (order by {field name} asc)
</code></pre>
<p>And then we're paging by that.</p>
<p>We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.</p>
<hr>
<p>We have valid user input that follows different formats for different clients.</p>
<p>One might go rec1, rec2, rec3, ... rec100, rec101</p>
<p>While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301</p>
<p>When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.</p>
<p>These formats vary a lot, but are often mixtures of letters and numbers.</p>
<p>Sorting these in C# is easy - just break it up into <code>{ "grp", 20, "rec", 301 }</code> and then compare sequence values in turn.</p>
<p>However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.</p>
<p>SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.</p>
<p>@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.</p>
| [
{
"answer_id": 35382,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": -1,
"selected": false,
"text": "<p>I still don't understand (probably because of my poor English).</p>\n\n<p>You could try:</p>\n\n<pre><code>ROW_N... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.
Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text.
While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.
For instance, sorting by a string record id gives something like:
```
rec1
rec10
rec14
rec2
rec20
rec3
rec4
```
...and so on.
I want this to take account of the number, so:
```
rec1
rec2
rec3
rec4
rec10
rec14
rec20
```
I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".
I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.
Does anyone know a way to quickly apply a natural sort in Sql server?
---
We're using:
```
ROW_NUMBER() over (order by {field name} asc)
```
And then we're paging by that.
We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.
---
We have valid user input that follows different formats for different clients.
One might go rec1, rec2, rec3, ... rec100, rec101
While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301
When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.
These formats vary a lot, but are often mixtures of letters and numbers.
Sorting these in C# is easy - just break it up into `{ "grp", 20, "rec", 301 }` and then compare sequence values in turn.
However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.
SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.
@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values. | Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was *way* too slow.
Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics:
* will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter)
* properly sorts decimals, so 123.333 comes before 123.45
* because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code
* supports sorting a string with an arbitrary number of numbers within it
* will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter)
The code is here:
```
using System;
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
public class UDF
{
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)]
public static SqlString Naturalize(string val)
{
if (String.IsNullOrEmpty(val))
return val;
while(val.Contains(" "))
val = val.Replace(" ", " ");
const int maxLength = 1000;
const int padLength = 25;
bool inNumber = false;
bool isDecimal = false;
int numStart = 0;
int numLength = 0;
int length = val.Length < maxLength ? val.Length : maxLength;
//TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength
var sb = new StringBuilder();
for (var i = 0; i < length; i++)
{
int charCode = (int)val[i];
if (charCode >= 48 && charCode <= 57)
{
if (!inNumber)
{
numStart = i;
numLength = 1;
inNumber = true;
continue;
}
numLength++;
continue;
}
if (inNumber)
{
sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
inNumber = false;
}
isDecimal = (charCode == 46);
sb.Append(val[i]);
}
if (inNumber)
sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
var ret = sb.ToString();
if (ret.Length > maxLength)
return ret.Substring(0, maxLength);
return ret;
}
static string PadNumber(string num, bool isDecimal, int padLength)
{
return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');
}
}
```
To register this so that you can call it from SQL Server, run the following commands in Query Analyzer:
```
CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here
go
CREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000)
EXTERNAL NAME SqlServerClr.UDF.Naturalize
go
```
Then, you can use it like so:
```
select *
from MyTable
order by dbo.Naturalize(MyTextField)
```
**Note**: If you get an error in SQL Server along the lines of *Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option.*, follow the instructions [here](http://www.novicksoftware.com/TipsAndTricks/tip-sql-server-2005-enable-clr-programming.htm) to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration.
**Note2**: This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome!
**Edit:** Renamed the function to *Naturalize* instead of *NaturalSort*, since it does not do any actual sorting. |
34,510 | <p>When writing multithreaded applications, one of the most common problems experienced is race conditions.</p>
<p>My questions to the community are:</p>
<ul>
<li>What is the race condition?</li>
<li>How do you detect them?</li>
<li>How do you handle them?</li>
<li>Finally, how do you prevent them from occurring?</li>
</ul>
| [
{
"answer_id": 34537,
"author": "Steve Gury",
"author_id": 1578,
"author_profile": "https://Stackoverflow.com/users/1578",
"pm_score": 5,
"selected": false,
"text": "<p>A race condition is a kind of bug, that happens only with certain temporal conditions.</p>\n\n<p>Example:\nImagine you ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] | When writing multithreaded applications, one of the most common problems experienced is race conditions.
My questions to the community are:
* What is the race condition?
* How do you detect them?
* How do you handle them?
* Finally, how do you prevent them from occurring? | A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.
Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:
```
if (x == 5) // The "Check"
{
y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
// y will not be equal to 10.
}
```
The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.
In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:
```
// Obtain lock for x
if (x == 5)
{
y = x * 2; // Now, nothing can change x until the lock is released.
// Therefore y = 10
}
// release lock for x
``` |
34,516 | <p>Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?</p>
| [
{
"answer_id": 34530,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 2,
"selected": false,
"text": "<pre><code>/// <summary>\n///\n/// </summary>\n/// <param name=\"strFilePath\"></param>\n</code><... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code? | You can use XML style comments, and use tools to pull those comments out into API documentation.
Here is an example of the comment style:
```
/// <summary>
/// Authenticates a user based on a username and password.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <returns>
/// True, if authentication is successful, otherwise False.
/// </returns>
/// <remarks>
/// For use with local systems
/// </remarks>
public override bool Authenticate(string username, string password)
```
Some items to facilitate this are:
[GhostDoc](http://www.roland-weigelt.de/ghostdoc/), which give a single shortcut key to automatically generate comments for a class or method.
[Sandcastle](http://blogs.msdn.com/sandcastle/about.aspx), which generates MSDN style documentation from XML comments. |
34,518 | <p>How do you sort an array of strings <a href="http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/" rel="nofollow noreferrer">naturally</a> in different programming languages? Post your implementation and what language it is in in the answer.</p>
| [
{
"answer_id": 34528,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 3,
"selected": false,
"text": "<p><strong>JavaScript</strong></p>\n\n<pre><code>Array.prototype.alphanumSort = function(caseInsensitive) {\n for (var z = 0,... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585/"
] | How do you sort an array of strings [naturally](http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/) in different programming languages? Post your implementation and what language it is in in the answer. | **JavaScript**
```
Array.prototype.alphanumSort = function(caseInsensitive) {
for (var z = 0, t; t = this[z]; z++) {
this[z] = [], x = 0, y = -1, n = 0, i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >=48 && i <= 57));
if (m !== n) {
this[z][++y] = "";
n = m;
}
this[z][y] += j;
}
}
this.sort(function(a, b) {
for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else return (aa > bb) ? 1 : -1;
}
}
return a.length - b.length;
});
for (var z = 0; z < this.length; z++)
this[z] = this[z].join("");
}
```
[Source](http://my.opera.com/GreyWyvern/blog/show.dml/1671288) |
34,519 | <p>A semaphore is a programming concept that is frequently used to solve multi-threading problems. My question to the community: </p>
<p>What is a semaphore and how do you use it?</p>
| [
{
"answer_id": 34529,
"author": "Craig H",
"author_id": 2328,
"author_profile": "https://Stackoverflow.com/users/2328",
"pm_score": -1,
"selected": false,
"text": "<p>A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] | A semaphore is a programming concept that is frequently used to solve multi-threading problems. My question to the community:
What is a semaphore and how do you use it? | Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.
It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.
Here is a very pedagogic example in C# :-)
```cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace TheNightclub
{
public class Program
{
public static Semaphore Bouncer { get; set; }
public static void Main(string[] args)
{
// Create the semaphore with 3 slots, where 3 are available.
Bouncer = new Semaphore(3, 3);
// Open the nightclub.
OpenNightclub();
}
public static void OpenNightclub()
{
for (int i = 1; i <= 50; i++)
{
// Let each guest enter on an own thread.
Thread thread = new Thread(new ParameterizedThreadStart(Guest));
thread.Start(i);
}
}
public static void Guest(object args)
{
// Wait to enter the nightclub (a semaphore to be released).
Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
Bouncer.WaitOne();
// Do some dancing.
Console.WriteLine("Guest {0} is doing some dancing.", args);
Thread.Sleep(500);
// Let one guest out (release one semaphore).
Console.WriteLine("Guest {0} is leaving the nightclub.", args);
Bouncer.Release(1);
}
}
}
``` |
34,536 | <p>This most be the second most simple rollover effect, still I don't find any simple solution.</p>
<p><strong>Wanted:</strong> I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.</p>
<p>The following code works, but <em>is awful</em>. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.</p>
<pre><code><script type="text/javascript">
function switchTo(id) {
document.getElementById('slide1').style.display=(id==1)?'block':'none';
document.getElementById('slide2').style.display=(id==2)?'block':'none';
document.getElementById('slide3').style.display=(id==3)?'block':'none';
document.getElementById('slide4').style.display=(id==4)?'block':'none';
document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal';
document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal';
document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal';
document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';
}
</script>
<ul id="switches">
<li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li>
<li id="switch2" onmouseover="switchTo(2);">Second slide</li>
<li id="switch3" onmouseover="switchTo(3);">Third slide</li>
<li id="switch4" onmouseover="switchTo(4);">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
</code></pre>
| [
{
"answer_id": 34564,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>The only thing that's wrong with this code (at least to me) is that you're not using a loop to process all elements... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3377/"
] | This most be the second most simple rollover effect, still I don't find any simple solution.
**Wanted:** I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.
The following code works, but *is awful*. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.
```
<script type="text/javascript">
function switchTo(id) {
document.getElementById('slide1').style.display=(id==1)?'block':'none';
document.getElementById('slide2').style.display=(id==2)?'block':'none';
document.getElementById('slide3').style.display=(id==3)?'block':'none';
document.getElementById('slide4').style.display=(id==4)?'block':'none';
document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal';
document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal';
document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal';
document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';
}
</script>
<ul id="switches">
<li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li>
<li id="switch2" onmouseover="switchTo(2);">Second slide</li>
<li id="switch3" onmouseover="switchTo(3);">Third slide</li>
<li id="switch4" onmouseover="switchTo(4);">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
``` | Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide.
```js
$(document).ready(function() {
switches = $('#switches > li');
slides = $('#slides > div');
switches.each(function(idx) {
$(this).data('slide', slides.eq(idx));
}).hover(
function() {
switches.removeClass('active');
slides.removeClass('active');
$(this).addClass('active');
$(this).data('slide').addClass('active');
});
});
```
```css
#switches .active {
font-weight: bold;
}
#slides div {
display: none;
}
#slides div.active {
display: block;
}
```
```html
<html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="switch.js"></script>
</head>
<body>
<ul id="switches">
<li class="active">First slide</li>
<li>Second slide</li>
<li>Third slide</li>
<li>Fourth slide</li>
</ul>
<div id="slides">
<div class="active">Well well.</div>
<div>Oh no!</div>
<div>You again?</div>
<div>I'm gone!</div>
</div>
</body>
</html>
``` |
34,565 | <p>Additionally, how can I format it as a string padded with zeros?</p>
| [
{
"answer_id": 34582,
"author": "quackingduck",
"author_id": 3624,
"author_profile": "https://Stackoverflow.com/users/3624",
"pm_score": 7,
"selected": false,
"text": "<p>To generate the number call rand with the result of the expression \"10 to the power of 10\"</p>\n\n<pre><code>rand(1... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] | Additionally, how can I format it as a string padded with zeros? | To generate the number call rand with the result of the expression "10 to the power of 10"
```
rand(10 ** 10)
```
To pad the number with zeros you can use the string format operator
```
'%010d' % rand(10 ** 10)
```
or the `rjust` method of string
```
rand(10 ** 10).to_s.rjust(10,'0')
``` |
34,571 | <p>How do I use JUnit to test a class that has internal private methods, fields or nested classes?</p>
<p>It seems bad to change the access modifier for a method just to be able to run a test.</p>
| [
{
"answer_id": 34586,
"author": "Sir Rippov the Maple",
"author_id": 2822,
"author_profile": "https://Stackoverflow.com/users/2822",
"pm_score": 10,
"selected": false,
"text": "<p>The best way to test a private method is via another public method. If this cannot be done, then one of the ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3098/"
] | How do I use JUnit to test a class that has internal private methods, fields or nested classes?
It seems bad to change the access modifier for a method just to be able to run a test. | If you have somewhat of a legacy **Java** application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use [reflection](http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29).
Internally we're using helpers to get/set `private` and `private static` variables as well as invoke `private` and `private static` methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change `private static final` variables through reflection.
```
Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
```
And for fields:
```
Field field = TargetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
```
---
>
> **Notes:**
>
>
> 1. `TargetClass.getDeclaredMethod(methodName, argClasses)` lets you look into `private` methods. The same thing applies for
> `getDeclaredField`.
> 2. The `setAccessible(true)` is required to play around with privates.
>
>
> |
34,579 | <p>I've recently been working with a MySQL database, and using MySQL workbench to design the Database.</p>
<p>When I use the export to SQL function, so I can actually get the layout in to the Database, I get:</p>
<blockquote>
<p>"Error 1005: Cannot create table"</p>
</blockquote>
<p>This appears to be related to Foreign Keys in the create table statement.</p>
<p>Does anybody have a work around for this that doesn't involve taking the constraints out and putting them back in later? That's a less than ideal solution given the size of the database.</p>
| [
{
"answer_id": 34642,
"author": "joev",
"author_id": 3449,
"author_profile": "https://Stackoverflow.com/users/3449",
"pm_score": 1,
"selected": false,
"text": "<p>I ran into this situation recently when I attempted (in InnoDB tables) to make a foreign key reference to a column that had a... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655/"
] | I've recently been working with a MySQL database, and using MySQL workbench to design the Database.
When I use the export to SQL function, so I can actually get the layout in to the Database, I get:
>
> "Error 1005: Cannot create table"
>
>
>
This appears to be related to Foreign Keys in the create table statement.
Does anybody have a work around for this that doesn't involve taking the constraints out and putting them back in later? That's a less than ideal solution given the size of the database. | When you get this (and other errors out of the InnoDB engine) issue:
```
SHOW ENGINE INNODB STATUS;
```
It will give a more detailed reason why the operation couldn't be completed. Make sure to run that from something that'll allow you to scroll or copy the data, as the response is quite long. |
34,581 | <p>I expected the two <code>span</code> tags in the following sample to display next to each other, instead they display one below the other. If I set the <code>width</code> of the class <code>span</code>.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible <code>padding/margin</code> which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
border: none;
}
div.header {
width: 100%;
height: 80px;
vertical-align: top;
}
span.left {
height: 80px;
width: 50%;
display: inline-block;
background-color: pink;
}
span.right {
vertical-align: top;
display: inline-block;
text-align: right;
height: 80px;
width: 50%;
background-color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Test Page</title>
</head>
<body>
<div class='header'>
<span class='left'>Left Span 50% width</span>
<span class='right'>Right Span 50% width</span>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<hr />
<p>Thanks for the explanation. The <code>float:left</code> works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge</p>
| [
{
"answer_id": 34587,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 3,
"selected": true,
"text": "<pre><code>float: left;\n</code></pre>\n\n<p>Try adding that to span.left</p>\n\n<p>It will cause it to float to the lef... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3635/"
] | I expected the two `span` tags in the following sample to display next to each other, instead they display one below the other. If I set the `width` of the class `span`.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible `padding/margin` which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas?
```css
* {
margin: 0;
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
border: none;
}
div.header {
width: 100%;
height: 80px;
vertical-align: top;
}
span.left {
height: 80px;
width: 50%;
display: inline-block;
background-color: pink;
}
span.right {
vertical-align: top;
display: inline-block;
text-align: right;
height: 80px;
width: 50%;
background-color: red;
}
```
```html
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div class='header'>
<span class='left'>Left Span 50% width</span>
<span class='right'>Right Span 50% width</span>
</div>
</body>
</html>
```
---
Thanks for the explanation. The `float:left` works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge | ```
float: left;
```
Try adding that to span.left
It will cause it to float to the left (as suggested by the syntax).
---
I am not a CSS expert by any means so please don't take this as unarguable fact but I find that when something is floated, it makes no difference to the vertical position of things below it.
If you float the span.right to the right then add text beneath them you should get some interesting results, to stop these "interesting results" you can use "clear: left/right/both" which will cause the block with the clear styling to be under anything floated to the left/right/both. [W3Schools](http://w3schools.com/css/pr_class_clear.asp) have a page on this property too.
And welcome to Stackoverflow. |
34,588 | <p>When running my application I sometimes get an error about <code>too many files open</code>.</p>
<p>Running <code>ulimit -a</code> reports that the limit is 1024. How do I increase the limit above 1024? </p>
<p><strong>Edit</strong>
<code>ulimit -n 2048</code> results in a permission error.</p>
| [
{
"answer_id": 34645,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 8,
"selected": true,
"text": "<p>You could always try doing a <code>ulimit -n 2048</code>. This will only reset the limit for your current shell and the num... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
] | When running my application I sometimes get an error about `too many files open`.
Running `ulimit -a` reports that the limit is 1024. How do I increase the limit above 1024?
**Edit**
`ulimit -n 2048` results in a permission error. | You could always try doing a `ulimit -n 2048`. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit
Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.
```
set rlim_fd_max = 166384
set rlim_fd_cur = 8192
```
On OS X, this same data must be set in /etc/sysctl.conf.
```
kern.maxfilesperproc=166384
kern.maxfiles=8192
```
Under Linux, these settings are often in /etc/security/limits.conf.
There are two kinds of limits:
* **soft** limits are simply the currently enforced limits
* **hard** limits mark the maximum value which cannot be exceeded by setting a soft limit
Soft limits could be set by any user while hard limits are changeable only by root.
Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam\_limits.
There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default. |
34,595 | <p>What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that:</p>
<pre><code>function Hash(key)
return key mod PrimeNumber
end
</code></pre>
<p>(mod is the % operator in C and similar languages)</p>
<p>with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys?</p>
| [
{
"answer_id": 34606,
"author": "Einar",
"author_id": 2964,
"author_profile": "https://Stackoverflow.com/users/2964",
"pm_score": 2,
"selected": false,
"text": "<p>I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485/"
] | What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that:
```
function Hash(key)
return key mod PrimeNumber
end
```
(mod is the % operator in C and similar languages)
with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys? | For doing "normal" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I've ever used.
<http://www.azillionmonkeys.com/qed/hash.html>
If you care about cryptographically secure or anything else more advanced, then YMMV. If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you're looking for. |
34,623 | <p>Why would you do an automatic HTML post rather than a simple redirect?</p>
<p>Is this so developers can automatically generate a login form that posts directory to the remote server when the OpenID is known?</p>
<p>eg.</p>
<ol>
<li>User is not logged in and visits your login page.</li>
<li>You detect the user's openID from a cookie.</li>
<li>Form is generated that directly posts to remote OpenID server.</li>
<li>Remote server redirects user back to website.</li>
<li>Website logs in the user.</li>
</ol>
<p>If this is the case I can see the benefit. However this assumes that you keep the user's openID in a cookie when they log out.</p>
<p>I can find very little information on how this spec should be best implemented.</p>
<p>See HTML FORM Redirection in the official specs:</p>
<p><a href="http://openid.net/specs/openid-authentication-2_0.html#indirect_comm" rel="noreferrer">http://openid.net/specs/openid-authentication-2_0.html#indirect_comm</a></p>
<p>I found this out from looking at the <a href="http://openidenabled.com/php-openid/" rel="noreferrer">PHP OpenID Library</a> (version 2.1.1).</p>
<pre><code>// Redirect the user to the OpenID server for authentication.
// Store the token for this authentication so we can verify the
// response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript
// form to send a POST request to the server.
if ($auth_request->shouldSendRedirect()) {
$redirect_url = $auth_request->redirectURL(getTrustRoot(),
getReturnTo());
// If the redirect URL can't be built, display an error
// message.
if (Auth_OpenID::isFailure($redirect_url)) {
displayError("Could not redirect to server: " . $redirect_url->message);
} else {
// Send redirect.
header("Location: ".$redirect_url);
}
} else {
// Generate form markup and render it.
$form_id = 'openid_message';
$form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(),
false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated;
// otherwise, render the HTML.
if (Auth_OpenID::isFailure($form_html)) {
displayError("Could not redirect to server: " . $form_html->message);
} else {
print $form_html;
}
}
</code></pre>
| [
{
"answer_id": 35960,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": false,
"text": "<p>I can think of a couple of reasons:</p>\n\n<ul>\n<li>A modicum of security by obscurity - it's slightly more work to... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108/"
] | Why would you do an automatic HTML post rather than a simple redirect?
Is this so developers can automatically generate a login form that posts directory to the remote server when the OpenID is known?
eg.
1. User is not logged in and visits your login page.
2. You detect the user's openID from a cookie.
3. Form is generated that directly posts to remote OpenID server.
4. Remote server redirects user back to website.
5. Website logs in the user.
If this is the case I can see the benefit. However this assumes that you keep the user's openID in a cookie when they log out.
I can find very little information on how this spec should be best implemented.
See HTML FORM Redirection in the official specs:
<http://openid.net/specs/openid-authentication-2_0.html#indirect_comm>
I found this out from looking at the [PHP OpenID Library](http://openidenabled.com/php-openid/) (version 2.1.1).
```
// Redirect the user to the OpenID server for authentication.
// Store the token for this authentication so we can verify the
// response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript
// form to send a POST request to the server.
if ($auth_request->shouldSendRedirect()) {
$redirect_url = $auth_request->redirectURL(getTrustRoot(),
getReturnTo());
// If the redirect URL can't be built, display an error
// message.
if (Auth_OpenID::isFailure($redirect_url)) {
displayError("Could not redirect to server: " . $redirect_url->message);
} else {
// Send redirect.
header("Location: ".$redirect_url);
}
} else {
// Generate form markup and render it.
$form_id = 'openid_message';
$form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(),
false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated;
// otherwise, render the HTML.
if (Auth_OpenID::isFailure($form_html)) {
displayError("Could not redirect to server: " . $form_html->message);
} else {
print $form_html;
}
}
``` | The primary motivation was, as Mark Brackett says, the limits on payload size imposed by using redirects and GET. Some implementations are smart enough to only use POST when the message goes over a certain size, as there are certainly disadvantages to the POST technique. (Chief among them being the fact that your Back button doesn't work.) Other implementations, like the example code you cited, go for simplicity and consistency and leave out that conditional. |
34,655 | <p>I would like to have an <code>iframe</code> take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?</p>
<p>Are there any workarounds?</p>
| [
{
"answer_id": 34663,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "<p>This CSS snippet should remove the vertical scrollbar:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>b... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983/"
] | I would like to have an `iframe` take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?
Are there any workarounds? | This should set the `IFRAME` height to its content's height:
```
<script type="text/javascript">
the_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;
document.getElementById('the_iframe').height = the_height;
</script>
```
You may want to add `scrolling="no"` to your `IFRAME` to turn off the scrollbars.
*edit:* Oops, forgot to declare `the_height`. |
34,664 | <p>Has anyone found a useful solution to the DesignMode problem when developing controls?</p>
<p>The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE.</p>
<p>The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.</p>
<p>The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.</p>
<p>A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better!</p>
| [
{
"answer_id": 34696,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 2,
"selected": false,
"text": "<p>I've never been caught by this myself, but couldn't you just walk back up the Parent chain from the control to see if Desi... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862/"
] | Has anyone found a useful solution to the DesignMode problem when developing controls?
The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE.
The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.
The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.
A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better! | Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows:
```
System.ComponentModel.DesignMode property
System.ComponentModel.LicenseManager.UsageMode property
private string ServiceString()
{
if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null)
return "Present";
else
return "Not present";
}
public bool IsDesignerHosted
{
get
{
Control ctrl = this;
while(ctrl != null)
{
if((ctrl.Site != null) && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return false;
}
}
public static bool IsInDesignMode()
{
return System.Reflection.Assembly.GetExecutingAssembly()
.Location.Contains("VisualStudio"))
}
```
To try and get a hang on the three solutions proposed, I created a little test solution - with three projects:
* TestApp (winforms application),
* SubControl (dll)
* SubSubControl (dll)
I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form.
This screenshot shows the result when running.

This screenshot shows the result with the form open in Visual Studio:

Conclusion: It would appear that *without reflection* the only one that is reliable *within* the constructor is LicenseUsage, and the only one which is reliable *outside* the constructor is 'IsDesignedHosted' (by [BlueRaja](https://stackoverflow.com/questions/34664/designmode-with-controls/2693338#2693338) below)
PS: See ToolmakerSteve's comment below (which I haven't tested): "Note that [IsDesignerHosted](https://stackoverflow.com/a/2693338/199364) answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is [test LicenseManager in constructor and cache the result](https://stackoverflow.com/a/2849244/199364)." |
34,674 | <p>You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C.</p>
<pre><code>myObject.property = YES;
</code></pre>
<p>or</p>
<pre><code>[myObject setProperty:YES];
</code></pre>
<p>Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style?</p>
| [
{
"answer_id": 34688,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I've seen, there isn't a significant performance difference between the two. I'm reasonably certain that... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
] | You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C.
```
myObject.property = YES;
```
or
```
[myObject setProperty:YES];
```
Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style? | Dot notation for property access in Objective-C **is** a message send, just as bracket notation. That is, given this:
```
@interface Foo : NSObject
@property BOOL bar;
@end
Foo *foo = [[Foo alloc] init];
foo.bar = YES;
[foo setBar:YES];
```
The last two lines will compile exactly the same. The only thing that changes this is if a property has a `getter` and/or `setter` attribute specified; however, all it does is change what message gets sent, not whether a message is sent:
```
@interface MyView : NSView
@property(getter=isEmpty) BOOL empty;
@end
if ([someView isEmpty]) { /* ... */ }
if (someView.empty) { /* ... */ }
```
Both of the last two lines will compile identically. |
34,687 | <p>When I try to do any svn command and supply the <code>--username</code> and/or <code>--password</code> options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by <code>--username</code>. Neither <code>--no-auth-cache</code> nor <code>--non-interactive</code> have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt.</p>
<p>For example, logged in as user1:</p>
<pre><code># $ svn update --username 'user2' --password 'password'
# user1@domain.com's password:
</code></pre>
<p>Other options work correctly:</p>
<pre><code># $ svn --version --quiet
# 1.3.2
</code></pre>
<p>Why does it prompt me?<br>
And why is it asking for user1's password instead of user2's?<br>
I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords?<br>
Or is it something else entirely?</p>
<p>I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux).</p>
<hr>
<p>Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN:</p>
<pre><code># HOSTNAME=XXXXXX
# TERM=xterm
# SHELL=/bin/sh
# HISTSIZE=1000
# KDE_NO_IPV6=1
# SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX
# QTDIR=/usr/lib/qt-3.3
# QTINC=/usr/lib/qt-3.3/include
# SSH_TTY=/dev/pts/2
# USER=XXXXXX
# LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:
# KDEDIR=/usr
# MAIL=/var/spool/mail/XXXXXX
# PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin
# INPUTRC=/etc/inputrc
# PWD=/home/users/XXXXXX/my_repository
# KDE_IS_PRELINKED=1
# LANG=en_US.UTF-8
# SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
# SHLVL=1
# HOME=/home/users/XXXXXX
# LOGNAME=XXXXXX
# QTLIB=/usr/lib/qt-3.3/lib
# CVS_RSH=ssh
# SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22
# LESSOPEN=|/usr/bin/lesspipe.sh %s
# G_BROKEN_FILENAMES=1
# _=/bin/env
# OLDPWD=/home/users/XXXXXX
</code></pre>
| [
{
"answer_id": 34755,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 0,
"selected": false,
"text": "<p>Best I can give you is a \"works for me\" on SVN 1.5. You may try adding <code>--no-auth-cache</code> to your <code>... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3625/"
] | When I try to do any svn command and supply the `--username` and/or `--password` options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by `--username`. Neither `--no-auth-cache` nor `--non-interactive` have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt.
For example, logged in as user1:
```
# $ svn update --username 'user2' --password 'password'
# user1@domain.com's password:
```
Other options work correctly:
```
# $ svn --version --quiet
# 1.3.2
```
Why does it prompt me?
And why is it asking for user1's password instead of user2's?
I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords?
Or is it something else entirely?
I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux).
---
Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN:
```
# HOSTNAME=XXXXXX
# TERM=xterm
# SHELL=/bin/sh
# HISTSIZE=1000
# KDE_NO_IPV6=1
# SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX
# QTDIR=/usr/lib/qt-3.3
# QTINC=/usr/lib/qt-3.3/include
# SSH_TTY=/dev/pts/2
# USER=XXXXXX
# LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:
# KDEDIR=/usr
# MAIL=/var/spool/mail/XXXXXX
# PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin
# INPUTRC=/etc/inputrc
# PWD=/home/users/XXXXXX/my_repository
# KDE_IS_PRELINKED=1
# LANG=en_US.UTF-8
# SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
# SHLVL=1
# HOME=/home/users/XXXXXX
# LOGNAME=XXXXXX
# QTLIB=/usr/lib/qt-3.3/lib
# CVS_RSH=ssh
# SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22
# LESSOPEN=|/usr/bin/lesspipe.sh %s
# G_BROKEN_FILENAMES=1
# _=/bin/env
# OLDPWD=/home/users/XXXXXX
``` | The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout.
IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using ?
If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password. |
34,708 | <p>A few months back I was tasked with implementing a unique and random code for our web application. The code would have to be user friendly and as small as possible, but still be essentially random (so users couldn't easily predict the next code in the sequence).</p>
<p>It ended up generating values that looked something like this:</p>
<pre><code>Af3nT5Xf2
</code></pre>
<p>Unfortunately, I was never satisfied with the implementation. Guid's were out of the question, they were simply too big and difficult for users to type in. I was hoping for something more along the lines of 4 or 5 characters/digits, but our particular implementation would generate noticeably patterned sequences if we encoded to less than 9 characters.</p>
<p>Here's what we ended up doing:</p>
<p>We pulled a unique sequential 32bit id from the database. We then inserted it into the center bits of a 64bit RANDOM integer. We created a lookup table of easily typed and recognized characters (A-Z, a-z, 2-9 skipping easily confused characters such as L,l,1,O,0, etc.). Finally, we used that lookup table to base-54 encode the 64-bit integer. The high bits were random, the low bits were random, but the center bits were sequential.</p>
<p>The final result was a code that was much smaller than a guid and looked random, even though it absolutely wasn't.</p>
<p>I was never satisfied with this particular implementation. What would you guys have done?</p>
| [
{
"answer_id": 34722,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 2,
"selected": false,
"text": "<p>In C#, I have used the '<a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx\"... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] | A few months back I was tasked with implementing a unique and random code for our web application. The code would have to be user friendly and as small as possible, but still be essentially random (so users couldn't easily predict the next code in the sequence).
It ended up generating values that looked something like this:
```
Af3nT5Xf2
```
Unfortunately, I was never satisfied with the implementation. Guid's were out of the question, they were simply too big and difficult for users to type in. I was hoping for something more along the lines of 4 or 5 characters/digits, but our particular implementation would generate noticeably patterned sequences if we encoded to less than 9 characters.
Here's what we ended up doing:
We pulled a unique sequential 32bit id from the database. We then inserted it into the center bits of a 64bit RANDOM integer. We created a lookup table of easily typed and recognized characters (A-Z, a-z, 2-9 skipping easily confused characters such as L,l,1,O,0, etc.). Finally, we used that lookup table to base-54 encode the 64-bit integer. The high bits were random, the low bits were random, but the center bits were sequential.
The final result was a code that was much smaller than a guid and looked random, even though it absolutely wasn't.
I was never satisfied with this particular implementation. What would you guys have done? | In .NET you can use the RNGCryptoServiceProvider method GetBytes() which will "fill an array of bytes with a cryptographically strong sequence of random values" (from ms documentation).
```
byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
```
You can increase the lengh of the byte array and pluck out the character values you want to allow. |
34,712 | <p>I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style.</p>
<p>Any ideas about how to detect which mode the user is in and re-format the forms on the fly?</p>
<hr>
<p>Post Answer Edit:</p>
<p>Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function.</p>
<p>I'm doing the following:</p>
<p><strong>Function Declaration:</strong>
<pre><code> Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32
</pre></code></p>
<p><strong><em>Code Body:</em></strong>
<pre><code>
Dim stringThemeName As New System.Text.StringBuilder(260)
Dim stringColorName As New System.Text.StringBuilder(260)
Dim stringSizeName As New System.Text.StringBuilder(260)</p>
<p>GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260)
MsgBox(stringThemeName.ToString)
</pre></code></p>
<p>The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue.</p>
| [
{
"answer_id": 34724,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>There's the <a href=\"http://msdn.microsoft.com/en-us/library/bb759813%28VS.85%29.aspx\" rel=\"nofollow noreferrer\... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3648/"
] | I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style.
Any ideas about how to detect which mode the user is in and re-format the forms on the fly?
---
Post Answer Edit:
Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function.
I'm doing the following:
**Function Declaration:**
```
Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32
```
***Code Body:***
```
Dim stringThemeName As New System.Text.StringBuilder(260)
Dim stringColorName As New System.Text.StringBuilder(260)
Dim stringSizeName As New System.Text.StringBuilder(260)
```
GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260)
MsgBox(stringThemeName.ToString)
The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue. | Try using a combination of [GetCurrentThemeName](http://www.pinvoke.net/default.aspx/uxtheme/GetCurrentThemeName.html) ([MSDN Page](http://msdn.microsoft.com/en-us/library/bb773365%28VS.85%29.aspx)) and [DwmIsCompositionEnabled](http://msdn.microsoft.com/en-us/library/aa969518%28VS.85%29.aspx)
I linked the first to PInvoke so you can just drop it in your code, and for the second one you can use the code provided in the MSDN comment:
```
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
```
See what results you get out of those two functions; they should be enough to determine when you want to use a different theme! |
34,732 | <p>How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library).</p>
<p>I'm using gcc 4.0.2, if that makes a difference.</p>
| [
{
"answer_id": 34758,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the <code>nm -g</code> tool from the binutils toolchain. However, their source is not always readily av... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
] | How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library).
I'm using gcc 4.0.2, if that makes a difference. | The standard tool for listing symbols is `nm`, you can use it simply like this:
```
nm -gD yourLib.so
```
If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled).
```
nm -gDC yourLib.so
```
If your .so file is in elf format, you have two options:
Either `objdump` (`-C` is also useful for demangling C++):
```
$ objdump -TC libz.so
libz.so: file format elf64-x86-64
DYNAMIC SYMBOL TABLE:
0000000000002010 l d .init 0000000000000000 .init
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location
0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable
```
Or use `readelf`:
```
$ readelf -Ws libz.so
Symbol table '.dynsym' contains 112 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000002010 0 SECTION LOCAL DEFAULT 10
2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14)
3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14)
4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
``` |
34,768 | <p>I have recently installed .net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set:</p>
<pre><code><form id="theForm" runat="server" action="post.aspx">
</code></pre>
<p>I received this error.<br>
Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set_Action(System.String)'.<br>
If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this?</p>
| [
{
"answer_id": 34776,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know the specific solution, but HtmlForm.set_Action() is a function the compiler creates that acts as the ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2903/"
] | I have recently installed .net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set:
```
<form id="theForm" runat="server" action="post.aspx">
```
I received this error.
Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set\_Action(System.String)'.
If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this? | [.NET 3.5 SP1 tries to use the action="" attribute](http://johnsheehan.me/blog/less-code-is-fun-aspnet-35-sp1-removes-need-for-control-adapter-when-using-url-rewriting/) (.NET 3.5 RTM did not). So, when you deploy, your code is attempting to set the HtmlForm.Action property and failing, as the System.Web.dll on the deploy target is RTM and does not have a setter on the property. |
34,784 | <p>What is a good setup for .hgignore file when working with Visual Studio 2008?</p>
<p>I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it.</p>
<p>I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include?</p>
<p>Thanks!</p>
<p>p.s.: at the moment I do the following : ignore all .pdb files and all obj folders.</p>
<pre><code># regexp syntax.
syntax: glob
*.pdb
syntax: regexp
/obj/
</code></pre>
| [
{
"answer_id": 34805,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 5,
"selected": false,
"text": "<p>This is specific to a C# project, but I ignore these files/directories:</p>\n\n<blockquote>\n <ul>\n <li><code>*... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
] | What is a good setup for .hgignore file when working with Visual Studio 2008?
I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it.
I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include?
Thanks!
p.s.: at the moment I do the following : ignore all .pdb files and all obj folders.
```
# regexp syntax.
syntax: glob
*.pdb
syntax: regexp
/obj/
``` | Here's my standard .hgignore file for use with VS2008 that was originally modified from a Git ignore file:
```
# Ignore file for Visual Studio 2008
# use glob syntax
syntax: glob
# Ignore Visual Studio 2008 files
*.obj
*.exe
*.pdb
*.user
*.aps
*.pch
*.vspscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.cache
*.ilk
*.log
*.lib
*.sbr
*.scc
[Bb]in
[Dd]ebug*/
obj/
[Rr]elease*/
_ReSharper*/
[Tt]est[Rr]esult*
[Bb]uild[Ll]og.*
*.[Pp]ublish.xml
``` |
34,790 | <p>The <code>datepicker</code> function only works on the first input box that is created.</p>
<p>I'm trying to duplicate a datepicker by cloning the <code>div</code> that is containing it.</p>
<pre><code><a href="#" id="dupMe">click</a>
<div id="template">
input-text <input type="text" value="text1" id="txt" />
date time picker <input type="text" id="example" value="(add date)" />
</div>
</code></pre>
<p>To initialize the datepicker, according to the <a href="http://docs.jquery.com/UI/Datepicker" rel="nofollow noreferrer">jQuery UI documentation</a> I only have to do <code>$('#example').datepicker();</code> and it does work, but only on the first datepicker that is created.</p>
<p>The code to duplicate the <code>div</code> is the following:</p>
<pre><code>$("a#dupMe").click(function(event){
event.preventDefault();
i++;
var a = $("#template")
.clone(true)
.insertBefore("#template")
.hide()
.fadeIn(1000);
a.find("input#txt").attr('value', i);
a.find("input#example").datepicker();
});
</code></pre>
<p>The strangest thing is that on the <code>document.ready</code> I have:</p>
<pre><code>$('#template #example').datepicker();
$("#template #txt").click(function() { alert($(this).val()); });
</code></pre>
<p>and if I click on the <code>#txt</code> it always works.</p>
| [
{
"answer_id": 34807,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 4,
"selected": false,
"text": "<p>I use a CSS class instead:</p>\n\n<pre><code><input type=\"text\" id=\"BeginDate\" class=\"calendar\" />\n<input ty... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842864/"
] | The `datepicker` function only works on the first input box that is created.
I'm trying to duplicate a datepicker by cloning the `div` that is containing it.
```
<a href="#" id="dupMe">click</a>
<div id="template">
input-text <input type="text" value="text1" id="txt" />
date time picker <input type="text" id="example" value="(add date)" />
</div>
```
To initialize the datepicker, according to the [jQuery UI documentation](http://docs.jquery.com/UI/Datepicker) I only have to do `$('#example').datepicker();` and it does work, but only on the first datepicker that is created.
The code to duplicate the `div` is the following:
```
$("a#dupMe").click(function(event){
event.preventDefault();
i++;
var a = $("#template")
.clone(true)
.insertBefore("#template")
.hide()
.fadeIn(1000);
a.find("input#txt").attr('value', i);
a.find("input#example").datepicker();
});
```
The strangest thing is that on the `document.ready` I have:
```
$('#template #example').datepicker();
$("#template #txt").click(function() { alert($(this).val()); });
```
and if I click on the `#txt` it always works. | I'd recommend just using a common class name as well. However, if you're against this for some reason, you could also write a function to create date pickers for all text boxes in your template `div` (to be called after each duplication). Something like:
```
function makeDatePickers() {
$("#template input[type=text]").datepicker();
}
``` |
34,798 | <p>I have a gridview that is within an updatepanel for a modal popup I have on a page.<br>
The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying.</p>
<p>Does any one know what I am missing. </p>
<p><strong>Edit:</strong> I entered a better solution at the bottom</p>
| [
{
"answer_id": 34875,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<p>do you have ChildrenAsTriggers=\"false\" on the UpdatePanel?</p>\n\n<p>Are there any javascript errors on the page?<... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | I have a gridview that is within an updatepanel for a modal popup I have on a page.
The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying.
Does any one know what I am missing.
**Edit:** I entered a better solution at the bottom | Several months later this problem was fixed. The project I was working in was a previous v1.1 which was converted with 2.0. However, in the web.config this line remained:
```
<xhtmlConformance mode="Legacy"/>
```
When it was commented out all of the bugs that we seemed to have with the ajax control toolkit disappeared |
34,802 | <p>I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this?</p>
| [
{
"answer_id": 34885,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 3,
"selected": true,
"text": "<p>First, I'd create a simple DependencyObject class to hold your collection: </p>\n\n<pre><code>class YourCollectionT... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this? | First, I'd create a simple DependencyObject class to hold your collection:
```
class YourCollectionType : DependencyObject {
[PROPERTY DEPENDENCY OF ObservableCollection<YourType> NAMED: BoundList]
}
```
Then, on your ValidationRule-derived class, create a property:
```
YourCollectionType ListToCheck { get; set; }
```
Then, in the XAML, do this:
```
<Binding.ValidationRules>
<YourValidationRule>
<YourValidationRule.ListToCheck>
<YourCollectionType BoundList="{Binding Path=TheCollectionYouWantToCheck}" />
</YourValidationRule.ListToCheck>
</YourValidationRule>
</Binding.ValidationRules>
```
Then in your validation, look at ListToCheck's BoundList property's collection for the item that you're validating against. If it's in there, obviously return a false validation result. If it's not, return true. |
34,806 | <p>I have a little dilemma that maybe you can help me sort out. </p>
<p>I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not. </p>
<p>What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned. </p>
<p>Having said that, my problem has nothing to do with it, it's a generic class design issue. </p>
<p>I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description. </p>
<p>I can think of the following scenarios: </p>
<ol>
<li><p>Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer. </p></li>
<li><p>Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it. </p></li>
<li><p>Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation. </p></li>
</ol>
<p>I think the best option is the third one... </p>
<p>How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think... </p>
| [
{
"answer_id": 34832,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": true,
"text": "<p>I feel the best combination of DRYness and forcing the contract is as follows (in pseudocode):</p>\n\n<pre><code>cla... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | I have a little dilemma that maybe you can help me sort out.
I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not.
What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned.
Having said that, my problem has nothing to do with it, it's a generic class design issue.
I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description.
I can think of the following scenarios:
1. Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer.
2. Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it.
3. Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation.
I think the best option is the third one...
How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think... | I feel the best combination of DRYness and forcing the contract is as follows (in pseudocode):
```
class Base {
public final constructor(name) {
constructor(name, null)
end
public abstract constructor(name, description);
}
```
or, alternatively:
```
class Base {
public abstract constructor(name);
public final constructor(name, description) {
constructor(name)
this.set_description(description)
}
private final set_description(description) {
...
}
}
```
There's a rule in Java that supports this decision: "never call non-final methods from a constructor." |
34,848 | <p>When using a <code>Zend_Form</code>, the only way to validate that an input is not left blank is to do</p>
<pre><code>$element->setRequired(true);
</code></pre>
<p>If this is not set and the element is blank, it appears to me that validation is not run on the element.</p>
<p>If I do use <code>setRequired()</code>, the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the <code>Zend_Validate_NotEmpty</code> class, but this is a bit hacky.</p>
<p>I would ideally like to be able to use my own class (derived from <code>Zend_Validate_NotEmpty</code>) to perform the not empty check.</p>
| [
{
"answer_id": 34862,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 1,
"selected": false,
"text": "<p>Change the <a href=\"http://framework.zend.com/manual/en/zend.form.forms.html#zend.form.forms.validation.errors\" rel=\"nofoll... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349865/"
] | When using a `Zend_Form`, the only way to validate that an input is not left blank is to do
```
$element->setRequired(true);
```
If this is not set and the element is blank, it appears to me that validation is not run on the element.
If I do use `setRequired()`, the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the `Zend_Validate_NotEmpty` class, but this is a bit hacky.
I would ideally like to be able to use my own class (derived from `Zend_Validate_NotEmpty`) to perform the not empty check. | I did it this way (ZF 1.5):
```
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Full Name: ')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator($MyNotEmpty);
```
so, the addValidator() is the interesting part. The Message is set in an "Errormessage File" (to bundle all custom messages in one file):
```
$MyNotEmpty = new Zend_Validate_NotEmpty();
$MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY);
```
hope this helps... |
34,852 | <p>I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list:</p>
<pre><code>public IList<Customer> GetCustomerByFirstName(string customerFirstName)
{
return _session.CreateCriteria(typeof(Customer))
.Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName))
.List<Customer>();
}
</code></pre>
<p>I am calling <code>Session.Flush()</code> at the end of the <code>HttpRequest</code>, and I get a <code>HibernateAdoException</code>. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the <code>flush</code>, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing?</p>
<hr>
<p>Here's the code from the exception:</p>
<pre><code>[SQL: UPDATE CUSTOMER SET first_name = ?, last_name = ?, strategy_code_1 = ?, strategy_code_2 = ?, strategy_code_3 = ?, dts_import = ?, account_cycle_code = ?, bucket = ?, collector_code = ?, days_delinquent_count = ?, external_status_code = ?, principal_balance_amount = ?, total_min_pay_due = ?, current_balance = ?, amount_delinquent = ?, current_min_pay_due = ?, bucket_1 = ?, bucket_2 = ?, bucket_3 = ?, bucket_4 = ?, bucket_5 = ?, bucket_6 = ?, bucket_7 = ? WHERE customer_account_id = ?]
</code></pre>
<p>No parameters are showing as being passed.</p>
| [
{
"answer_id": 34965,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 5,
"selected": true,
"text": "<p>I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] | I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list:
```
public IList<Customer> GetCustomerByFirstName(string customerFirstName)
{
return _session.CreateCriteria(typeof(Customer))
.Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName))
.List<Customer>();
}
```
I am calling `Session.Flush()` at the end of the `HttpRequest`, and I get a `HibernateAdoException`. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the `flush`, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing?
---
Here's the code from the exception:
```
[SQL: UPDATE CUSTOMER SET first_name = ?, last_name = ?, strategy_code_1 = ?, strategy_code_2 = ?, strategy_code_3 = ?, dts_import = ?, account_cycle_code = ?, bucket = ?, collector_code = ?, days_delinquent_count = ?, external_status_code = ?, principal_balance_amount = ?, total_min_pay_due = ?, current_balance = ?, amount_delinquent = ?, current_min_pay_due = ?, bucket_1 = ?, bucket_2 = ?, bucket_3 = ?, bucket_4 = ?, bucket_5 = ?, bucket_6 = ?, bucket_7 = ? WHERE customer_account_id = ?]
```
No parameters are showing as being passed. | I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). May you please paste your model and mapping? |
34,868 | <p>In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the <a href="http://php.net/date" rel="noreferrer"><code>date()</code></a> function, the manual reads:</p>
<pre><code>string date ( string $format [, int $timestamp = time() ] )
</code></pre>
<p>Where <code>$timestamp</code> is an optional parameter, and when left blank it defaults to the <a href="http://php.net/time" rel="noreferrer"><code>time()</code></a> function's return value.</p>
<p>How do you go about creating optional parameters like this when defining a custom function in PHP?</p>
| [
{
"answer_id": 34869,
"author": "Jeff Winkworth",
"author_id": 1306,
"author_profile": "https://Stackoverflow.com/users/1306",
"pm_score": 9,
"selected": true,
"text": "<p>Much like the manual, use an equals (<code>=</code>) sign in your definition of the parameters:</p>\n\n<pre><code>fu... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2687/"
] | In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the [`date()`](http://php.net/date) function, the manual reads:
```
string date ( string $format [, int $timestamp = time() ] )
```
Where `$timestamp` is an optional parameter, and when left blank it defaults to the [`time()`](http://php.net/time) function's return value.
How do you go about creating optional parameters like this when defining a custom function in PHP? | Much like the manual, use an equals (`=`) sign in your definition of the parameters:
```
function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}
``` |
34,879 | <p>I need debug some old code that uses a Hashtable to store response from various threads.</p>
<p>I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.</p>
<p>How can this be done?</p>
| [
{
"answer_id": 34884,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 6,
"selected": true,
"text": "<pre><code>foreach(string key in hashTable.Keys)\n{\n Console.WriteLine(String.Format(\"{0}: {1}\", key, hashTable[key... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] | I need debug some old code that uses a Hashtable to store response from various threads.
I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.
How can this be done? | ```
foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
``` |
34,913 | <p>I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out.</p>
<p>As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days.</p>
<pre><code>╔════════╦═════════════╦════════╦══════╗
║ SiteId ║ VisitorType ║ Last30 ║ Total║
╠════════╬═════════════╬════════╬══════╣
║ 1 ║ 1 ║ 10 ║ 100 ║
║ 1 ║ 2 ║ 40 ║ 140 ║
║ 2 ║ 1 ║ 20 ║ 180 ║
╚════════╩═════════════╩════════╩══════╝
</code></pre>
<p>In SQL, I can easily get the counts for SiteID 1 with the following:</p>
<pre><code>SELECT SiteId,
SUM(Last30) AS Last30Sum
FROM Sites
WHERE SiteId = 1
GROUP BY SiteId
</code></pre>
<p>and should get a row like...</p>
<pre><code>╔════════╦════════════╗
║ SiteId ║ Last30Total║
╠════════╬════════════╣
║ 1 ║ 50 ║
╚════════╩════════════╝
</code></pre>
<p>However I'm not sure how to get this result using Linq. I've tried:</p>
<pre><code>var statsRecord = from ss in db.SiteStats
where ss.SiteId == siteId
group ss by ss.SiteId into ss
select ss;
</code></pre>
<p>but I'm not able to get back the total with something like <code>statsRecord.Last30</code></p>
<p>Can someone please let me know where I'm going wrong? Any help is appreciated.</p>
| [
{
"answer_id": 34951,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 2,
"selected": false,
"text": "<p>Easiest way for me to illustrate is using in-memory objects so it's clear what's happening. LINQ to SQL should be abl... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
] | I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out.
As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days.
```
╔════════╦═════════════╦════════╦══════╗
║ SiteId ║ VisitorType ║ Last30 ║ Total║
╠════════╬═════════════╬════════╬══════╣
║ 1 ║ 1 ║ 10 ║ 100 ║
║ 1 ║ 2 ║ 40 ║ 140 ║
║ 2 ║ 1 ║ 20 ║ 180 ║
╚════════╩═════════════╩════════╩══════╝
```
In SQL, I can easily get the counts for SiteID 1 with the following:
```
SELECT SiteId,
SUM(Last30) AS Last30Sum
FROM Sites
WHERE SiteId = 1
GROUP BY SiteId
```
and should get a row like...
```
╔════════╦════════════╗
║ SiteId ║ Last30Total║
╠════════╬════════════╣
║ 1 ║ 50 ║
╚════════╩════════════╝
```
However I'm not sure how to get this result using Linq. I've tried:
```
var statsRecord = from ss in db.SiteStats
where ss.SiteId == siteId
group ss by ss.SiteId into ss
select ss;
```
but I'm not able to get back the total with something like `statsRecord.Last30`
Can someone please let me know where I'm going wrong? Any help is appreciated. | Actually, although Thomas' code will work, it is more succint to use a lambda expression:
```
var totals =
from s in sites
group s by s.SiteID into grouped
select new
{
SiteID = grouped.Key,
Last30Sum = grouped.Sum( s => s.Last30 )
};
```
which uses the Sum extension method without the need for a nested LINQ operation.
as per the LINQ 101 examples - <http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped> |
34,914 | <p>The manual page for <code>XML::Parser::Style::Objects</code> is horrible. A simple hello world style program would really be helpful.</p>
<p>I really wanted to do something like this: (not real code of course)</p>
<pre><code>use XML::Parser;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
$tree->doSomething();
MyNode::doSomething() {
my $self = shift;
print "This is a normal node";
for $kid ($self->Kids)
{
$kid->doSomething();
}
}
MyNode::special::doSomething() {
my $self = shift;
print "This is a special node";
}
</code></pre>
| [
{
"answer_id": 35450,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "<p>When ever I need to do something similar, usually I end up using <a href=\"http://search.cpan.org/~ebohlman/XML-Parser-EasyTree-... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657/"
] | The manual page for `XML::Parser::Style::Objects` is horrible. A simple hello world style program would really be helpful.
I really wanted to do something like this: (not real code of course)
```
use XML::Parser;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
$tree->doSomething();
MyNode::doSomething() {
my $self = shift;
print "This is a normal node";
for $kid ($self->Kids)
{
$kid->doSomething();
}
}
MyNode::special::doSomething() {
my $self = shift;
print "This is a special node";
}
``` | In all cases here is actual code that runs ... doesn't mean much but produces output and hopefully can get you started ...
```
use XML::Parser;
package MyNode::inner;
sub doSomething {
my $self = shift;
print "This is an inner node containing : ";
print $self->{Kids}->[0]->{Text};
print "\n";
}
package MyNode::Characters;
sub doSomething {}
package MyNode::foo;
sub doSomething {
my $self = shift;
print "This is an external node\n";
for $kid (@ { $self->{Kids} }) {
$kid->doSomething();
}
}
package main;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
for (@$tree) {
$_->doSomething();
}
```
with foo.xml
```
<foo> <inner>some text</inner> <inner>something else</inner></foo>
```
which outputs
```
>perl -w "tree.pl"
This is an external node
This is an inner node containing : some text
This is an inner node containing : something else
```
Hope that helps. |
34,920 | <p>What is the best way to create a lock on a file in Perl?</p>
<p>Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file?</p>
| [
{
"answer_id": 34928,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <a href=\"http://perldoc.perl.org/functions/flock.html\" rel=\"nofollow noreferrer\">flock</a> Luke. </p>\n\n<p><stron... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539/"
] | What is the best way to create a lock on a file in Perl?
Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file? | If you end up using flock, here's some code to do it:
```
use Fcntl ':flock'; # Import LOCK_* constants
# We will use this file path in error messages and function calls.
# Don't type it out more than once in your code. Use a variable.
my $file = '/path/to/some/file';
# Open the file for appending. Note the file path is quoted
# in the error message. This helps debug situations where you
# have a stray space at the start or end of the path.
open(my $fh, '>>', $file) or die "Could not open '$file' - $!";
# Get exclusive lock (will block until it does)
flock($fh, LOCK_EX) or die "Could not lock '$file' - $!";
# Do something with the file here...
# Do NOT use flock() to unlock the file if you wrote to the
# file in the "do something" section above. This could create
# a race condition. The close() call below will unlock the
# file for you, but only after writing any buffered data.
# In a world of buffered i/o, some or all of your data may not
# be written until close() completes. Always, always, ALWAYS
# check the return value of close() if you wrote to the file!
close($fh) or die "Could not write '$file' - $!";
```
Some useful links:
* [PerlMonks file locking tutorial](http://www.perlmonks.org/?node_id=7058) (somewhat old)
* [`flock()` documentation](http://perldoc.perl.org/functions/flock.html)
In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics). |
34,925 | <p>I've seen quite a few posts on changes in .NET 3.5 SP1, but stumbled into one that I've yet to see documentation for yesterday. I had code working just fine on my machine, from VS, msbuild command line, everything, but it failed on the build server (running .NET 3.5 RTM).</p>
<pre><code>[XmlRoot("foo")]
public class Foo
{
static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string xml = @"<foo name='ack' />";
using (StringReader sr = new StringReader(xml))
{
Foo foo = serializer.Deserialize(sr) as Foo;
}
}
[XmlAttribute("name")]
public string Name { get; set; }
public Foo Bar { get; private set; }
}
</code></pre>
<p>In SP1, the above code runs just fine. In RTM, you get an InvalidOperationException:</p>
<blockquote>
<p>Unable to generate a temporary class (result=1).
error CS0200: Property or indexer 'ConsoleApplication2.Foo.Bar' cannot be assign to -- it is read only</p>
</blockquote>
<p>Of course, all that's needed to make it run under RTM is adding [XmlIgnore] to the Bar property.</p>
<p>My google fu is apparently not up to finding documentation of these kinds of changes. Is there a change list anywhere that lists this change (and similar under-the-hood changes that might jump up and shout "gotcha")? Is this a bug or a feature? </p>
<p><strong>EDIT</strong>: In SP1, if I added a <code><Bar /></code> element, or set [XmlElement] for the Bar property, it won't get deserialized. It doesn't fail pre-SP1 when it tries to deserialize--it throws an exception when the XmlSerializer is constructed.</p>
<p>This makes me lean more toward it being a bug, especially if I set an [XmlElement] attribute for Foo.Bar. If it's unable to do what I ask it to do, it should be throwing an exception instead of silently ignoring Foo.Bar. Other invalid combinations/settings of XML serialization attributes result in an exception.</p>
<p><strong>EDIT</strong>: Thank you, TonyB, I'd not known about setting the temp files location. For those that come across similar issues in the future, you do need an additional config flag:</p>
<pre><code><system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="1" />
</switches>
</system.diagnostics>
<system.xml.serialization>
<xmlSerializer tempFilesLocation="c:\\foo"/>
</system.xml.serialization>
</code></pre>
<p>Even with setting an [XmlElement] attribute on the Bar property, no mention was made of it in the generated serialization assembly--which fairly firmly puts this in the realm of a silently swallowed error (aka, a bug). Either that or the designers have decided [XmlIgnore] is no longer necessary for properties that can't be set--and you'd expect to see that in release notes, <a href="http://support.microsoft.com/kb/951847" rel="nofollow noreferrer">change lists</a>, or the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlignoreattribute.aspx" rel="nofollow noreferrer">XmlIgnoreAttribute documentation</a>.</p>
| [
{
"answer_id": 35223,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 3,
"selected": true,
"text": "<p>In SP1 does the foo.Bar property get properly deserialized?</p>\n\n<p>In pre SP1 you wouldn't be able to deserialize the obje... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2314/"
] | I've seen quite a few posts on changes in .NET 3.5 SP1, but stumbled into one that I've yet to see documentation for yesterday. I had code working just fine on my machine, from VS, msbuild command line, everything, but it failed on the build server (running .NET 3.5 RTM).
```
[XmlRoot("foo")]
public class Foo
{
static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string xml = @"<foo name='ack' />";
using (StringReader sr = new StringReader(xml))
{
Foo foo = serializer.Deserialize(sr) as Foo;
}
}
[XmlAttribute("name")]
public string Name { get; set; }
public Foo Bar { get; private set; }
}
```
In SP1, the above code runs just fine. In RTM, you get an InvalidOperationException:
>
> Unable to generate a temporary class (result=1).
> error CS0200: Property or indexer 'ConsoleApplication2.Foo.Bar' cannot be assign to -- it is read only
>
>
>
Of course, all that's needed to make it run under RTM is adding [XmlIgnore] to the Bar property.
My google fu is apparently not up to finding documentation of these kinds of changes. Is there a change list anywhere that lists this change (and similar under-the-hood changes that might jump up and shout "gotcha")? Is this a bug or a feature?
**EDIT**: In SP1, if I added a `<Bar />` element, or set [XmlElement] for the Bar property, it won't get deserialized. It doesn't fail pre-SP1 when it tries to deserialize--it throws an exception when the XmlSerializer is constructed.
This makes me lean more toward it being a bug, especially if I set an [XmlElement] attribute for Foo.Bar. If it's unable to do what I ask it to do, it should be throwing an exception instead of silently ignoring Foo.Bar. Other invalid combinations/settings of XML serialization attributes result in an exception.
**EDIT**: Thank you, TonyB, I'd not known about setting the temp files location. For those that come across similar issues in the future, you do need an additional config flag:
```
<system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="1" />
</switches>
</system.diagnostics>
<system.xml.serialization>
<xmlSerializer tempFilesLocation="c:\\foo"/>
</system.xml.serialization>
```
Even with setting an [XmlElement] attribute on the Bar property, no mention was made of it in the generated serialization assembly--which fairly firmly puts this in the realm of a silently swallowed error (aka, a bug). Either that or the designers have decided [XmlIgnore] is no longer necessary for properties that can't be set--and you'd expect to see that in release notes, [change lists](http://support.microsoft.com/kb/951847), or the [XmlIgnoreAttribute documentation](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlignoreattribute.aspx). | In SP1 does the foo.Bar property get properly deserialized?
In pre SP1 you wouldn't be able to deserialize the object because the set method of the Bar property is private so the XmlSerializer doesn't have a way to set that value. I'm not sure how SP1 is pulling it off.
You could try adding this to your web.config/app.config
```
<system.xml.serialization>
<xmlSerializer tempFilesLocation="c:\\foo"/>
</system.xml.serialization>
```
That will put the class generated by the XmlSerializer into c:\foo so you can see what it is doing in SP1 vs RTM |
34,926 | <p>my <b>SSRS DataSet</b> returns a field with HTML, e.g.</p>
<pre><code><b>blah blah </b><i> blah </i>.
</code></pre>
<p>how do i strip all the HTML tags? has to be done with <b>inline</b> VB.NET</p>
<p>Changing the data in the table is not an option.</p>
<p><strong>Solution found</strong> ... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","")</p>
| [
{
"answer_id": 34935,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a good example using Regular Expressions: <a href=\"https://web.archive.org/web/20210619174622/https://www.... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] | my **SSRS DataSet** returns a field with HTML, e.g.
```
<b>blah blah </b><i> blah </i>.
```
how do i strip all the HTML tags? has to be done with **inline** VB.NET
Changing the data in the table is not an option.
**Solution found** ... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","") | Thanx to Daniel, but I needed it to be done inline ... here's the solution:
`= System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","")`
Here are the links:
<http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx>
<http://msdn.microsoft.com/en-us/library/ms157328.aspx> |
34,938 | <p>I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.</p>
<p>if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?</p>
<pre><code>if ( (condition1) | (condition2) ){
// do this
}
</code></pre>
<p>or would I need to nest two if statements to only check the second condition if the first evaluates to false?</p>
<pre><code>if (condition1){
// do this
}else if (condition2){
// do this
}
</code></pre>
<p>I am working in PHP, however, I assume that this may be language-agnostic.</p>
| [
{
"answer_id": 34941,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 0,
"selected": false,
"text": "<p>Since this is tagged language agnostic I'll chime in. For Perl at least, the first option is sufficient, I'm not familiar w... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083/"
] | I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.
if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?
```
if ( (condition1) | (condition2) ){
// do this
}
```
or would I need to nest two if statements to only check the second condition if the first evaluates to false?
```
if (condition1){
// do this
}else if (condition2){
// do this
}
```
I am working in PHP, however, I assume that this may be language-agnostic. | For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated.
An old trick for doing obfuscated code was to use this to create if statements, such as:
```
a || b();
```
if "a" is true, "b()" would never be evaluated, so we can rewrite it into:
```
if(!a)
b();
```
and similarly:
```
a && b();
```
would become
```
if(a)
b();
```
**Please note** that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised".
EDIT:
As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time.
First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason.
Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless. |
34,955 | <p>When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors?</p>
| [
{
"answer_id": 34967,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "<p>One of the common linking errors I've run into is when a function is used differently from how it's defined. If yo... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575/"
] | When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors? | Not sure what your level of expertise is, but here are the basics.
Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it.
```
ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z)
```
There are a couple of points to focus on:
* "ByteComparator.obj" - Look for a ByteComparator.cpp file, this is the source of the linker problem
* "int \_\_cdecl does\_not\_exist(void)" - This is the symbol it couldn't find, in this case a function named does\_not\_exist()
At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together.
If you're using VS2005, you would use the "Project Dependencies..." right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of .o files) and add the missing .o file.
---
In a second scenario, you may be missing an "external" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to [MSDN](http://msdn.microsoft.com/en-us/default.aspx) or ["Microsoft Google"](http://www.google.com/microsoft) and search for the API. At the bottom of the API description the library name is given. Add this to your project properties "Configuration Properties->Linker->Input->Additional Dependencies" list. For example, the function timeGetTime()'s [page on MSDN](http://msdn.microsoft.com/en-us/library/ms713418(VS.85).aspx) tells you to use Winmm.lib at the bottom of the page. |
34,977 | <p>I have a protocol that requires a length field up to 32-bits, and it must be
generated at runtime to describe how many bytes are in a given packet.</p>
<p>The code below is kind of ugly but I am wondering if this can be refactored to
be slightly more efficient or easily understandable. The problem is that the
code will only generate enough bytes to describe the length of the packet, so
less than 255 bytes = 1 byte of length, less than 65535 = 2 bytes of length
etc...</p>
<pre><code>{
extern char byte_stream[];
int bytes = offset_in_packet;
int n = length_of_packet;
/* Under 4 billion, so this can be represented in 32 bits. */
int t;
/* 32-bit number used for temporary storage. */
/* These are the bytes we will break up n into. */
unsigned char first, second, third, fourth;
t = n & 0xFF000000;
/* We have used AND to "mask out" the first byte of the number. */
/* The only bits which can be on in t are the first 8 bits. */
first = t >> 24;
if (t) {
printf("byte 1: 0x%02x\n",first );
byte_stream[bytes] = first; bytes++;
write_zeros = 1;
}
/* Now we shift t so that it is between 0 and 255. This is the first, highest byte of n. */
t = n & 0x00FF0000;
second = t >> 16;
if (t || write_zeros) {
printf("byte 2: 0x%02x\n", second );
byte_stream[bytes] = second; bytes++;
write_zeros = 1;
}
t = n & 0x0000FF00;
third = t >> 8;
if ( t || write_zeros) {
printf("byte 3: 0x%02x\n", third );
byte_stream[bytes] = third; bytes++;
write_zeros = 1;
}
t = n & 0x000000FF;
fourth = t;
if (t || write_zeros) {
printf("byte 4: 0x%02x\n", fourth);
byte_stream[bytes] = fourth; bytes++;
}
}
</code></pre>
| [
{
"answer_id": 35027,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "<p>Try this loop:</p>\n\n<pre><code>{\n extern char byte_stream[];\n int bytes = offset_in_packet;\n int n =... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3663/"
] | I have a protocol that requires a length field up to 32-bits, and it must be
generated at runtime to describe how many bytes are in a given packet.
The code below is kind of ugly but I am wondering if this can be refactored to
be slightly more efficient or easily understandable. The problem is that the
code will only generate enough bytes to describe the length of the packet, so
less than 255 bytes = 1 byte of length, less than 65535 = 2 bytes of length
etc...
```
{
extern char byte_stream[];
int bytes = offset_in_packet;
int n = length_of_packet;
/* Under 4 billion, so this can be represented in 32 bits. */
int t;
/* 32-bit number used for temporary storage. */
/* These are the bytes we will break up n into. */
unsigned char first, second, third, fourth;
t = n & 0xFF000000;
/* We have used AND to "mask out" the first byte of the number. */
/* The only bits which can be on in t are the first 8 bits. */
first = t >> 24;
if (t) {
printf("byte 1: 0x%02x\n",first );
byte_stream[bytes] = first; bytes++;
write_zeros = 1;
}
/* Now we shift t so that it is between 0 and 255. This is the first, highest byte of n. */
t = n & 0x00FF0000;
second = t >> 16;
if (t || write_zeros) {
printf("byte 2: 0x%02x\n", second );
byte_stream[bytes] = second; bytes++;
write_zeros = 1;
}
t = n & 0x0000FF00;
third = t >> 8;
if ( t || write_zeros) {
printf("byte 3: 0x%02x\n", third );
byte_stream[bytes] = third; bytes++;
write_zeros = 1;
}
t = n & 0x000000FF;
fourth = t;
if (t || write_zeros) {
printf("byte 4: 0x%02x\n", fourth);
byte_stream[bytes] = fourth; bytes++;
}
}
``` | Really you're only doing four calculations, so ***readability seems way more important*** here than efficiency. My approach to make something like this more readable is to
1. Extract common code to a function
2. Put similar calculations together to make the patterns more obvious
3. Get rid of the intermediate variable print\_zeroes and be explicit about the cases in which you output bytes even if they're zero (i.e. the preceding byte was non-zero)
I've changed the random code block into a function and changed a few variables (underscores are giving me trouble in the markdown preview screen). I've also assumed that *bytes* is being passed in, and that whoever is passing it in will pass us a pointer so we can modify it.
Here's the code:
```
/* append byte b to stream, increment index */
/* really needs to check length of stream before appending */
void output( int i, unsigned char b, char stream[], int *index )
{
printf("byte %d: 0x%02x\n", i, b);
stream[(*index)++] = b;
}
void answer( char bytestream[], unsigned int *bytes, unsigned int n)
{
/* mask out four bytes from word n */
first = (n & 0xFF000000) >> 24;
second = (n & 0x00FF0000) >> 16;
third = (n & 0x0000FF00) >> 8;
fourth = (n & 0x000000FF) >> 0;
/* conditionally output each byte starting with the */
/* first non-zero byte */
if (first)
output( 1, first, bytestream, bytes);
if (first || second)
output( 2, second, bytestream, bytes);
if (first || second || third)
output( 3, third, bytestream, bytes);
if (first || second || third || fourth)
output( 4, fourth, bytestream, bytes);
}
```
Ever so slightly more efficient, and ***maybe*** easier to understand would be this modification to the last four if statements:
```
if (n>0x00FFFFFF)
output( 1, first, bytestream, bytes);
if (n>0x0000FFFF)
output( 2, second, bytestream, bytes);
if (n>0x000000FF)
output( 3, third, bytestream, bytes);
if (1)
output( 4, fourth, bytestream, bytes);
```
I agree, however, that compressing this field makes the receiving state machine overly complicated. But if you can't change the protocol, this code is much easier to read. |
34,987 | <p>I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?</p>
<p>Possible non-solutions:</p>
<pre><code>vector<string> v;
v.push_back("abc");
b.push_back("xyz");
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
</code></pre>
<p>Problems - no way to create the vector on one line with a list of strings</p>
<p>Possible non-solution 2:</p>
<pre><code>string list[] = {"abc", "xyz"};
</code></pre>
<p>Problems - no way to get the number of strings automatically (that I know of).</p>
<p>There must be an easy way of doing this.</p>
| [
{
"answer_id": 35006,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>Problems - no way to get the number of strings automatically (that i know of).</p>\n</blockquote>\n\n<p>Th... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779/"
] | I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?
Possible non-solutions:
```
vector<string> v;
v.push_back("abc");
b.push_back("xyz");
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
```
Problems - no way to create the vector on one line with a list of strings
Possible non-solution 2:
```
string list[] = {"abc", "xyz"};
```
Problems - no way to get the number of strings automatically (that I know of).
There must be an easy way of doing this. | C++ 11 added initialization lists to allow the following syntax:
```
std::vector<std::string> v = {"Hello", "World"};
```
Support for this C++ 11 feature was added in at least [GCC 4.4](http://gcc.gnu.org/projects/cxx0x.html) and only in [Visual Studio 2013](https://msdn.microsoft.com/en-us/library/hh567368.aspx#corelanguagetable). |
35,002 | <p><strong>Is there anything built into the core C# libraries that can give me an immutable Dictionary?</strong> </p>
<p>Something along the lines of <em>Java's</em>:</p>
<pre><code>Collections.unmodifiableMap(myMap);
</code></pre>
<p>And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called (<code>Add, Remove, Clear</code>).</p>
| [
{
"answer_id": 35045,
"author": "Kevin Dente",
"author_id": 9,
"author_profile": "https://Stackoverflow.com/users/9",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think so. There is a way to create a read-only List and read only Collection, but I don't think there's a built in r... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] | **Is there anything built into the core C# libraries that can give me an immutable Dictionary?**
Something along the lines of *Java's*:
```
Collections.unmodifiableMap(myMap);
```
And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called (`Add, Remove, Clear`). | No, but a wrapper is rather trivial:
```
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
IDictionary<TKey, TValue> _dict;
public ReadOnlyDictionary(IDictionary<TKey, TValue> backingDict)
{
_dict = backingDict;
}
public void Add(TKey key, TValue value)
{
throw new InvalidOperationException();
}
public bool ContainsKey(TKey key)
{
return _dict.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get { return _dict.Keys; }
}
public bool Remove(TKey key)
{
throw new InvalidOperationException();
}
public bool TryGetValue(TKey key, out TValue value)
{
return _dict.TryGetValue(key, out value);
}
public ICollection<TValue> Values
{
get { return _dict.Values; }
}
public TValue this[TKey key]
{
get { return _dict[key]; }
set { throw new InvalidOperationException(); }
}
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new InvalidOperationException();
}
public void Clear()
{
throw new InvalidOperationException();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _dict.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_dict.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _dict.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new InvalidOperationException();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _dict.GetEnumerator();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)_dict).GetEnumerator();
}
}
```
Obviously, you can change the this[] setter above if you want to allow modifying values. |
35,007 | <p>Every time I create an object that has a collection property I go back and forth on the best way to do it?</p>
<ol>
<li>public property with a getter that
returns a reference to private variable</li>
<li>explicit get_ObjList and set_ObjList
methods that return and create new or cloned
objects every time</li>
<li>explicit get_ObjList that returns an
IEnumerator and a set_ObjList that
takes IEnumerator</li>
</ol>
<p>Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List?</p>
<p>If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks?</p>
<p>And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property?</p>
<p>The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has <a href="http://www.coversant.net/Coversant/Blogs/tabid/88/EntryID/34/Default.aspx" rel="noreferrer">enumeration concerns</a> </p>
<p>Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better.</p>
<p>Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.?</p>
| [
{
"answer_id": 35018,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 0,
"selected": false,
"text": "<p>If you're simply looking to expose a collection on your instance, then using a getter/setter to a private member var... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582/"
] | Every time I create an object that has a collection property I go back and forth on the best way to do it?
1. public property with a getter that
returns a reference to private variable
2. explicit get\_ObjList and set\_ObjList
methods that return and create new or cloned
objects every time
3. explicit get\_ObjList that returns an
IEnumerator and a set\_ObjList that
takes IEnumerator
Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List?
If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks?
And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property?
The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has [enumeration concerns](http://www.coversant.net/Coversant/Blogs/tabid/88/EntryID/34/Default.aspx)
Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better.
Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.? | How you expose a collection depends entirely on how users are intended to interact with it.
**1)** If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question):
```
private readonly Collection<T> myCollection_ = new ...;
public Collection<T> MyCollection {
get { return this.myCollection_; }
}
```
This strategy is used for the `Items` collections on the WindowsForms and WPF `ItemsControl` controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items.
WPF also exposes some settable collections to allow users to display a collection of items they control, such as the `ItemsSource` property on `ItemsControl` (option #3 from the original question). However, this is not a common use case.
**2)** If users will only be reading data maintained by the object, then you can use a readonly collection, as [Quibblesome](https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property#35065) suggested:
```
private readonly List<T> myPrivateCollection_ = new ...;
private ReadOnlyCollection<T> myPrivateCollectionView_;
public ReadOnlyCollection<T> MyCollection {
get {
if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ }
return this.myPrivateCollectionView_;
}
}
```
Note that `ReadOnlyCollection<T>` provides a live view of the underlying collection, so you only need to create the view once.
If the internal collection does not implement `IList<T>`, or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator:
```
public IEnumerable<T> MyCollection {
get {
foreach( T item in this.myPrivateCollection_ )
yield return item;
}
}
```
This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection.
**3)** Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question):
```
private T[] myArray_;
public T[] GetMyArray( ) {
T[] copy = new T[this.myArray_.Length];
this.myArray_.CopyTo( copy, 0 );
return copy;
// Note: if you are using LINQ, calling the 'ToArray( )'
// extension method will create a copy for you.
}
```
You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding `SetMyArray( T[] array )` method, or use a custom indexer:
```
public T this[int index] {
get { return this.myArray_[index]; }
set {
// TODO: validate new value; raise change event; etc.
this.myArray_[index] = value;
}
}
```
(of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes :) |
35,011 | <p>I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution?</p>
| [
{
"answer_id": 35057,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 6,
"selected": true,
"text": "<p>GACUTIL doesn't register DLLs -- not in the \"COM\" sense. Unlike in COM, GACUTIL copies the file to an opaque directo... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/667/"
] | I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution? | GACUTIL doesn't register DLLs -- not in the "COM" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL "register a folder" (not that you can do that with RegSvr32 either).
You can use a batch FOR command such as:
```
FOR %a IN (C:\MyFolderWithAssemblies\*.dll) DO GACUTIL /i %a
```
If you place that in a batch file, you must replace %a with %%a |
35,037 | <p>I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links:</p>
<pre><code><A HREF="path to file">filename</A>
</code></pre>
<p>The filenames can be complicated:</p>
<pre><code>LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf
</code></pre>
<p>What is the correct way to link to this file on a Linux/Apache server?</p>
<p>Is there a PHP function to do this conversion?</p>
| [
{
"answer_id": 35046,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://se.php.net/manual/en/function.urlencode.php\" rel=\"nofollow noreferrer\">urlencode()</a> should probably do... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2703/"
] | I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links:
```
<A HREF="path to file">filename</A>
```
The filenames can be complicated:
```
LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf
```
What is the correct way to link to this file on a Linux/Apache server?
Is there a PHP function to do this conversion? | You can use [rawurlencode()](http://php.net/manual/en/function.rawurlencode.php) to convert a string according to the RFC 1738 spec.
This function replaces all non-alphanumeric characters by their associated code.
The difference with [urlencode()](http://php.net/manual/en/function.urlencode.php) is that spaces are encoded as plus signs.
You'll probably want to use the last one.
This technique is called Percent or URL encoding. See [Wikipedia](http://en.wikipedia.org/wiki/Url_encoding) for more details. |
35,047 | <p>Perhaps the biggest risk in pushing new functionality to live lies with the database modifications required by the new code. In Rails, I believe they have 'migrations', in which you can programmatically make changes to your development host, and then make the same changes live along with the code that uses the revised schema. And roll both backs if needs be, in a synchronized fashion.</p>
<p>Has anyone come across a similar toolset for PHP/MySQL? Would love to hear about it, or any programmatic or process solutions to help make this less risky...</p>
| [
{
"answer_id": 35061,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 2,
"selected": false,
"text": "<p>Symfony has a plugin called sfMigrationsLight that handles basic migrations. CakePHP also has migrations.</p>\n\n<p>For wha... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | Perhaps the biggest risk in pushing new functionality to live lies with the database modifications required by the new code. In Rails, I believe they have 'migrations', in which you can programmatically make changes to your development host, and then make the same changes live along with the code that uses the revised schema. And roll both backs if needs be, in a synchronized fashion.
Has anyone come across a similar toolset for PHP/MySQL? Would love to hear about it, or any programmatic or process solutions to help make this less risky... | I've never come across a tool that would do the job. Instead I've used individual files, numbered so that I know which order to run them: essentially, a manual version of Rails migrations, but without the rollback.
Here's the sort of thing I'm talking about:
```
000-clean.sql # wipe out everything in the DB
001-schema.sql # create the initial DB objects
002-fk.sql # apply referential integrity (simple if kept separate)
003-reference-pop.sql # populate reference data
004-release-pop.sql # populate release data
005-add-new-table.sql # modification
006-rename-table.sql # another modification...
```
I've never actually run into any problems doing this, but it's not very elegant. It's up to you to track which scripts need to run for a given update (a smarter numbering scheme could help). It also works fine with source control.
Dealing with surrogate key values (from autonumber columns) can be a pain, since the production database will likely have different values than the development DB. So, I try never to reference a literal surrogate key value in any of my modification scripts if at all possible. |
35,070 | <p>What's the best way to programmatically merge a .reg file into the registry? This is for unit testing; the .reg file is a test artifact which will be added then removed at the start and end of testing.</p>
<p>Or, if there's a better way to unit test against the registry...</p>
| [
{
"answer_id": 35092,
"author": "Javache",
"author_id": 1074,
"author_profile": "https://Stackoverflow.com/users/1074",
"pm_score": 2,
"selected": false,
"text": "<p>I looked into it by checking out my file associations.</p>\n\n<p>It seems that a .reg file is just called as the first par... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] | What's the best way to programmatically merge a .reg file into the registry? This is for unit testing; the .reg file is a test artifact which will be added then removed at the start and end of testing.
Or, if there's a better way to unit test against the registry... | It is possible to remove registry keys using a .reg file, although I'm not sure how well it's documented. Here's how:
```
REGEDIT4
[-HKEY_CURRENT_USER\Software\<otherpath>]
```
The `-` in front of the key name tells `Regedit` that you want to remove the key.
To run this silently, type:
```
regedit /s "myfile.reg"
``` |
35,076 | <p>I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove.</p>
<p>The database is shared by several different applications, so I can't be 100% confident that reviewing these will give me a complete list of the objects that are used.</p>
<p>What I'd like to do, if it's possible, is to get a list of tables that haven't been accessed at all for some period of time. No reads, no writes. How should I approach this?</p>
| [
{
"answer_id": 35087,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>If you have lastupdate columns you can check for the writes, there is really no easy way to check for reads. You could run... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3344/"
] | I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove.
The database is shared by several different applications, so I can't be 100% confident that reviewing these will give me a complete list of the objects that are used.
What I'd like to do, if it's possible, is to get a list of tables that haven't been accessed at all for some period of time. No reads, no writes. How should I approach this? | MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there to find all the tables (and views, sps, etc) that are used by your applications.
Another way I think you might check if there's any "writes" is to add a new timestamp column to every table, and a trigger that updates that column every time there's an update or an insert. But keep in mind that if your apps do queries of the type
```
select * from ...
```
then they will receive a new column and that might cause you some problems. |
35,102 | <p>In emacs, I've read the following code snippet in <code>simple.el</code>:</p>
<pre><code>(frame-parameter frame 'buried-buffer-list)
</code></pre>
<p>What is the exact meaning of the <code>'buried-buffer-list</code> parameter?
What it is used for?</p>
| [
{
"answer_id": 35087,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>If you have lastupdate columns you can check for the writes, there is really no easy way to check for reads. You could run... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3673/"
] | In emacs, I've read the following code snippet in `simple.el`:
```
(frame-parameter frame 'buried-buffer-list)
```
What is the exact meaning of the `'buried-buffer-list` parameter?
What it is used for? | MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there to find all the tables (and views, sps, etc) that are used by your applications.
Another way I think you might check if there's any "writes" is to add a new timestamp column to every table, and a trigger that updates that column every time there's an update or an insert. But keep in mind that if your apps do queries of the type
```
select * from ...
```
then they will receive a new column and that might cause you some problems. |
35,103 | <p>I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file.</p>
<p>Essentially if someone modifies this file outside of the program the program should fail to load it again.</p>
<p>EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place.</p>
<p>The configuration still needs to be editable though so compiling an individual copy for each customer is not an option.</p>
<hr>
<p>It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes.</p>
| [
{
"answer_id": 35109,
"author": "Joel Martinez",
"author_id": 3433,
"author_profile": "https://Stackoverflow.com/users/3433",
"pm_score": -1,
"selected": false,
"text": "<p>just make a const string that holds the md5 hash and compile it into your app ... your app can then just refer to t... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191/"
] | I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file.
Essentially if someone modifies this file outside of the program the program should fail to load it again.
EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place.
The configuration still needs to be editable though so compiling an individual copy for each customer is not an option.
---
It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes. | A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5.
```
write(MD5(SecretKey + ConfigFileText));
```
Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key.
Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored.
A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort.
If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is *virus like* behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE.
**Update:** I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the user's computer (which you *must* do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael.
**Update:** The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere "secret" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system. . . Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances.
**UPDATE:** For a Credit Card system you might want to consider some real security. You should retain the services of a *security and cryptography consultant*. More information needs to be exchanged. They need to analyze your specific needs and risks.
Also, if you want security with .NET you need to first start with a really good .NET obfuscator ([just Google it](http://www.google.com/search?hl=en&q=.NET%20obfuscator&aq=f&oq=)). A .NET assembly is way to easy to disassemble and get at the source code and read all your secrets. Not to sound a like a broken record, but anything that depends on the security of your user's system is fundamentally flawed from the beginning. |
35,106 | <p>I've found <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.scriptingjsonserializationsection.scriptingjsonserializationsection.aspx" rel="noreferrer"><code>ScriptingJsonSerializationSection</code></a> but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the <code><System.Web.Services.WebMethod()></code> and <code><System.Web.Script.Services.ScriptMethod()></code> attributes so there must be a built-in way that I'm missing. </p>
<p>PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it.</p>
| [
{
"answer_id": 35125,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 5,
"selected": true,
"text": "<p>This should do the trick</p>\n\n<pre><code>Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer\nDi... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | I've found [`ScriptingJsonSerializationSection`](http://msdn.microsoft.com/en-us/library/system.web.configuration.scriptingjsonserializationsection.scriptingjsonserializationsection.aspx) but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the `<System.Web.Services.WebMethod()>` and `<System.Web.Script.Services.ScriptMethod()>` attributes so there must be a built-in way that I'm missing.
PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it. | This should do the trick
```
Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jsonString as String = jsonSerialiser.Serialize(yourObject)
``` |
35,123 | <p>What did I do wrong?</p>
<p>Here is an excerpt from my code:</p>
<pre><code>public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
scrollBox.setExpandHorizontal(true);
mParent = new Composite(scrollBox, SWT.NONE);
scrollBox.setContent(mParent);
FormLayout layout = new FormLayout();
mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.layout();
mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
}
</code></pre>
<p>...but it clips the last button:
<img src="https://i.stack.imgur.com/1ubzc.png" alt="alt text" title="Screenshot"></p>
<p>bigbrother82: That didn't work.</p>
<p>SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that.</p>
| [
{
"answer_id": 35503,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 0,
"selected": false,
"text": "<p>Don't you need to recompute the size of the scrollBox after the layout?</p>\n"
},
{
"answer_id": 36306,
"author":... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657/"
] | What did I do wrong?
Here is an excerpt from my code:
```
public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
scrollBox.setExpandHorizontal(true);
mParent = new Composite(scrollBox, SWT.NONE);
scrollBox.setContent(mParent);
FormLayout layout = new FormLayout();
mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.layout();
mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
}
```
...but it clips the last button:

bigbrother82: That didn't work.
SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that. | This is a common hurdle when using `ScrolledComposite`. When it gets so small that the scroll bar must be shown, the client control has to shrink horizontally to make room for the scroll bar. This has the side effect of making some labels wrap lines, which moved the following controls farther down, which increased the minimum height needed by the content composite.
You need to listen for width changes on the content composite (`mParent`), compute the minimum height again given the new content width, and call `setMinHeight()` on the scrolled composite with new height.
```
public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
scrollBox.setExpandHorizontal(true);
scrollBox.setExpandVertical(true);
// Using 0 here ensures the horizontal scroll bar will never appear. If
// you want the horizontal bar to appear at some threshold (say 100
// pixels) then send that value instead.
scrollBox.setMinWidth(0);
mParent = new Composite(scrollBox, SWT.NONE);
FormLayout layout = new FormLayout();
mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.addListener(SWT.Resize, new Listener() {
int width = -1;
public void handleEvent(Event e) {
int newWidth = mParent.getSize().x;
if (newWidth != width) {
scrollBox.setMinHeight(mParent.computeSize(newWidth, SWT.DEFAULT).y);
width = newWidth;
}
}
}
// Wait until here to set content pane. This way the resize listener will
// fire when the scrolled composite first resizes mParent, which in turn
// computes the minimum height and calls setMinHeight()
scrollBox.setContent(mParent);
}
```
In listening for size changes, note that we ignore any resize events where the width stays the same. This is because changes in the height of the content do not affect the *minimum* height of the content, as long as the width is the same. |
35,167 | <p>I know that the following is true</p>
<pre><code>int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010
</code></pre>
<p>But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with.</p>
<p>Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop.</p>
| [
{
"answer_id": 35172,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 7,
"selected": true,
"text": "<p>If you know the size of type, you could do something like:</p>\n\n<pre><code>uint i = 17;\nuint j = i << 1 | ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] | I know that the following is true
```
int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010
```
But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with.
Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop. | If you know the size of type, you could do something like:
```
uint i = 17;
uint j = i << 1 | i >> 31;
```
... which would perform a circular shift of a 32 bit value.
As a generalization to circular shift left n bits, on a b bit variable:
```
/*some unsigned numeric type*/ input = 17;
var result = input << n | input >> (b - n);
```
---
@The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this [here](http://www.blackwasp.co.uk/CSharpShiftOperators.aspx). I also changed the example to use a uint. |
35,170 | <p>What does it mean if a task is declared with the automatic keyword in Verilog?</p>
<pre><code>task automatic do_things;
input [31:0] number_of_things;
reg [31:0] tmp_thing;
begin
// ...
end
endtask;
</code></pre>
<p>Note: This question is mostly because I'm curious if there are any hardware programmers on the site. :)</p>
| [
{
"answer_id": 35193,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 5,
"selected": true,
"text": "<p>It means that the task is re-entrant - items declared within the task are dynamically allocated rather than shared between ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | What does it mean if a task is declared with the automatic keyword in Verilog?
```
task automatic do_things;
input [31:0] number_of_things;
reg [31:0] tmp_thing;
begin
// ...
end
endtask;
```
Note: This question is mostly because I'm curious if there are any hardware programmers on the site. :) | It means that the task is re-entrant - items declared within the task are dynamically allocated rather than shared between different invocations of the task.
You see - some of us do Verilog... (ugh) |
35,178 | <p>I am working on a C++ code base that was recently moved from X/Motif to Qt. I am trying to write a Perl script that will replace all occurrences of Boolean (from X) with bool. The script just does a simple replacement. </p>
<pre><code>s/\bBoolean\b/bool/g
</code></pre>
<p>There are a few conditions. </p>
<p>1) We have CORBA in our code and \b matches CORBA::Boolean which should <strong>not</strong> be changed.<br>
2) It should not match if it was found as a string (i.e. "Boolean")</p>
<p><strong>Updated:</strong></p>
<p>For #1, I used lookbehind</p>
<pre><code>s/(?<!:)\bBoolean\b/bool/g;
</code></pre>
<p>For #2, I used lookahead.</p>
<pre><code>s/(?<!:)\bBoolean\b(?!")/bool/g</pre>
</code></pre>
<p>This will most likely work for my situation but how about the following improvements?</p>
<p>3) Do not match if in the middle of a string (thanks <a href="https://stackoverflow.com/users/3101/nohat">nohat</a>).<br>
4) Do not match if in a comment. (// or /**/) </p>
| [
{
"answer_id": 35198,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "<p>To fix condition 1 try:</p>\n\n<pre><code>s/[^:]\\bBoolean\\b(?!\")/bool/g\n</code></pre>\n\n<p>The [^:] says to matc... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897/"
] | I am working on a C++ code base that was recently moved from X/Motif to Qt. I am trying to write a Perl script that will replace all occurrences of Boolean (from X) with bool. The script just does a simple replacement.
```
s/\bBoolean\b/bool/g
```
There are a few conditions.
1) We have CORBA in our code and \b matches CORBA::Boolean which should **not** be changed.
2) It should not match if it was found as a string (i.e. "Boolean")
**Updated:**
For #1, I used lookbehind
```
s/(?<!:)\bBoolean\b/bool/g;
```
For #2, I used lookahead.
```
s/(?<!:)\bBoolean\b(?!")/bool/g</pre>
```
This will most likely work for my situation but how about the following improvements?
3) Do not match if in the middle of a string (thanks [nohat](https://stackoverflow.com/users/3101/nohat)).
4) Do not match if in a comment. (// or /\*\*/) | >
> s/[^:]\bBoolean\b(?!")/bool/g
>
>
>
This does not match strings where Boolean is at that the beginning of the line becuase [^:] is "match a character that is not :". |
35,185 | <p>What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice.</p>
<p>So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm.</p>
| [
{
"answer_id": 35192,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 0,
"selected": false,
"text": "<p>You need to specify what you mean by \"best\" - to some, speed is all that matters and would qualify an answer as \"... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] | What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice.
So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm. | The fastest (O(n)) and most memory efficient (O(1)) way is with the XOR operation.
In C:
```
int arr[] = {3, 2, 5, 2, 1, 5, 3};
int num = 0, i;
for (i=0; i < 7; i++)
num ^= arr[i];
printf("%i\n", num);
```
This prints "1", which is the only one that occurs once.
This works because the first time you hit a number it marks the num variable with itself, and the second time it unmarks num with itself (more or less). The only one that remains unmarked is your non-duplicate. |
35,208 | <p>I have a page with many forms in panels and usercontrols, and a requiredfield validator I just added to one form is preventing all of my other forms from submitting. what's the rule that I'm not following?</p>
| [
{
"answer_id": 35213,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 0,
"selected": false,
"text": "<p>You should be setting ValidationGroup property to a different value for each group of elements. Your validator's Va... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] | I have a page with many forms in panels and usercontrols, and a requiredfield validator I just added to one form is preventing all of my other forms from submitting. what's the rule that I'm not following? | Are you using ValidationGroups? Try assigning each control with a validation group as well as the validator that you want to use. Something like:
```
<asp:TextBox ID="txt1" ValidationGroup="Group1" ruant="server" />
<asp:RequiredFieldValidator ID="rfv1" ... ValidationGroup="Group1" />
```
Note, if a button doesn't specify a validation group it will validate all controls that aren't assigned to a validation group. |
35,211 | <p>The compiler usually chokes when an event doesn't appear beside a <code>+=</code> or a <code>-=</code>, so I'm not sure if this is possible.</p>
<p>I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:</p>
<pre><code>using(var foo = new EventWatcher(target, x => x.MyEventToWatch) {
// act here
} // throws on Dispose() if MyEventToWatch hasn't fired
</code></pre>
<p>My questions are twofold:</p>
<ol>
<li>Will the compiler choke? And if so, any suggestions on how to prevent this?</li>
<li>How can I parse the Expression object from the constructor in order to attach to the <code>MyEventToWatch</code> event of <code>target</code>?</li>
</ol>
| [
{
"answer_id": 36255,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "<p>A .NET event isn't actually an object, it's an endpoint represented by two functions -- one for adding and one for ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The compiler usually chokes when an event doesn't appear beside a `+=` or a `-=`, so I'm not sure if this is possible.
I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:
```
using(var foo = new EventWatcher(target, x => x.MyEventToWatch) {
// act here
} // throws on Dispose() if MyEventToWatch hasn't fired
```
My questions are twofold:
1. Will the compiler choke? And if so, any suggestions on how to prevent this?
2. How can I parse the Expression object from the constructor in order to attach to the `MyEventToWatch` event of `target`? | **Edit:** As [Curt](https://stackoverflow.com/questions/35211/identify-an-event-via-a-linq-expression-tree#36255) has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event :) Instead of "`x => x.MyEvent`" returning the event, it was returning the backing field, which is only accessble by the class.
Since expressions cannot contain assignment statements, a modified expression like "`( x, h ) => x.MyEvent += h`" cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the `EventInfo` for the event (which, unfortunatley, will not be strongly typed).
Otherwise, the only updates that need to be made are to store the reflected `EventInfo`, and use the `AddEventHandler`/`RemoveEventHandler` methods to register the listener (instead of the manual `Delegate` `Combine`/`Remove` calls and field sets). The rest of the implementation should not need to be changed. Good luck :)
---
**Note:** This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader ;)
```
public sealed class EventWatcher : IDisposable {
private readonly object target_;
private readonly string eventName_;
private readonly FieldInfo eventField_;
private readonly Delegate listener_;
private bool eventWasRaised_;
public static EventWatcher Create<T>( T target, Expression<Func<T,Delegate>> accessor ) {
return new EventWatcher( target, accessor );
}
private EventWatcher( object target, LambdaExpression accessor ) {
this.target_ = target;
// Retrieve event definition from expression.
var eventAccessor = accessor.Body as MemberExpression;
this.eventField_ = eventAccessor.Member as FieldInfo;
this.eventName_ = this.eventField_.Name;
// Create our event listener and add it to the declaring object's event field.
this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Combine( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
}
public void SetEventWasRaised( ) {
this.eventWasRaised_ = true;
}
private Delegate CreateEventListenerDelegate( Type eventType ) {
// Create the event listener's body, setting the 'eventWasRaised_' field.
var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" );
var body = Expression.Call( Expression.Constant( this ), setMethod );
// Get the event delegate's parameters from its 'Invoke' method.
var invokeMethod = eventType.GetMethod( "Invoke" );
var parameters = invokeMethod.GetParameters( )
.Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );
// Create the listener.
var listener = Expression.Lambda( eventType, body, parameters );
return listener.Compile( );
}
void IDisposable.Dispose( ) {
// Remove the event listener.
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Remove( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
// Ensure event was raised.
if( !this.eventWasRaised_ )
throw new InvalidOperationException( "Event was not raised: " + this.eventName_ );
}
}
```
Usage is slightly different from that suggested, in order to take advantage of type inference:
```
try {
using( EventWatcher.Create( o, x => x.MyEvent ) ) {
//o.RaiseEvent( ); // Uncomment for test to succeed.
}
Console.WriteLine( "Event raised successfully" );
}
catch( InvalidOperationException ex ) {
Console.WriteLine( ex.Message );
}
``` |
35,240 | <p>I used the jQuery Form plugin for asynchronous form submission. For forms that contain files, it copies the form to a hidden iframe, submits it, and copies back the iframe's contents. The problem is that I can't figure out how to find what HTTP status code was returned by the server. For example, if the server returns 404, the data from the iframe will be copied as normal and treated as a regular response.</p>
<p>I've tried poking around in the iframe objects looking for some sort of <code>status_code</code> attribute, but haven't been able to find anything like that.</p>
<hr>
<p>The <code>$.ajax()</code> function can't be used, because it does not support uploading files. The only way to asynchronously upload files that I know of is using the hidden <code>iframe</code> method.</p>
| [
{
"answer_id": 1847965,
"author": "Coyod",
"author_id": 223888,
"author_profile": "https://Stackoverflow.com/users/223888",
"pm_score": 4,
"selected": false,
"text": "<p>You can't get page headers by JS, but you can distinguish error from success:\nTry something like this:</p>\n\n<pre><c... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3560/"
] | I used the jQuery Form plugin for asynchronous form submission. For forms that contain files, it copies the form to a hidden iframe, submits it, and copies back the iframe's contents. The problem is that I can't figure out how to find what HTTP status code was returned by the server. For example, if the server returns 404, the data from the iframe will be copied as normal and treated as a regular response.
I've tried poking around in the iframe objects looking for some sort of `status_code` attribute, but haven't been able to find anything like that.
---
The `$.ajax()` function can't be used, because it does not support uploading files. The only way to asynchronously upload files that I know of is using the hidden `iframe` method. | You can't get page headers by JS, but you can distinguish error from success:
Try something like this:
```
<script type="text/javascript">
var uploadStarted = false;
function OnUploadStart(){
uploadStarted = true;
}
function OnUploadComplete(state,message){
if(state == 1)
alert("Success: "+message);
else
if(state == 0 && uploadStarted)
alert("Error:"+( message ? message : "unknow" ));
}
</script>
<iframe id="uploader" name="uploader" onload="OnUploadComplete(0)" style="width:0px;height:0px;border:none;"></iframe>
<form id="sender" action="/upload.php" method="post" target="uploader" enctype="multipart/form-data" onsubmit="OnUploadStart()">
<input type="file" name="files[upload]"/>
<input type="submit" value="Upload"/>
</form>
```
On server side:
```
/*
file: upload.php
*/
<?php
// do some stuff with file
print '<script type="text/javascript">';
if(success)
print 'window.parent.OnUploadComplete(1,"File uploaded!");';
else
print 'window.parent.OnUploadComplete(0, "File too large!");';
print '</script>';
?>
``` |
35,286 | <p>I want to escape a DOS filename so I can use it with sed. I have a DOS batch file something like this:</p>
<pre><code>set FILENAME=%~f1
sed 's/Some Pattern/%FILENAME%/' inputfile
</code></pre>
<p>(Note: <code>%~f1</code> - expands <code>%1</code> to a Fully qualified path name - <code>C:\utils\MyFile.txt</code>)</p>
<p>I found that the backslashes in <code>%FILENAME%</code> are just escaping the next letter.</p>
<p>How can I double them up so that they are escaped?</p>
<p>(I have cygwin installed so feel free to use any other *nix commands)</p>
<h1>Solution</h1>
<p>Combining Jeremy and Alexandru Nedelcu's suggestions, and using | for the delimiter in the sed command I have</p>
<pre><code>set FILENAME=%~f1
cygpath "s|Some Pattern|%FILENAME%|" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
</code></pre>
| [
{
"answer_id": 35386,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 3,
"selected": true,
"text": "<p>This will work. It's messy because in BAT files you can't use set var=`cmd` like you can in unix.\nThe fact that echo doesn... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] | I want to escape a DOS filename so I can use it with sed. I have a DOS batch file something like this:
```
set FILENAME=%~f1
sed 's/Some Pattern/%FILENAME%/' inputfile
```
(Note: `%~f1` - expands `%1` to a Fully qualified path name - `C:\utils\MyFile.txt`)
I found that the backslashes in `%FILENAME%` are just escaping the next letter.
How can I double them up so that they are escaped?
(I have cygwin installed so feel free to use any other \*nix commands)
Solution
========
Combining Jeremy and Alexandru Nedelcu's suggestions, and using | for the delimiter in the sed command I have
```
set FILENAME=%~f1
cygpath "s|Some Pattern|%FILENAME%|" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
``` | This will work. It's messy because in BAT files you can't use set var=`cmd` like you can in unix.
The fact that echo doesn't understand quotes is also messy, and could lead to trouble if `Some Pattern` contains shell meta characters.
```
set FILENAME=%~f1
echo s/Some Pattern/%FILENAME%/ | sed -e "s/\\/\\\\/g" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
```
[Edited]: I am suprised that it didn't work for you. I just tested it, and it worked on my machine. I am using sed from <http://sourceforge.net/projects/unxutils> and using cmd.exe to run those commands in a bat file. |
35,301 | <p>I have always used <code>||</code> (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: <code>|</code>. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?</p>
| [
{
"answer_id": 35303,
"author": "nsanders",
"author_id": 1244,
"author_profile": "https://Stackoverflow.com/users/1244",
"pm_score": 5,
"selected": false,
"text": "<p>One is a \"bitwise or\".</p>\n\n<blockquote>\n <p>10011b | 01000b => 11011b</p>\n</blockquote>\n\n<p>The other is a logi... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
] | I have always used `||` (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: `|`. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable? | Just like the `&` and `&&` operator, the double Operator is a "short-circuit" operator.
For example:
```
if(condition1 || condition2 || condition3)
```
If condition1 is true, condition 2 and 3 will NOT be checked.
```
if(condition1 | condition2 | condition3)
```
This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.
There is one big caveat, NullReferences or similar problems. For example:
```
if(class != null && class.someVar < 20)
```
If class is null, the if-statement will stop after `class != null` is false. If you only use &, it will try to check `class.someVar` and you get a nice `NullReferenceException`. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.
No one ever uses the single `&` or `|` operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The `&` operator does "run these 3 functions, and if one of them returns false, execute the else block", while the `|` does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.
There is a Second use of the `|` and `&` operator though: [Bitwise Operations](http://www.c-sharpcorner.com/UploadFile/chandrahundigam/BitWiserOpsInCS11082005050940AM/BitWiserOpsInCS.aspx). |
35,317 | <p>When I log into a remote machine using ssh X11 forwarding, Vista pops up a box complaining about a process that died unexpectedly. Once I dismiss the box, everything is fine. So I really don't care if some process died. How do I get Vista to shut up about it?</p>
<hr>
<p>Specifically, the message reads:</p>
<pre><code>sh.exe has stopped working
</code></pre>
<p>So it's not ssh itself that died, but some sub-process.</p>
<p>The problem details textbox reads:</p>
<pre><code>Problem signature:
Problem Event Name: APPCRASH
Application Name: sh.exe
Application Version: 0.0.0.0
Application Timestamp: 48a031a1
Fault Module Name: comctl32.dll_unloaded
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 4549bcb0
Exception Code: c0000005
Exception Offset: 73dc5b17
OS Version: 6.0.6000.2.0.0.768.3
Locale ID: 1033
Additional Information 1: fc4d
Additional Information 2: d203a7335117760e7b4d2cf9dc2925f9
Additional Information 3: 1bc1
Additional Information 4: 7bc0b00964c4a1bd48f87b2415df3372
Read our privacy statement:
http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409
</code></pre>
<p>I notice the problem occurs when I use the <strong>-Y</strong> option to enable X11 forwarding in an X terminal under Vista.</p>
<p>The dialog box that pops up doesn't automatically gain focus, so pressing Enter serves no purpose. I have to wait for the box to appear, grab it with the mouse, and dismiss it. Even forcing the error to receive focus would be a step in the right direction.</p>
<hr>
<p>Per DrPizza I have sent an <a href="http://cygwin.com/ml/cygwin/2008-08/msg00880.html" rel="nofollow noreferrer">email</a> to the Cygwin mailing list. The trimmed down subject line represents my repeated attempts to bypass an over-aggressive spam filter and highlights the need for something like StackOverflow.</p>
| [
{
"answer_id": 35324,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is, the process didn't just die, it died unexpectedly. Sounds like there's a bug in your SSH client that V... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] | When I log into a remote machine using ssh X11 forwarding, Vista pops up a box complaining about a process that died unexpectedly. Once I dismiss the box, everything is fine. So I really don't care if some process died. How do I get Vista to shut up about it?
---
Specifically, the message reads:
```
sh.exe has stopped working
```
So it's not ssh itself that died, but some sub-process.
The problem details textbox reads:
```
Problem signature:
Problem Event Name: APPCRASH
Application Name: sh.exe
Application Version: 0.0.0.0
Application Timestamp: 48a031a1
Fault Module Name: comctl32.dll_unloaded
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 4549bcb0
Exception Code: c0000005
Exception Offset: 73dc5b17
OS Version: 6.0.6000.2.0.0.768.3
Locale ID: 1033
Additional Information 1: fc4d
Additional Information 2: d203a7335117760e7b4d2cf9dc2925f9
Additional Information 3: 1bc1
Additional Information 4: 7bc0b00964c4a1bd48f87b2415df3372
Read our privacy statement:
http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409
```
I notice the problem occurs when I use the **-Y** option to enable X11 forwarding in an X terminal under Vista.
The dialog box that pops up doesn't automatically gain focus, so pressing Enter serves no purpose. I have to wait for the box to appear, grab it with the mouse, and dismiss it. Even forcing the error to receive focus would be a step in the right direction.
---
Per DrPizza I have sent an [email](http://cygwin.com/ml/cygwin/2008-08/msg00880.html) to the Cygwin mailing list. The trimmed down subject line represents my repeated attempts to bypass an over-aggressive spam filter and highlights the need for something like StackOverflow. | Well, I don't know what the original problem was, but when I update Cygwin recently the error message stopped popping up.
My guess it that [rebasing](http://sourceware.org/ml/cygwin/2006-11/msg00059.html) was necessary. |
35,320 | <p>In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level.</p>
<pre><code>DECLARE @LookupID int
--Our test value
SET @LookupID = 1
WITH cteLevelOne (ParentID, CustID) AS
(
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustomerID
)
</code></pre>
<p>So if tblCustomer looks like this: </p>
<pre><code>ParentID CustID
5 5
1 8
5 4
4 1
</code></pre>
<p>The result I get from the code above is: </p>
<pre><code>ParentID CustID
4 1
5 4
5 5
</code></pre>
<p>What I want is just the last row of that result: </p>
<pre><code>ParentID CustID
5 5
</code></pre>
<p>How do I just return the last record generated in the CTE (which would be highest level CustID)?</p>
<p>Also note that there are multiple unrelated CustID hierarchies in this table so I can't just do a SELECT * FROM tblCustomer WHERE ParentID = CustID. I can't order by ParentID or CustID because the ID number is not related to where it is in the hierarchy.</p>
| [
{
"answer_id": 35425,
"author": "Trevor Abell",
"author_id": 2916,
"author_profile": "https://Stackoverflow.com/users/2916",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not certain I fully understand the problem, but just to hack & slash at it you could try:</p>\n\n<pre><code>S... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3677/"
] | In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level.
```
DECLARE @LookupID int
--Our test value
SET @LookupID = 1
WITH cteLevelOne (ParentID, CustID) AS
(
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustomerID
)
```
So if tblCustomer looks like this:
```
ParentID CustID
5 5
1 8
5 4
4 1
```
The result I get from the code above is:
```
ParentID CustID
4 1
5 4
5 5
```
What I want is just the last row of that result:
```
ParentID CustID
5 5
```
How do I just return the last record generated in the CTE (which would be highest level CustID)?
Also note that there are multiple unrelated CustID hierarchies in this table so I can't just do a SELECT \* FROM tblCustomer WHERE ParentID = CustID. I can't order by ParentID or CustID because the ID number is not related to where it is in the hierarchy. | If you just want want the highest recursion depth couldn't you do something like this?Then, when you actually query the CTE just look for the row with max(Depth)? Like so:
```
DECLARE @LookupID int
--Our test value
SET @LookupID = 1;
WITH cteLevelOne (ParentID, CustID, Depth) AS
(
SELECT a.ParentID, a.CustID, 1
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID, c.Depth + 1
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustID
)
select * from CTELevelone where Depth = (select max(Depth) from CTELevelone)
```
or, adapting what trevor suggests, this could be used with the same CTE:
```
select top 1 * from CTELevelone order by Depth desc
```
I don't think CustomerID was necessarily what you wanted to order by in the case you described, but I wasn't perfectly clear on the question either. |
35,322 | <p>I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough.</p>
<p>Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page? </p>
<p>I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior.</p>
<p>Note: As a test I added this to my global.asax and it didn't bypass forms auth:</p>
<pre><code>protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SkipAuthorization = true;
}
</code></pre>
<hr>
<p>@Dale and Andy</p>
<p>I'm using the AuthorizeAttributeFilter provided in MVC preview 4. This is returning an HttpUnauthorizedResult. This result is correctly setting the statusCode to 401. The problem, as i understand it, is that asp.net is intercepting the response (since its taged as a 401) and redirecting to the login page instead of just letting it go through. I want to bypass this interception for certain urls.</p>
| [
{
"answer_id": 35341,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": -1,
"selected": false,
"text": "<p>I did some googling and this is what I came up with:</p>\n\n<pre><code>\n HttpContext.Current.Response.StatusCode = 401;\... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] | I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough.
Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page?
I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior.
Note: As a test I added this to my global.asax and it didn't bypass forms auth:
```
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SkipAuthorization = true;
}
```
---
@Dale and Andy
I'm using the AuthorizeAttributeFilter provided in MVC preview 4. This is returning an HttpUnauthorizedResult. This result is correctly setting the statusCode to 401. The problem, as i understand it, is that asp.net is intercepting the response (since its taged as a 401) and redirecting to the login page instead of just letting it go through. I want to bypass this interception for certain urls. | Ok, I worked around this. I made a custom ActionResult (HttpForbiddenResult) and custom ActionFilter (NoFallBackAuthorize).
To avoid redirection, HttpForbiddenResult marks responses with status code 403. FormsAuthentication doesn't catch responses with this code so the login redirection is effectively skipped. The NoFallBackAuthorize filter checks to see if the user is authorized much like the, included, Authorize filter. It differs in that it returns HttpForbiddenResult when access is denied.
The HttpForbiddenResult is pretty trivial:
```
public class HttpForbiddenResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.HttpContext.Response.StatusCode = 0x193; // 403
}
}
```
It doesn't appear to be possible to skip the login page redirection in the FormsAuthenticationModule. |
35,333 | <p>I'm compiling a simple .c in visual c++ with Compile as C Code (/TC)
and i get this compiler error </p>
<blockquote>
<p>error C2143: syntax error : missing ';' before 'type'</p>
</blockquote>
<p>on a line that calls for a simple struct </p>
<pre><code> struct foo test;
</code></pre>
<p>same goes for using the typedef of the struct.</p>
<blockquote>
<p>error C2275: 'FOO' : illegal use of this type as an expression</p>
</blockquote>
| [
{
"answer_id": 35336,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>Did you accidentally omit a semicolon on a previous line? If the previous line is an <code>#include</code>, you might h... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] | I'm compiling a simple .c in visual c++ with Compile as C Code (/TC)
and i get this compiler error
>
> error C2143: syntax error : missing ';' before 'type'
>
>
>
on a line that calls for a simple struct
```
struct foo test;
```
same goes for using the typedef of the struct.
>
> error C2275: 'FOO' : illegal use of this type as an expression
>
>
> | I forgot that in C you have to declare all your variables before any code. |
35,407 | <p>I'm working on a system with four logical CPS (two dual-core CPUs if it matters). I'm using make to parallelize twelve trivially parallelizable tasks and doing it from cron.</p>
<p>The invocation looks like:</p>
<pre><code>make -k -j 4 -l 3.99 -C [dir] [12 targets]
</code></pre>
<p>The trouble I'm running into is that sometimes one job will finish but the next one won't startup even though it shouldn't be stopped by the load average limiter. Each target takes about four hours to complete and I'm wondering if this might be part of the problem.</p>
<p>Edit: Sometimes a target does fail but I use the -k option to have the rest of the make still run. I haven't noticed any correlation with jobs failing and the next job not starting.</p>
| [
{
"answer_id": 35447,
"author": "KannoN",
"author_id": 2897,
"author_profile": "https://Stackoverflow.com/users/2897",
"pm_score": 0,
"selected": false,
"text": "<p>Does make think one of the targets is failing? If so, it will stop the make after the running jobs finish. You can use -... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447/"
] | I'm working on a system with four logical CPS (two dual-core CPUs if it matters). I'm using make to parallelize twelve trivially parallelizable tasks and doing it from cron.
The invocation looks like:
```
make -k -j 4 -l 3.99 -C [dir] [12 targets]
```
The trouble I'm running into is that sometimes one job will finish but the next one won't startup even though it shouldn't be stopped by the load average limiter. Each target takes about four hours to complete and I'm wondering if this might be part of the problem.
Edit: Sometimes a target does fail but I use the -k option to have the rest of the make still run. I haven't noticed any correlation with jobs failing and the next job not starting. | I'd drop the '-l'
If all you plan to run the the system is this build I *think* the -j 4 does what you want.
Based on my memory, if you have anything else running (crond?), that can push the load average over 4.
[GNU make ref](http://sunsite.ualberta.ca/Documentation/Gnu/make-3.79/html_chapter/make_5.html#SEC47) |
35,420 | <p>I've had a tough time setting up my replication server. Is there any program (OS X, Windows, Linux, or PHP no problem) that lets me monitor and resolve replication issues? (btw, for those following, I've been on this issue <a href="https://stackoverflow.com/questions/8166/mysql-replication-if-i-dont-specify-any-databases-will-logbin-log-everything">here</a>, <a href="https://stackoverflow.com/questions/3798/full-complete-mysql-db-replication-ideas-what-do-people-do">here</a>, <a href="https://stackoverflow.com/questions/8365/mysql-administrator-backups-compatibility-mode-what-exactly-is-this-doing">here</a> and <a href="https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors">here</a>)</p>
<p>My production database is several megs in size and growing. Every time the database replication stops and the databases inevitably begin to slide out of sync i cringe. My last resync from dump took almost 4 hours roundtrip!</p>
<p>As always, even after sync, I run into this kind of show-stopping error:</p>
<pre><code>Error 'Duplicate entry '252440' for key 1' on query.
</code></pre>
<p>I would love it if there was some way to closely monitor whats going on and perhaps let the software deal with it. I'm even all ears for service companies which may help me monitor my data better. Or an alternate way to mirror altogether.</p>
<p><strong>Edit</strong>: going through my previous questions i found <a href="https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors#30889">this</a> which helps tremendously. I'm still all ears on the monitoring solution.</p>
| [
{
"answer_id": 35438,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 3,
"selected": true,
"text": "<p>To monitor the servers we use the free <a href=\"http://www.maatkit.org/tools.html\" rel=\"nofollow noreferrer\">... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] | I've had a tough time setting up my replication server. Is there any program (OS X, Windows, Linux, or PHP no problem) that lets me monitor and resolve replication issues? (btw, for those following, I've been on this issue [here](https://stackoverflow.com/questions/8166/mysql-replication-if-i-dont-specify-any-databases-will-logbin-log-everything), [here](https://stackoverflow.com/questions/3798/full-complete-mysql-db-replication-ideas-what-do-people-do), [here](https://stackoverflow.com/questions/8365/mysql-administrator-backups-compatibility-mode-what-exactly-is-this-doing) and [here](https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors))
My production database is several megs in size and growing. Every time the database replication stops and the databases inevitably begin to slide out of sync i cringe. My last resync from dump took almost 4 hours roundtrip!
As always, even after sync, I run into this kind of show-stopping error:
```
Error 'Duplicate entry '252440' for key 1' on query.
```
I would love it if there was some way to closely monitor whats going on and perhaps let the software deal with it. I'm even all ears for service companies which may help me monitor my data better. Or an alternate way to mirror altogether.
**Edit**: going through my previous questions i found [this](https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors#30889) which helps tremendously. I'm still all ears on the monitoring solution. | To monitor the servers we use the free [tools from Maatkit](http://www.maatkit.org/tools.html) ... simple, yet efficient.
The binary replication is available in 5.1, so I guess you've got some balls. We still use 5.0 and it works OK, but of course we had our share of issues with it.
We use a Master-Master replication with a MySql Proxy as a load-balancer in front, and to prevent it from having errors:
* we removed all unique indexes
* for the few cases where we really needed unique constraints we made sure we used REPLACE instead of INSERT (MySql Proxy can be used to guard for proper usage ... it can even rewrite your queries)
* scheduled scripts doing intensive reports are always accessing the same server (not the load-balancer) ... so that dangerous operations are replicated safely
Yeah, I know it sounds simple and stupid, but it solved 95% of all the problems we had. |
35,463 | <p>Some code that rounds up the division to demonstrate (C-syntax):</p>
<pre><code>#define SINT64 long long int
#define SINT32 long int
SINT64 divRound(SINT64 dividend, SINT64 divisor)
{
SINT32 quotient1 = dividend / divisor;
SINT32 modResult = dividend % divisor;
SINT32 multResult = modResult * 2;
SINT32 quotient2 = multResult / divisor;
SINT64 result = quotient1 + quotient2;
return ( result );
}
</code></pre>
<p>Now, if this were User-space we probably wouldn't even notice that our compiler is generating code for those operators (e.g. <code>divdi3()</code> for division). Chances are we link with <code>libgcc</code> without even knowing it. The problem is that Kernel-space is different (e.g. no <code>libgcc</code>). What to do?</p>
<p>Crawl Google for a while, notice that pretty much everyone addresses the unsigned variant:</p>
<pre><code>#define UINT64 long long int
#define UINT32 long int
UINT64 divRound(UINT64 dividend, UINT64 divisor)
{
UINT32 quotient1 = dividend / divisor;
UINT32 modResult = dividend % divisor;
UINT32 multResult = modResult * 2;
UINT32 quotient2 = multResult / divisor;
UINT64 result = quotient1 + quotient2;
return ( result );
}
</code></pre>
<p>I know how to fix this one: Override <code>udivdi3()</code> and <code>umoddi3()</code> with <code>do_div()</code> from <em>asm/div64.h</em>. Done right? Wrong. Signed is not the same as unsigned, <code>sdivdi3()</code> does not simply call <code>udivdi3()</code>, they are separate functions for a reason.</p>
<p>Have you solved this problem? Do you know of a library that will help me do this? I'm really stuck so whatever you might see here that I just don't right now would be really helpful.</p>
<p>Thanks,
Chad</p>
| [
{
"answer_id": 35468,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 0,
"selected": false,
"text": "<p><code>ldiv</code> ?</p>\n\n<p>Edit: reread title, so you might want to ignore this. Or not, depending on if it has an ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Some code that rounds up the division to demonstrate (C-syntax):
```
#define SINT64 long long int
#define SINT32 long int
SINT64 divRound(SINT64 dividend, SINT64 divisor)
{
SINT32 quotient1 = dividend / divisor;
SINT32 modResult = dividend % divisor;
SINT32 multResult = modResult * 2;
SINT32 quotient2 = multResult / divisor;
SINT64 result = quotient1 + quotient2;
return ( result );
}
```
Now, if this were User-space we probably wouldn't even notice that our compiler is generating code for those operators (e.g. `divdi3()` for division). Chances are we link with `libgcc` without even knowing it. The problem is that Kernel-space is different (e.g. no `libgcc`). What to do?
Crawl Google for a while, notice that pretty much everyone addresses the unsigned variant:
```
#define UINT64 long long int
#define UINT32 long int
UINT64 divRound(UINT64 dividend, UINT64 divisor)
{
UINT32 quotient1 = dividend / divisor;
UINT32 modResult = dividend % divisor;
UINT32 multResult = modResult * 2;
UINT32 quotient2 = multResult / divisor;
UINT64 result = quotient1 + quotient2;
return ( result );
}
```
I know how to fix this one: Override `udivdi3()` and `umoddi3()` with `do_div()` from *asm/div64.h*. Done right? Wrong. Signed is not the same as unsigned, `sdivdi3()` does not simply call `udivdi3()`, they are separate functions for a reason.
Have you solved this problem? Do you know of a library that will help me do this? I'm really stuck so whatever you might see here that I just don't right now would be really helpful.
Thanks,
Chad | This functionality is introduced in [/linux/lib/div64.c](http://lxr.linux.no/linux+v2.6.22/lib/div64.c) as early as kernel v2.6.22. |
35,480 | <p>I'm currently working on a large implementation of Class::DBI for an existing database structure, and am running into a problem with clearing the cache from Class::DBI. This is a mod_perl implementation, so an instance of a class can be quite old between times that it is accessed.
From the man pages I found two options:</p>
<pre><code>Music::DBI->clear_object_index();
</code></pre>
<p>And:</p>
<pre><code>Music::Artist->purge_object_index_every(2000);
</code></pre>
<p>Now, when I add clear_object_index() to the DESTROY method, it seems to run, but doesn't actually empty the cache. I am able to manually change the database, re-run the request, and it is still the old version.
purge_object_index_every says that it clears the index every n requests. Setting this to "1" or "0", seems to clear the index... sometimes. I'd expect one of those two to work, but for some reason it doesn't do it every time. More like 1 in 5 times.</p>
<p>Any suggestions for clearing this out?</p>
| [
{
"answer_id": 35529,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 4,
"selected": true,
"text": "<p>The \"<a href=\"http://wiki.class-dbi.com/wiki/Common_problems\" rel=\"nofollow noreferrer\">common problems</a>\" page... | 2008/08/29 | [
"https://Stackoverflow.com/questions/35480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3421/"
] | I'm currently working on a large implementation of Class::DBI for an existing database structure, and am running into a problem with clearing the cache from Class::DBI. This is a mod\_perl implementation, so an instance of a class can be quite old between times that it is accessed.
From the man pages I found two options:
```
Music::DBI->clear_object_index();
```
And:
```
Music::Artist->purge_object_index_every(2000);
```
Now, when I add clear\_object\_index() to the DESTROY method, it seems to run, but doesn't actually empty the cache. I am able to manually change the database, re-run the request, and it is still the old version.
purge\_object\_index\_every says that it clears the index every n requests. Setting this to "1" or "0", seems to clear the index... sometimes. I'd expect one of those two to work, but for some reason it doesn't do it every time. More like 1 in 5 times.
Any suggestions for clearing this out? | The "[common problems](http://wiki.class-dbi.com/wiki/Common_problems)" page on the [Class::DBI wiki](http://wiki.class-dbi.com/wiki) has a [section](http://wiki.class-dbi.com/wiki/Common_problems#Old_data_due_to_object_index) on this subject. The simplest solution is to disable the live object index entirely using:
```
$Class::DBI::Weaken_Is_Available = 0;
``` |
35,485 | <p>I want to be able to get an estimate of how much code & static data is used by my C++ program?</p>
<p>Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?</p>
<p>Will objdump & readelf help?</p>
| [
{
"answer_id": 35508,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "<p><code>readelf</code> will indeed help. You can use the <code>-S</code> option; that will show the sizes of all sections. <... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] | I want to be able to get an estimate of how much code & static data is used by my C++ program?
Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?
Will objdump & readelf help? | "size" is the traditional tool. "readelf" has a lot of options.
```
$ size /bin/sh
text data bss dec hex filename
712739 37524 21832 772095 bc7ff /bin/sh
``` |
35,491 | <p>I want to be able to get an estimate of how much code & static data is used by my C++ program?</p>
<p>Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?</p>
<p>Will otool help?</p>
| [
{
"answer_id": 35583,
"author": "Mike Haboustak",
"author_id": 2146,
"author_profile": "https://Stackoverflow.com/users/2146",
"pm_score": 2,
"selected": false,
"text": "<p>I think otool can help. Specifically, \"otool -s {segment} {section}\" should print out the details. I'm not sure i... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] | I want to be able to get an estimate of how much code & static data is used by my C++ program?
Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?
Will otool help? | * "size" is the traditional tool and works on all unix flavors.
* "otool" has a bit finer grain control and has a lot of options.
.
```
$ size python
__TEXT __DATA __OBJC others dec hex
860160 159744 0 2453504 3473408 350000
``` |
35,507 | <p>I have been working with Struts for some time, but for a project I am finishing I was asked to separate Templates (velocity .vm files), configs (struts.xml, persistence.xml) from main WAR file.</p>
<p>I have all in default structure like: </p>
<pre>
application
|-- <i><b>META-INF</b></i> -- Some configs are here
|-- <i><b>WEB-INF</b></i> -- others here
| |-- classes
| | |-- META-INF
| | `-- mypackage
| | `-- class-files
| `-- lib
|-- css
`-- <i><b>tpl</b></i> -- Template dir to be relocated
</pre>
<p>And I apparently can't find documentation about how to setup (probably in struts.xml) where my templates go, and where config files will be.</p>
<p>I think I will have to use configurations on the application server too (I am using Jetty 5.1.14).</p>
<p>So, any lights on how to configure it ? </p>
<p>Thanks</p>
<hr>
<p>Well, the whole thing about changing templates place is to put the templates in a designer accessible area, so any modification needed, the designer can load them to his/her computer, edit, and upload it again. I think this is a common scenario. So, probably I am missing something in my research. Maybe I am focusing in configuring it on the wrong place ... Any thoughts ?</p>
| [
{
"answer_id": 35867,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 0,
"selected": false,
"text": "<p>For <em>persistence.xml</em>, specifically, you can put a persistence unit in a separate JAR, which you can deploy se... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] | I have been working with Struts for some time, but for a project I am finishing I was asked to separate Templates (velocity .vm files), configs (struts.xml, persistence.xml) from main WAR file.
I have all in default structure like:
```
application
|-- ***META-INF*** -- Some configs are here
|-- ***WEB-INF*** -- others here
| |-- classes
| | |-- META-INF
| | `-- mypackage
| | `-- class-files
| `-- lib
|-- css
`-- ***tpl*** -- Template dir to be relocated
```
And I apparently can't find documentation about how to setup (probably in struts.xml) where my templates go, and where config files will be.
I think I will have to use configurations on the application server too (I am using Jetty 5.1.14).
So, any lights on how to configure it ?
Thanks
---
Well, the whole thing about changing templates place is to put the templates in a designer accessible area, so any modification needed, the designer can load them to his/her computer, edit, and upload it again. I think this is a common scenario. So, probably I am missing something in my research. Maybe I am focusing in configuring it on the wrong place ... Any thoughts ? | If I understood your question about Struts config files right, they are specified in web.xml. Find the Struts servlet config param. The param-value can be a list of comma separated list of XML files to load. Eg:
```
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
WEB-INF/config/struts-config.xml,
WEB-INF/config/struts-config-stuff.xml,
WEB-INF/config/struts-config-good.xml,
WEB-INF/config/struts-config-bad.xml,
WEB-INF/config/struts-config-ugly.xml
</param-value>
</init-param>
...
</servlet>
```
See this [Struts guide](http://struts.apache.org/1.x/userGuide/configuration.html) under 5.3.2. And yes, this applies to 2.x also. |
35,538 | <p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
| [
{
"answer_id": 35543,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "<p>XHTML is easy, use <a href=\"http://lxml.de/validation.html\" rel=\"noreferrer\">lxml</a>.</p>\n\n<pre><code>from lxm... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app. | XHTML is easy, use [lxml](http://lxml.de/validation.html).
```
from lxml import etree
from StringIO import StringIO
etree.parse(StringIO(html), etree.HTMLParser(recover=False))
```
HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as [nsgmls](http://www.jclark.com/sp/) or [OpenJade](http://openjade.sourceforge.net/), and then parse their output. |
35,548 | <p>I use this tool called <a href="http://www.lazycplusplus.com/" rel="nofollow noreferrer">Lazy C++</a> which breaks a single C++ .lzz file into a .h and .cpp file. I want <a href="http://makepp.sourceforge.net/" rel="nofollow noreferrer">Makepp</a> to expect both of these files to exist after my rule for building .lzz files, but I'm not sure how to put two targets into a single build line.</p>
| [
{
"answer_id": 35592,
"author": "Tynan",
"author_id": 3548,
"author_profile": "https://Stackoverflow.com/users/3548",
"pm_score": 3,
"selected": true,
"text": "<p>I've never used Makepp personally, but since it's a drop-in replacement for GNU Make, you should be able to do something like... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | I use this tool called [Lazy C++](http://www.lazycplusplus.com/) which breaks a single C++ .lzz file into a .h and .cpp file. I want [Makepp](http://makepp.sourceforge.net/) to expect both of these files to exist after my rule for building .lzz files, but I'm not sure how to put two targets into a single build line. | I've never used Makepp personally, but since it's a drop-in replacement for GNU Make, you should be able to do something like:
```
build: foo.h foo.cpp
g++ $(CFLAGS) foo.cpp -o $(LFLAGS) foo
foo.h foo.cpp: foo.lzz
lzz foo.lzz
```
Also not sure about the lzz invocation there, but that should help. You can read more about this at <http://theory.uwinnipeg.ca/gnu/make/make_37.html>. |
35,551 | <p>In a project I'm working on FxCop shows me lots of (and I mean more than 400) errors on the InitializeComponent() methods generated by the Windows Forms designer. Most of those errors are just the assignment of the Text property of labels.</p>
<p>I'd like to suppress those methods in source, so I copied the suppression code generated by FxCop into AssemblyInfo.cs, but it doesn't work.</p>
<p>This is the attribute that FxCop copied to the clipboard.</p>
<pre><code>[module: SuppressMessage("Microsoft.Globalization",
"CA1303:DoNotPassLiteralsAsLocalizedParameters",
Scope = "member",
Target = "WindowsClient.MainForm.InitializeComponent():System.Void",
MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
</code></pre>
<p>Anyone knows the correct attribute to suppress this messages?</p>
<p>PS: I'm using Visual Studio 2005, C#, FxCop 1.36 beta.</p>
| [
{
"answer_id": 35556,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": true,
"text": "<p>You've probably got the right code, but you also need to add CODE_ANALYSIS as a precompiler defined symbol in the proje... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
] | In a project I'm working on FxCop shows me lots of (and I mean more than 400) errors on the InitializeComponent() methods generated by the Windows Forms designer. Most of those errors are just the assignment of the Text property of labels.
I'd like to suppress those methods in source, so I copied the suppression code generated by FxCop into AssemblyInfo.cs, but it doesn't work.
This is the attribute that FxCop copied to the clipboard.
```
[module: SuppressMessage("Microsoft.Globalization",
"CA1303:DoNotPassLiteralsAsLocalizedParameters",
Scope = "member",
Target = "WindowsClient.MainForm.InitializeComponent():System.Void",
MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
```
Anyone knows the correct attribute to suppress this messages?
PS: I'm using Visual Studio 2005, C#, FxCop 1.36 beta. | You've probably got the right code, but you also need to add CODE\_ANALYSIS as a precompiler defined symbol in the project properties. I think those SuppressMessage attributes are only left in the compiled binaries if CODE\_ANALYSIS is defined. |
35,699 | <p>I'm trying to make a two-column page using a div-based layout (no tables please!). Problem is, I can't grow the left div to match the height of the right one. My right div typically has a lot of content. </p>
<p>Here's a paired down example of my template to illustrate the problem.</p>
<pre><code><div style="float:left; width: 150px; border: 1px solid;">
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
<li>nav4</li>
</ul>
</div>
<div style="float:left; width: 250px">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
....
</div>
</code></pre>
| [
{
"answer_id": 35711,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 3,
"selected": false,
"text": "<p>Your simplest answer lies in the next version of css (3), which currently no browser supports.</p>\n\n<p>For now y... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] | I'm trying to make a two-column page using a div-based layout (no tables please!). Problem is, I can't grow the left div to match the height of the right one. My right div typically has a lot of content.
Here's a paired down example of my template to illustrate the problem.
```
<div style="float:left; width: 150px; border: 1px solid;">
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
<li>nav4</li>
</ul>
</div>
<div style="float:left; width: 250px">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
....
</div>
``` | Use jQuery for this problem; just call this function in your ready function:
```
function setHeight(){
var height = $(document).height(); //optionally, subtract some from the height
$("#leftDiv").css("height", height + "px");
}
``` |
35,743 | <p>According to <a href="http://msdn.microsoft.com/en-us/library/bb386454.aspx" rel="noreferrer">Microsoft</a> the FileUpload control is not compatible with an AJAX UpdatePanel. </p>
<p>I am aware that a PostBackTrigger can be added to the submit button of the form like this:</p>
<pre><code><Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</code></pre>
<p>The problem is that this forces the form to perform a full post-back which voids out the whole point of using the UpdatePanel in the first place. Is there a workaround to this issue that does not cause the whole page to refresh?</p>
| [
{
"answer_id": 35754,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 3,
"selected": false,
"text": "<p>I know of a third party component that can do that. It's called <a href=\"http://swfupload.org/\" rel=\"noreferrer\">\"<em>swfupl... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3677/"
] | According to [Microsoft](http://msdn.microsoft.com/en-us/library/bb386454.aspx) the FileUpload control is not compatible with an AJAX UpdatePanel.
I am aware that a PostBackTrigger can be added to the submit button of the form like this:
```
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
```
The problem is that this forces the form to perform a full post-back which voids out the whole point of using the UpdatePanel in the first place. Is there a workaround to this issue that does not cause the whole page to refresh? | I know of a third party component that can do that. It's called ["*swfupload*"](http://swfupload.org/) and is free to use and open source, and uses javascript and flash to do the magic.
here is a list of the features they offer:
(from their site)
>
> * Upload multiple files at once by ctrl/shift-selecting in dialog
> * Javascript callbacks on all events
> * Get file information before upload starts
> * Style upload elements with XHTML and css
> * Display information while files are uploading using HTML
> * No page reloads necessary
> * Works on all platforms/browsers that has Flash support.
> * Degrades gracefully to normal HTML upload form if Flash or javascript is
> unavailable
> * Control filesize before upload starts
> * Only display chosen filetypes in dialog
> * Queue uploads, remove/add files before starting upload
>
>
>
They also have a [demo area](http://www.swfupload.org/documentation/demonstration) where you can play around with their control. That way you can make sure it is exactly what you want.
We used it in one of our projects and it has never failed us so far, so I think this is a safe bet.
oh and here is the download page: <http://code.google.com/p/swfupload/> |
35,782 | <p>I need to produce a calculation trace file containing tabular data showing intermediate results. I am currently using a combination of the standard ascii pipe symbols (|) and dashes (-) to draw the table lines:</p>
<p>E.g. </p>
<pre><code>Numerator | Denominator | Result
----------|-------------|-------
6 | 2 | 3
10 | 5 | 2
</code></pre>
<p>Are there any unicode characters that could be used to produce a more professional looking table?</p>
<p>(The file must be a raw text format and cannot use HTML or any other markup)</p>
<p><strong>Edit:</strong> I've added an example of what the table now looks like having taken the suggestion on board and used the unicode box drawing characters:</p>
<pre><code>Numerator │ Denominator │ Result
──────────┼─────────────┼───────
6 │ 2 │ 3
10 │ 5 │ 2
</code></pre>
| [
{
"answer_id": 35784,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": true,
"text": "<p>There are <a href=\"http://www.unicode.org/charts/symbols.html\" rel=\"nofollow noreferrer\">Unicode box drawing charact... | 2008/08/30 | [
"https://Stackoverflow.com/questions/35782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1131/"
] | I need to produce a calculation trace file containing tabular data showing intermediate results. I am currently using a combination of the standard ascii pipe symbols (|) and dashes (-) to draw the table lines:
E.g.
```
Numerator | Denominator | Result
----------|-------------|-------
6 | 2 | 3
10 | 5 | 2
```
Are there any unicode characters that could be used to produce a more professional looking table?
(The file must be a raw text format and cannot use HTML or any other markup)
**Edit:** I've added an example of what the table now looks like having taken the suggestion on board and used the unicode box drawing characters:
```
Numerator │ Denominator │ Result
──────────┼─────────────┼───────
6 │ 2 │ 3
10 │ 5 │ 2
``` | There are [Unicode box drawing characters](http://www.unicode.org/charts/symbols.html) (look for Box Drawing under Geometrical Symbols - the [chart itself](http://www.unicode.org/charts/PDF/U2500.pdf) is a PDF). I don't have any idea how widely supported those characters are, though. |