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
|
---|---|---|---|---|---|---|
118,261 | <p>E.g. we this code in the asp.net form codebihind:</p>
<pre><code>private void btnSendEmails_OnClick()
{
Send100000EmailsAndWaitForReplies();
}
</code></pre>
<p>This code execution will be killed by the timeout reason.
For resolving the problem I'd like to see something like this:</p>
<pre><code>private void btnSendEmails_OnClick()
{
var taskId = AsyncTask.Run( () => Send100000EmailsAndWaitForReplies() );
// Store taskId for future task execution status checking.
}
</code></pre>
<p>And this method will be executed for some way outside the w3wp.exe process within a special enveronment.</p>
<p>Does anybody know a framework/toolset for resolving this kind of issues?</p>
<p><strong>Update:</strong> The emails sending method is only an example of what I mean. In fact, I could have a lot of functionality need to be executed outside the asp.net working process. </p>
<p>E.g. this point is very important for an application which aggregates data from a couple of 3rd party services, do something with it and send it back to another service.</p>
| [
{
"answer_id": 118278,
"author": "madcolor",
"author_id": 13954,
"author_profile": "https://Stackoverflow.com/users/13954",
"pm_score": 0,
"selected": false,
"text": "<p>One option is to have the task execute a certain amount of emails, then Response.Redirect back to itself and repeat until all of your emails have been sent.</p>\n"
},
{
"answer_id": 118285,
"author": "JPrescottSanders",
"author_id": 19444,
"author_profile": "https://Stackoverflow.com/users/19444",
"pm_score": 1,
"selected": false,
"text": "<p>I can think of two possible paths I'd head down:</p>\n\n<ol>\n<li>You could create a windows service that hosted a remoted object and have your web app call that remoted object to ensure that the method executed outside of the IIS process space.</li>\n<li>You could set up a DB or MSMQ to which you would log a request. Your web app could then monitor the status of the request to subsequently notify the user of it's completion. I would envision a service completeing the requests.</li>\n</ol>\n"
},
{
"answer_id": 118290,
"author": "Mike",
"author_id": 1115144,
"author_profile": "https://Stackoverflow.com/users/1115144",
"pm_score": -1,
"selected": false,
"text": "<p>Server.ScriptTimeout = 360000000;</p>\n"
},
{
"answer_id": 118293,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>You could have the functionality that sends the mails run as a service. Submit the request to it, and let it process it. Query every once in a while for its status. If you have control of the server you can install a windows service which would probably be ideal for optimal processing and lifetime management.</p>\n"
},
{
"answer_id": 118295,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 0,
"selected": false,
"text": "<p>ASP.NET 2.0+ supports the concept of Asynchronous pages. Add the page directive Async=\"true\" to your page. </p>\n\n<p>Then in Page_Load, use the BeginEventHandler and EndEventHandler delegates to have code executed asynchronously in the corresponding \"handlers\".</p>\n\n<pre><code><%@ Page Language=\"C#\" Async=\"true\" %>\n<script runat=\"server\">\n\n protected void Page_Load(object sender, EventArgs e)\n {\n BeginEventHandler begin = new BeginEventHandler(BeginMethod);\n EndEventHandler end = new EndEventHandler(EndMethod);\n\n AddOnPreRenderCompleteAsync(begin, end);\n }\n</script>\n</code></pre>\n"
},
{
"answer_id": 118297,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 3,
"selected": false,
"text": "<p>This has been discussed as a part of other questions:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/50221/multithreading-in-aspnet#50377\">Multithreading in asp.net</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/57845/backgroundworker-thread-in-aspnet\">BackgroundWorker thread in ASP.NET</a></p>\n\n<p>There is no good way to do this. You don't want any long running processes in the ASP.NET worker process, since it might recycle before you are done.</p>\n\n<p>Write a Windows Service to run in the background that does the work for you. Drop messages into MSMQ to initiate tasks. Then they can run as long as they want. </p>\n"
},
{
"answer_id": 6149911,
"author": "sigi",
"author_id": 277358,
"author_profile": "https://Stackoverflow.com/users/277358",
"pm_score": 0,
"selected": false,
"text": "<p>It can be often impossible to run a custom windows service when your site is hosted by a shared hosting provider. Running a separate thread that you put to sleep to run in regular intervals can be inconsistent since IIS will tend to recycle your threads every now and then, and even setting the script-execution property in cofig file or through code will not enshure that your thread doesnt get killed off and recycled. </p>\n\n<p>I came accross a cache expiration based method, which given the methods available on a shared hosting service might be the safest, i.e. most consistent option to go for. This article explains it quite well and provides a job-queue class to help manage your scheduled jobs at the end of the article, see it here - <a href=\"http://www.codeproject.com/KB/aspnet/ASPNETService.aspx\" rel=\"nofollow\">http://www.codeproject.com/KB/aspnet/ASPNETService.aspx</a></p>\n"
},
{
"answer_id": 24116283,
"author": "odinserj",
"author_id": 1317575,
"author_profile": "https://Stackoverflow.com/users/1317575",
"pm_score": 1,
"selected": false,
"text": "<p>ASP.NET hosting environment is very dangerous for any long-running processes, either CPU or I/O consuming, because sudden AppDomain unloads may happen.</p>\n\n<p>If you want to perform background tasks outside of request processing pipeline, consider using <a href=\"http://hangfire.io\" rel=\"nofollow\">http://hangfire.io</a>, it handles all difficulties and risks of background processing for you, without the requirement to install additional windows service (but it is possible to use them, when the time come). There is a <a href=\"http://docs.hangfire.io/en/latest/tutorials/send-email.html\" rel=\"nofollow\">mail sending tutorial</a> either.</p>\n"
},
{
"answer_id": 24148829,
"author": "RickAndMSFT",
"author_id": 502537,
"author_profile": "https://Stackoverflow.com/users/502537",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li><a href=\"http://blogs.msdn.com/b/webdev/archive/2014/06/04/queuebackgroundworkitem-to-reliably-schedule-and-run-long-background-process-in-asp-net.aspx\" rel=\"nofollow\">QueueBackgroundWorkItem</a> My sample shows sending email.</li>\n<li><a href=\"http://hangfire.io/\" rel=\"nofollow\">HangFire</a> Open source project works on shared hosting.</li>\n<li>On Azure, you can use <a href=\"http://www.asp.net/aspnet/overview/developing-apps-with-windows-azure/azure-webjobs-recommended-resources\" rel=\"nofollow\">WebJobs</a>.</li>\n<li>On Azure, <a href=\"http://azure.microsoft.com/en-us/documentation/articles/cloud-services-dotnet-get-started/\" rel=\"nofollow\">Cloud services</a></li>\n</ol>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/118261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9198/"
]
| E.g. we this code in the asp.net form codebihind:
```
private void btnSendEmails_OnClick()
{
Send100000EmailsAndWaitForReplies();
}
```
This code execution will be killed by the timeout reason.
For resolving the problem I'd like to see something like this:
```
private void btnSendEmails_OnClick()
{
var taskId = AsyncTask.Run( () => Send100000EmailsAndWaitForReplies() );
// Store taskId for future task execution status checking.
}
```
And this method will be executed for some way outside the w3wp.exe process within a special enveronment.
Does anybody know a framework/toolset for resolving this kind of issues?
**Update:** The emails sending method is only an example of what I mean. In fact, I could have a lot of functionality need to be executed outside the asp.net working process.
E.g. this point is very important for an application which aggregates data from a couple of 3rd party services, do something with it and send it back to another service. | 1. [QueueBackgroundWorkItem](http://blogs.msdn.com/b/webdev/archive/2014/06/04/queuebackgroundworkitem-to-reliably-schedule-and-run-long-background-process-in-asp-net.aspx) My sample shows sending email.
2. [HangFire](http://hangfire.io/) Open source project works on shared hosting.
3. On Azure, you can use [WebJobs](http://www.asp.net/aspnet/overview/developing-apps-with-windows-azure/azure-webjobs-recommended-resources).
4. On Azure, [Cloud services](http://azure.microsoft.com/en-us/documentation/articles/cloud-services-dotnet-get-started/) |
118,272 | <p>(Java question)</p>
<p>If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class?</p>
<p>How can I avoid this? </p>
<p>Here is an example:</p>
<pre><code>public class Outer {
private Other o;
private Inner i;
public Outer() {
o = new Other();
i = new Inner() {
public void doSomething() {
o.foo();
}
};
}
}
</code></pre>
| [
{
"answer_id": 118317,
"author": "William",
"author_id": 9193,
"author_profile": "https://Stackoverflow.com/users/9193",
"pm_score": 0,
"selected": false,
"text": "<p>The syntax you're using in the example is a little off there is no declaration of the class or interface Inner. But there isn't anything wrong with the concept of the example. In Java it will work fine.</p>\n\n<p>I'm not sure what you're doing here, but you may want to consider a more simple design for maintainability etc.</p>\n\n<p>It's a common pattern for anonymous event handlers to reference elements of their parent class, so no reason to avoid it if that's the case, that's how Java was designed instead of having function pointers.</p>\n"
},
{
"answer_id": 118483,
"author": "killdash10",
"author_id": 7621,
"author_profile": "https://Stackoverflow.com/users/7621",
"pm_score": 0,
"selected": false,
"text": "<p>(Not sure if this is what you are asking...)</p>\n\n<p>At runtime, the inner class has an implicit reference to the instance of the outer class it belongs to. So whenever you pass the inner class instance around, you are also passing the outer class instance around.<br>\nYou can avoid that by declaring the inner class as \"static\", but that means that the inner class can't access member variables of the outer class. So in that case if you want to access a member of the outer class, you need to pass it explicitly to the inner class (using a setter or using the constructor of the inner class).</p>\n"
},
{
"answer_id": 118669,
"author": "helios",
"author_id": 9686,
"author_profile": "https://Stackoverflow.com/users/9686",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Static vs instance class:</strong> If you declare the inner class as static then the instances of the inner class doesn't have any reference to the outer class. If it's not satic then your inner object efectivelly points to the outer object that created it (it has an implicit reference, in fact, if you use reflection over its constructors you'll see an extra parameter for receiving the outer instance).</p>\n\n<p><strong>Inner instance points outer instance:</strong> Circular reference is in case each instance points the other one. A lot of times you use inner classes for elegantly implementing some interface and accessing private fields while not implementing the interface with the outer class. It does mean inner instance points outer instance but doesn't mean the opposite. Not necesary a circular reference.</p>\n\n<p><strong>Closing the circle:</strong> Anyway there's nothing wrong with circular referencing in Java. Objects work nicely and when they're not more referenced they're garbage collected. It doesn't matter if they point each other.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/118272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18445/"
]
| (Java question)
If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class?
How can I avoid this?
Here is an example:
```
public class Outer {
private Other o;
private Inner i;
public Outer() {
o = new Other();
i = new Inner() {
public void doSomething() {
o.foo();
}
};
}
}
``` | **Static vs instance class:** If you declare the inner class as static then the instances of the inner class doesn't have any reference to the outer class. If it's not satic then your inner object efectivelly points to the outer object that created it (it has an implicit reference, in fact, if you use reflection over its constructors you'll see an extra parameter for receiving the outer instance).
**Inner instance points outer instance:** Circular reference is in case each instance points the other one. A lot of times you use inner classes for elegantly implementing some interface and accessing private fields while not implementing the interface with the outer class. It does mean inner instance points outer instance but doesn't mean the opposite. Not necesary a circular reference.
**Closing the circle:** Anyway there's nothing wrong with circular referencing in Java. Objects work nicely and when they're not more referenced they're garbage collected. It doesn't matter if they point each other. |
118,280 | <p>I thought I had seen a bug report about this on the jQuery site, but now I cannot find it. I'm trying to resize a dialog in IE6. But when the element is resized, the content and title bar don't resize down. They will resize up if the dialog is made larger, however. The result is that the close button ends up being cut off and the content is clipped if the user resize the dialog to be smaller. </p>
<p>I've tried handling the resizeStop event and manually resizing the content and titlebar, but this can gave me weird results. The sizes and positions of elements in the content area were still off. Also, even though I resize the title bar, the close button still doesn't move back into view. Any ideas? If this is a bug in jQuery-ui, does anyone know a good workaround?</p>
<pre><code><html>
<head>
<title>Example of IE6 resize issue</title>
<link rel="stylesheet" type="text/css" href="http://ui.jquery.com/repository/latest/themes/flora/flora.all.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
google.setOnLoadCallback(
function() {
$(document).ready(function()
{
$("#main-dialog").dialog();
});
});
</script>
</head>
<body>
<div id="main-dialog">
This is just some simple content that will fill the dialog. This example is
sufficient to reproduce the problem in IE6. It does not seem to occur in IE7
or FF. I haven't tried with Opera or Safari.
</div>
</body>
</html>
</code></pre>
| [
{
"answer_id": 120050,
"author": "Dave Richardson",
"author_id": 3392,
"author_profile": "https://Stackoverflow.com/users/3392",
"pm_score": 0,
"selected": false,
"text": "<p>The css may be a factor. Could you change your example so we can see your stylesheet? I've updated the example so that it doesn't depend on having jQuery locally.</p>\n\n<pre><code><html>\n<head>\n<title>Example of IE6 resize issue</title>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"?.css\" />\n<script src=\"http://www.google.com/jsapi\"></script>\n<script>\n google.load(\"jquery\", \"1\");\n google.load(\"jqueryui\", \"1\");\n\n google.setOnLoadCallback(\n function() {\n $(document).ready(function()\n {\n $(\"#main-dialog\").dialog();\n });\n });\n</script>\n</head>\n<body>\n<div id=\"main-dialog\">\n This is just some simple content that will fill the dialog. This example is\n sufficient to reproduce the problem in IE6. It does not seem to occur in IE7\n or FF. I haven't tried with Opera or Safari.\n</div>\n</body> \n</html>\n</code></pre>\n"
},
{
"answer_id": 130100,
"author": "Harry Steinhilber",
"author_id": 6118,
"author_profile": "https://Stackoverflow.com/users/6118",
"pm_score": 3,
"selected": true,
"text": "<p>I was able to come up with a solution. If you add the style <strong>overflow: hidden</strong> to the dialog container div element (which has the css class .ui-dialog-container applied to it), then everything resizes correctly. All I did was add a css rule as follows to the flora theme:</p>\n\n<pre><code>.ui-dialog .ui-dialog-container {\n overflow: hidden;\n}\n</code></pre>\n\n<p>It could also be corrected by executing the following:</p>\n\n<pre><code>if ($.browser.msie && $.browser.version == 6)\n{\n $(\".ui-dialog-container\").css({ overflow: 'hidden' });\n} \n</code></pre>\n\n<p>This corrected the issue I was seeing under IE6 and has not introduced any problems in FireFox.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/118280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6118/"
]
| I thought I had seen a bug report about this on the jQuery site, but now I cannot find it. I'm trying to resize a dialog in IE6. But when the element is resized, the content and title bar don't resize down. They will resize up if the dialog is made larger, however. The result is that the close button ends up being cut off and the content is clipped if the user resize the dialog to be smaller.
I've tried handling the resizeStop event and manually resizing the content and titlebar, but this can gave me weird results. The sizes and positions of elements in the content area were still off. Also, even though I resize the title bar, the close button still doesn't move back into view. Any ideas? If this is a bug in jQuery-ui, does anyone know a good workaround?
```
<html>
<head>
<title>Example of IE6 resize issue</title>
<link rel="stylesheet" type="text/css" href="http://ui.jquery.com/repository/latest/themes/flora/flora.all.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
google.setOnLoadCallback(
function() {
$(document).ready(function()
{
$("#main-dialog").dialog();
});
});
</script>
</head>
<body>
<div id="main-dialog">
This is just some simple content that will fill the dialog. This example is
sufficient to reproduce the problem in IE6. It does not seem to occur in IE7
or FF. I haven't tried with Opera or Safari.
</div>
</body>
</html>
``` | I was able to come up with a solution. If you add the style **overflow: hidden** to the dialog container div element (which has the css class .ui-dialog-container applied to it), then everything resizes correctly. All I did was add a css rule as follows to the flora theme:
```
.ui-dialog .ui-dialog-container {
overflow: hidden;
}
```
It could also be corrected by executing the following:
```
if ($.browser.msie && $.browser.version == 6)
{
$(".ui-dialog-container").css({ overflow: 'hidden' });
}
```
This corrected the issue I was seeing under IE6 and has not introduced any problems in FireFox. |
118,289 | <p>I have a string with possible command line arguments (using an Read-Eval-Print-Loop program) and I want it to be parsed similar to the command line arguments when passed to Getopt::Long.</p>
<p>To elaborate:</p>
<p>I have a string</p>
<pre><code>$str = '--infile /tmp/infile_location --outfile /tmp/outfile'
</code></pre>
<p>I want it to be parsed by GetOptions so that it is easier for me to add new options.</p>
<p>One workaround I could think of is to split the string on whitespace and replace @ARGV with new array and then call GetOptions. something like ...</p>
<pre><code>my @arg_arr = split (/\s/, $input_line);
# This is done so that GetOptions reads these new arguments
@ARGV = @arg_arr;
print "ARGV is : @ARGV\n";
GetOptions (
'infile=s' => \$infile,
'outfile=s' => \$outfile
);
</code></pre>
<p>Is there any good/better way?</p>
| [
{
"answer_id": 118339,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of splitting on whitespace, use the built-in glob function. In addition to splitting on whitespace, that will do the standard command line expansions, then return a list. (For instance * would give a list of files, etc.) I would also recommend local-izing @ARG on general principle.</p>\n\n<p><strike>Other than that, that's the only way you can do it without rewriting GetOptions.</strike> (Clearly I need to read the documentation more carefully.)</p>\n"
},
{
"answer_id": 118365,
"author": "Drew Stephens",
"author_id": 17339,
"author_profile": "https://Stackoverflow.com/users/17339",
"pm_score": 5,
"selected": true,
"text": "<p>Check out the section <a href=\"http://perldoc.perl.org/Getopt/Long.html#Parsing-options-from-an-arbitrary-string\" rel=\"nofollow noreferrer\">parsing options from an arbitrary string</a> in the <a href=\"http://perldoc.perl.org/Getopt/Long.html\" rel=\"nofollow noreferrer\">man page for Getopt::Long</a>, I think it does exactly what you're looking for.</p>\n"
},
{
"answer_id": 118392,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 3,
"selected": false,
"text": "<p>Wow!!!</p>\n\n<p>I think I can use both of bentilly and dinomite's answers and do the following:</p>\n\n<ul>\n<li>use glob to perform standard command line expansions</li>\n<li>pass the array after glob to GetOptionsFromArray method of the GetOpt::Long (see <a href=\"http://search.cpan.org/~jv/Getopt-Long-2.37/lib/Getopt/Long.pm#Parsing_options_from_an_arbitrary_array\" rel=\"nofollow noreferrer\">here</a>)</li>\n</ul>\n\n<p>Code may look something like ...</p>\n\n<pre><code>GetOptionsFromArray ([glob ($input_line)]);\n</code></pre>\n\n<p>And that is only one line .. cool (I know I have to do some error checking etc) .. but its cool ... </p>\n"
},
{
"answer_id": 119551,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "<p>When you use Getopt::Long on something other than user input, be aware that some features are different based on the POSIXLY_CORRECT environment variable. You can override this with the appropriate call to Configure.</p>\n\n<p><a href=\"http://everything2.com/node/877243\" rel=\"nofollow noreferrer\">Obligatory POSIXLY_CORRECT anecdote</a>.</p>\n"
},
{
"answer_id": 120320,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 0,
"selected": false,
"text": "<p>It seems like the methods GetOptionsFromArray and GetOptionsFromString were added only in v2.36 and as Murphy would say I have version 2.35 only.</p>\n\n<p>For now, I think I will have to live with local @ARGV.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/118289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
]
| I have a string with possible command line arguments (using an Read-Eval-Print-Loop program) and I want it to be parsed similar to the command line arguments when passed to Getopt::Long.
To elaborate:
I have a string
```
$str = '--infile /tmp/infile_location --outfile /tmp/outfile'
```
I want it to be parsed by GetOptions so that it is easier for me to add new options.
One workaround I could think of is to split the string on whitespace and replace @ARGV with new array and then call GetOptions. something like ...
```
my @arg_arr = split (/\s/, $input_line);
# This is done so that GetOptions reads these new arguments
@ARGV = @arg_arr;
print "ARGV is : @ARGV\n";
GetOptions (
'infile=s' => \$infile,
'outfile=s' => \$outfile
);
```
Is there any good/better way? | Check out the section [parsing options from an arbitrary string](http://perldoc.perl.org/Getopt/Long.html#Parsing-options-from-an-arbitrary-string) in the [man page for Getopt::Long](http://perldoc.perl.org/Getopt/Long.html), I think it does exactly what you're looking for. |
118,292 | <p>So I was writing some code today that basically looks like this:</p>
<pre><code>string returnString = s.Replace("!", " ")
.Replace("@", " ")
.Replace("#", " ")
.Replace("$", " ")
.Replace("%", " ")
.Replace("^", " ")
.Replace("*", " ")
.Replace("_", " ")
.Replace("+", " ")
.Replace("=", " ")
.Replace("\", " ")
</code></pre>
<p>Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the <code>Replace()</code> function?</p>
| [
{
"answer_id": 118306,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": true,
"text": "<p>You can use <strong>Regex.Replace()</strong>. All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first parameter is the input string and the last parameter is the replacement string.</p>\n\n<pre><code>var returnString = Regex.Replace(s,@\"[!@#\\$%\\^*_\\+=\\\\]\",\" \");\n</code></pre>\n"
},
{
"answer_id": 118314,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "<pre><code>s/[!@#$%^*_+=\\]/ /\n</code></pre>\n\n<p>Would be the regex for it... in c# you should be able to use</p>\n\n<pre><code>Regex.Replace(yourstring, \"[!@#$%^*_+=\\]\", \"\" ); \n</code></pre>\n\n<p>Though my C# is rusty..</p>\n"
},
{
"answer_id": 118386,
"author": "Nathan",
"author_id": 541,
"author_profile": "https://Stackoverflow.com/users/541",
"pm_score": 2,
"selected": false,
"text": "<p>FYI - if you need to modify this regex, you'll need to have an understanding of the regular expression language. It is quite simple, and as a developer you really owe it to yourself to add regular expressions to your toolbox - you don't need them every day, but being able to apply them appropriately where necessary when the need does arise will pay you back tenfold for the initial effort. Here is a link to a website with some top notch, easy to follow tutorials and reference material on regular expressions: <a href=\"http://www.regular-expressions.info/\" rel=\"nofollow noreferrer\">regular-expressions.info</a>. Once you get a feel for regular expressions and want to use them in your software, you'll want to buy Regex Buddy. It is a cheap and extraordinary tool for learning and using regular expressions. I <em>very</em> rarely purchase development tools, but this one was worth every penny. It is here: <a href=\"http://www.regexbuddy.com/\" rel=\"nofollow noreferrer\">Regex Buddy</a></p>\n"
},
{
"answer_id": 118660,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't care to delve into Regex, here are a couple of other extension-method possibilities.</p>\n\n<p>You can pass in the specific characters you want to replace:</p>\n\n<pre><code>static public string ReplaceCharsWithSpace(this string original, string chars)\n{\n var result = new StringBuilder();\n foreach (var ch in original)\n {\n result.Append(chars.Contains(ch) ? ' ' : ch);\n }\n return result.ToString();\n}\n</code></pre>\n\n<p>Or if you know you want to only keep or only strip out specific types of characters, you can use the various methods in <code>char</code>, such as <code>IsLetter</code>, <code>IsDigit</code>, <code>IsPunctuation</code>, and <code>IsSymbol</code>:</p>\n\n<pre><code>static public string ReplaceNonLetterCharsWithSpace(this string original)\n{\n var result = new StringBuilder();\n foreach (var ch in original)\n {\n result.Append(char.IsLetter(ch) ? ch : ' ');\n }\n return result.ToString();\n}\n</code></pre>\n\n<p>Here's how you'd use each of these possibilities:</p>\n\n<pre><code>string s = \"ab!2c\";\ns = s.ReplaceCharsWithSpace(@\"!@#$%^*_+=/\"); // s contains \"ab c\"\n\nstring t = \"ab3*c\";\nt = t.ReplaceNonLetterCharsWithSpace(); // t contains \"ab c\"\n</code></pre>\n"
},
{
"answer_id": 210940,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you can reduce this down to a couple of lines, if desired, by using a Lambda expression and <code>List<>, ForEach</code></p>\n\n<pre><code>using System.Collections.Generic;\n\nnamespace ReplaceWithSpace \n {\n class Program \n {\n static void Main(string[] args) \n {\n string someString = \"#1, 1+1=2 $string$!\";\n\n var charsToRemove = new List<char>(@\"!@#$%^*_+=\\\");\n charsToRemove.ForEach(c => someString = someString.Replace(c, ' '));\n\n System.Diagnostics.Debug.Print(someString); //\" 1, 1 1 2 string \"\n }\n }\n\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/118292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
| So I was writing some code today that basically looks like this:
```
string returnString = s.Replace("!", " ")
.Replace("@", " ")
.Replace("#", " ")
.Replace("$", " ")
.Replace("%", " ")
.Replace("^", " ")
.Replace("*", " ")
.Replace("_", " ")
.Replace("+", " ")
.Replace("=", " ")
.Replace("\", " ")
```
Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the `Replace()` function? | You can use **Regex.Replace()**. All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first parameter is the input string and the last parameter is the replacement string.
```
var returnString = Regex.Replace(s,@"[!@#\$%\^*_\+=\\]"," ");
``` |
118,305 | <p>How can UTF-8 strings (i.e. 8-bit string) be converted to/from XML-compatible 7-bit strings (i.e. printable ASCII with numeric entities)?</p>
<p>i.e. an <code>encode()</code> function such that:</p>
<pre><code>encode("“£”") -> "&#8220;&#163;&#8221;"
</code></pre>
<p><code>decode()</code> would also be useful:</p>
<pre><code>decode("&#8220;&#163;&#8221;") -> "“£”"
</code></pre>
<p>PHP's <code>htmlenties()</code>/<code>html_entity_decode()</code> pair does not do the right thing:</p>
<pre><code>htmlentities(html_entity_decode("&#8220;&#163;&#8221;")) ->
"&amp;#8220;&pound;&amp;#8221;"
</code></pre>
<p>Laboriously specifying types helps a little, but still returns XML-incompatible named entities, not numeric ones:</p>
<pre><code>htmlentities(html_entity_decode("&#8220;&#163;&#8221;", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") ->
"&ldquo;&pound;&rdquo;"
</code></pre>
| [
{
"answer_id": 193057,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 0,
"selected": false,
"text": "<p>It's a bit of a workaround, but I read a bit about <code>iconv()</code> and i don't think it'll give you numeric entities (not put to the test)</p>\n\n<pre><code>function decode( $string )\n{\n $doc = new DOMDocument( \"1.0\", \"UTF-8\" ); \n $doc->LoadXML( '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'.\"\\n\".'<x />', LIBXML_NOENT );\n $doc->documentElement->appendChild( $doc->createTextNode( $string ) );\n $output = $doc->saveXML( $doc );\n $output = preg_replace( '/<\\?([^>]+)\\?>/', '', $output ); \n $output = str_replace( array( '<x>', '</x>' ), array( '', '' ), $output );\n return trim( $output );\n}\n</code></pre>\n\n<p>This however, I have put to the test. I might do the reverse later, just don't hold your breath ;-)</p>\n"
},
{
"answer_id": 194025,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://php.net/manual/en/function.mb-encode-numericentity.php\" rel=\"noreferrer\"><code>mb_encode_numericentity</code></a> does that exactly.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/118305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11543/"
]
| How can UTF-8 strings (i.e. 8-bit string) be converted to/from XML-compatible 7-bit strings (i.e. printable ASCII with numeric entities)?
i.e. an `encode()` function such that:
```
encode("“£”") -> "“£”"
```
`decode()` would also be useful:
```
decode("“£”") -> "“£”"
```
PHP's `htmlenties()`/`html_entity_decode()` pair does not do the right thing:
```
htmlentities(html_entity_decode("“£”")) ->
"&#8220;£&#8221;"
```
Laboriously specifying types helps a little, but still returns XML-incompatible named entities, not numeric ones:
```
htmlentities(html_entity_decode("“£”", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") ->
"“£”"
``` | [`mb_encode_numericentity`](http://php.net/manual/en/function.mb-encode-numericentity.php) does that exactly. |
118,307 | <p>Tools like 'ps' and 'top' report various kinds of memory usages, such as the VM size and the Resident Set Size. However, none of those are the "real" memory usage:</p>
<ul>
<li>Program code is shared between multiple instances of the same program.</li>
<li>Shared library program code is shared between all processes that use that library.</li>
<li>Some apps fork off processes and share memory with them (e.g. via shared memory segments).</li>
<li>The virtual memory system makes the VM size report pretty much useless.</li>
<li>RSS is 0 when a process is swapped out, making it not very useful.</li>
<li>Etc etc.</li>
</ul>
<p>I've found that the private dirty RSS, as reported by Linux, is the closest thing to the "real" memory usage. This can be obtained by summing all <code>Private_Dirty</code> values in <code>/proc/somepid/smaps</code>.</p>
<p>However, do other operating systems provide similar functionality? If not, what are the alternatives? In particular, I'm interested in FreeBSD and OS X.</p>
| [
{
"answer_id": 118726,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 3,
"selected": false,
"text": "<p>Top knows how to do this. It shows VIRT, RES and SHR by default on Debian Linux. VIRT = SWAP + RES. RES = CODE + DATA. SHR is the memory that may be shared with another process (shared library or other memory.)</p>\n\n<p>Also, 'dirty' memory is merely RES memory that has been used, and/or has not been swapped.</p>\n\n<p>It can be hard to tell, but the best way to understand is to look at a system that isn't swapping. Then, RES - SHR is the process exclusive memory. However, that's not a good way of looking at it, because you don't know that the memory in SHR is being used by another process. It may represent unwritten shared object pages that are only used by the process.</p>\n"
},
{
"answer_id": 327785,
"author": "alex",
"author_id": 26787,
"author_profile": "https://Stackoverflow.com/users/26787",
"pm_score": 3,
"selected": false,
"text": "<p>You really can't.</p>\n\n<p>I mean, shared memory between processes... are you going to count it, or not. If you don't count it, you are wrong; the sum of all processes' memory usage is not going to be the total memory usage. If you count it, you are going to count it twice- the sum's not going to be correct.</p>\n\n<p>Me, I'm happy with RSS. And knowing you can't really rely on it completely...</p>\n"
},
{
"answer_id": 1954774,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 6,
"selected": false,
"text": "<p>On OSX the Activity Monitor gives you actually a very good guess.</p>\n<p>Private memory is for sure memory that is only used by your application. E.g. stack memory and all memory dynamically reserved using malloc() and comparable functions/methods (alloc method for Objective-C) is private memory. If you fork, private memory will be shared with you child, but marked copy-on-write. That means as long as a page is not modified by either process (parent or child) it is shared between them. As soon as either process modifies any page, this page is copied before it is modified. Even while this memory is shared with fork children (and it can <strong>only</strong> be shared with fork children), it is still shown as "private" memory, because in the worst case, every page of it will get modified (sooner or later) and then it is again private to each process again.</p>\n<p>Shared memory is either memory that is currently shared (the same pages are visible in the virtual process space of different processes) or that is likely to become shared in the future (e.g. read-only memory, since there is no reason for not sharing read-only memory). At least that's how I read the source code of some command line tools from Apple. So if you share memory between processes using mmap (or a comparable call that maps the same memory into multiple processes), this would be shared memory. However the executable code itself is also shared memory, since if another instance of your application is started there is no reason why it may not share the code already loaded in memory (executable code pages are read-only by default, unless you are running your app in a debugger). Thus shared memory is really memory used by your application, just like private one, but it might additionally be shared with another process (or it might not, but why would it not count towards your application if it was shared?)</p>\n<p>Real memory is the amount of RAM currently "assigned" to your process, no matter if private or shared. This can be exactly the sum of private and shared, but usually it is not. Your process might have more memory assigned to it than it currently needs (this speeds up requests for more memory in the future), but that is no loss to the system. If another process needs memory and no free memory is available, before the system starts swapping, it will take that extra memory away from your process and assign it another process (which is a fast and painless operation); therefor your next malloc call might be somewhat slower. Real memory can also be smaller than private and physical memory; this is because if your process requests memory from the system, it will only receive "virtual memory". This virtual memory is not linked to any real memory pages as long as you don't use it (so malloc 10 MB of memory, use only one byte of it, your process will get only a single page, 4096 byte, of memory assigned - the rest is only assigned if you actually ever need it). Further memory that is swapped may not count towards real memory either (not sure about this), but it will count towards shared and private memory.</p>\n<p>Virtual memory is the sum of all address blocks that are consider valid in your apps process space. These addresses might be linked to physical memory (that is again private or shared), or they might not, but in that case they will be linked to physical memory as soon as you use the address. Accessing memory addresses outside of the known addresses will cause a SIGBUS and your app will crash. When memory is swapped, the virtual address space for this memory remains valid and accessing those addresses causes memory to be swapped back in.</p>\n<p><strong>Conclusion:</strong><br>\nIf your app does not explicitly or implicitly use shared memory, private memory is the amount of memory your app needs because of the stack size (or sizes if multithreaded) and because of the malloc() calls you made for dynamic memory. You don't have to care a lot for shared or real memory in that case.</p>\n<p>If your app uses shared memory, and this includes a graphical UI, where memory is shared between your application and the WindowServer for example, then you might have a look at shared memory as well. A very high shared memory number may mean you have too many graphical resources loaded in memory at the moment.</p>\n<p>Real memory is of little interest for app development. If it is bigger than the sum of shared and private, then this means nothing other than that the system is lazy at taken memory away from your process. If it is smaller, then your process has requested more memory than it actually needed, which is not bad either, since as long as you don't use all of the requested memory, you are not "stealing" memory from the system. If it is much smaller than the sum of shared and private, you may only consider to request less memory where possible, as you are a bit over-requesting memory (again, this is not bad, but it tells me that your code is not optimized for minimal memory usage and if it is cross platform, other platforms may not have such a sophisticated memory handling, so you may prefer to alloc many small blocks instead of a few big ones for example, or free memory a lot sooner, and so on).</p>\n<p>If you are still not happy with all that information, you can get even more information. Open a terminal and run:</p>\n<pre><code>sudo vmmap <pid>\n</code></pre>\n<p>where is the process ID of your process. This will show you statistics for <strong>EVERY</strong> block of memory in your process space with start and end address. It will also tell you where this memory came from (A mapped file? Stack memory? Malloc'ed memory? A __DATA or __TEXT section of your executable?), how big it is in KB, the access rights and whether it is private, shared or copy-on-write. If it is mapped from a file, it will even give you the path to the file.</p>\n<p>If you want only "actual" RAM usage, use</p>\n<pre><code>sudo vmmap -resident <pid>\n</code></pre>\n<p>Now it will show for every memory block how big the memory block is virtually and how much of it is really currently present in physical memory.</p>\n<p>At the end of each dump is also an overview table with the sums of different memory types. This table looks like this for Firefox right now on my system:</p>\n<pre><code>REGION TYPE [ VIRTUAL/RESIDENT]\n=========== [ =======/========]\nATS (font support) [ 33.8M/ 2496K]\nCG backing stores [ 5588K/ 5460K]\nCG image [ 20K/ 20K]\nCG raster data [ 576K/ 576K]\nCG shared images [ 2572K/ 2404K]\nCarbon [ 1516K/ 1516K]\nCoreGraphics [ 8K/ 8K]\nIOKit [ 256.0M/ 0K]\nMALLOC [ 256.9M/ 247.2M]\nMemory tag=240 [ 4K/ 4K]\nMemory tag=242 [ 12K/ 12K]\nMemory tag=243 [ 8K/ 8K]\nMemory tag=249 [ 156K/ 76K]\nSTACK GUARD [ 101.2M/ 9908K]\nStack [ 14.0M/ 248K]\nVM_ALLOCATE [ 25.9M/ 25.6M]\n__DATA [ 6752K/ 3808K]\n__DATA/__OBJC [ 28K/ 28K]\n__IMAGE [ 1240K/ 112K]\n__IMPORT [ 104K/ 104K]\n__LINKEDIT [ 30.7M/ 3184K]\n__OBJC [ 1388K/ 1336K]\n__OBJC/__DATA [ 72K/ 72K]\n__PAGEZERO [ 4K/ 0K]\n__TEXT [ 108.6M/ 63.5M]\n__UNICODE [ 536K/ 512K]\nmapped file [ 118.8M/ 50.8M]\nshared memory [ 300K/ 276K]\nshared pmap [ 6396K/ 3120K]\n</code></pre>\n<p>What does this tell us? E.g. the Firefox binary and all library it loads have 108 MB data together in their __TEXT sections, but currently only 63 MB of those are currently resident in memory. The font support (ATS) needs 33 MB, but only about 2.5 MB are really in memory. It uses a bit over 5 MB CG backing stores, CG = Core Graphics, those are most likely window contents, buttons, images and other data that is cached for fast drawing. It has requested 256 MB via malloc calls and currently 247 MB are really in mapped to memory pages. It has 14 MB space reserved for stacks, but only 248 KB stack space is really in use right now.</p>\n<p>vmmap also has a good summary above the table</p>\n<pre><code>ReadOnly portion of Libraries: Total=139.3M resident=66.6M(48%) swapped_out_or_unallocated=72.7M(52%)\nWritable regions: Total=595.4M written=201.8M(34%) resident=283.1M(48%) swapped_out=0K(0%) unallocated=312.3M(52%)\n</code></pre>\n<p>And this shows an interesting aspect of the OS X: For read only memory that comes from libraries, it plays no role if it is swapped out or simply unallocated; there is only resident and not resident. For writable memory this makes a difference (in my case 52% of all requested memory has never been used and is such unallocated, 0% of memory has been swapped out to disk).</p>\n<p>The reason for that is simple: Read-only memory from mapped files is not swapped. If the memory is needed by the system, the current pages are simply dropped from the process, as the memory is already "swapped". It consisted only of content mapped directly from files and this content can be remapped whenever needed, as the files are still there. That way this memory won't waste space in the swap file either. Only writable memory must first be swapped to file before it is dropped, as its content wasn't stored on disk before.</p>\n"
},
{
"answer_id": 7734509,
"author": "Justin L.",
"author_id": 61394,
"author_profile": "https://Stackoverflow.com/users/61394",
"pm_score": 4,
"selected": false,
"text": "<p>On Linux, you may want the PSS (proportional set size) numbers in /proc/self/smaps. A mapping's PSS is its RSS divided by the number of processes which are using that mapping.</p>\n"
},
{
"answer_id": 9591754,
"author": "Ankur Agarwal",
"author_id": 494074,
"author_profile": "https://Stackoverflow.com/users/494074",
"pm_score": 3,
"selected": false,
"text": "<p>You can get private dirty and private clean RSS from /proc/pid/smaps</p>\n"
},
{
"answer_id": 14191692,
"author": "Arvind",
"author_id": 291917,
"author_profile": "https://Stackoverflow.com/users/291917",
"pm_score": 1,
"selected": false,
"text": "<p>For a question that mentioned Freebsd, surprised no one wrote this yet : </p>\n\n<p>If you want a linux style /proc/PROCESSID/status output, please do the following : </p>\n\n<pre><code>mount -t linprocfs none /proc\ncat /proc/PROCESSID/status\n</code></pre>\n\n<p>Atleast in FreeBSD 7.0, the mounting was not done by default ( 7.0 is a much older release,but for something this basic,the answer was hidden in a mailing list!) </p>\n"
},
{
"answer_id": 16597463,
"author": "BMDan",
"author_id": 598625,
"author_profile": "https://Stackoverflow.com/users/598625",
"pm_score": 2,
"selected": false,
"text": "<p>Reworked this to be much cleaner, to demonstrate some proper best practices in bash, and in particular to use <code>awk</code> instead of <code>bc</code>.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>find /proc/ -maxdepth 1 -name '[0-9]*' -print0 | while read -r -d $'\\0' pidpath; do\n [ -f \"${pidpath}/smaps\" ] || continue\n awk '!/^Private_Dirty:/ {next;}\n $3==\"kB\" {pd += $2 * (1024^1); next}\n $3==\"mB\" {pd += $2 * (1024^2); next}\n $3==\"gB\" {pd += $2 * (1024^3); next}\n $3==\"tB\" {pd += $2 * (1024^4); next}\n $3==\"pB\" {pd += $2 * (1024^5); next}\n {print \"ERROR!! \"$0 >\"/dev/stderr\"; exit(1)}\n END {printf(\"%10d: %d\\n\", '\"${pidpath##*/}\"', pd)}' \"${pidpath}/smaps\" || break\ndone\n</code></pre>\n\n<p>On a handy little container on my machine, with <code>| sort -n -k 2</code> to sort the output, this looks like:</p>\n\n<pre><code> 56: 106496\n 1: 147456\n 55: 155648\n</code></pre>\n"
},
{
"answer_id": 18815222,
"author": "http8086",
"author_id": 1356874,
"author_profile": "https://Stackoverflow.com/users/1356874",
"pm_score": 1,
"selected": false,
"text": "<p>Check it out, this is the source code of gnome-system-monitor, it thinks the memory \"<em>really used</em>\" by one process is sum(<code>info->mem</code>) of X Server Memory(<code>info->memxserver</code>) and Writable Memory(<code>info->memwritable</code>), the \"<strong><em>Writable Memory</em></strong>\" is the memory blocks which are marked as \"<strong>Private_Dirty</strong>\" in <strong>/proc/PID/smaps</strong> file.</p>\n\n<p>Other than linux system, could be different way according to gnome-system-monitor code.</p>\n\n<pre><code>static void\nget_process_memory_writable (ProcInfo *info)\n{\n glibtop_proc_map buf;\n glibtop_map_entry *maps;\n\n maps = glibtop_get_proc_map(&buf, info->pid);\n\n gulong memwritable = 0;\n const unsigned number = buf.number;\n\n for (unsigned i = 0; i < number; ++i) {\n#ifdef __linux__\n memwritable += maps[i].private_dirty;\n#else\n if (maps[i].perm & GLIBTOP_MAP_PERM_WRITE)\n memwritable += maps[i].size;\n#endif\n }\n\n info->memwritable = memwritable;\n\n g_free(maps);\n}\n\nstatic void\nget_process_memory_info (ProcInfo *info)\n{\n glibtop_proc_mem procmem;\n WnckResourceUsage xresources;\n\n wnck_pid_read_resource_usage (gdk_screen_get_display (gdk_screen_get_default ()),\n info->pid,\n &xresources);\n\n glibtop_get_proc_mem(&procmem, info->pid);\n\n info->vmsize = procmem.vsize;\n info->memres = procmem.resident;\n info->memshared = procmem.share;\n\n info->memxserver = xresources.total_bytes_estimate;\n\n get_process_memory_writable(info);\n\n // fake the smart memory column if writable is not available\n info->mem = info->memxserver + (info->memwritable ? info->memwritable : info->memres);\n}\n</code></pre>\n"
},
{
"answer_id": 22305737,
"author": "gheese",
"author_id": 1061727,
"author_profile": "https://Stackoverflow.com/users/1061727",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at smem. It will give you PSS information</p>\n\n<p><a href=\"http://www.selenic.com/smem/\" rel=\"noreferrer\">http://www.selenic.com/smem/</a></p>\n"
},
{
"answer_id": 52118812,
"author": "Edward Tomasz Napierala",
"author_id": 3390390,
"author_profile": "https://Stackoverflow.com/users/3390390",
"pm_score": 2,
"selected": false,
"text": "<p>Use the mincore(2) system call. Quoting the man page:</p>\n\n<pre><code>DESCRIPTION\n The mincore() system call determines whether each of the pages in the\n region beginning at addr and continuing for len bytes is resident. The\n status is returned in the vec array, one character per page. Each\n character is either 0 if the page is not resident, or a combination of\n the following flags (defined in <sys/mman.h>):\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/118307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20816/"
]
| Tools like 'ps' and 'top' report various kinds of memory usages, such as the VM size and the Resident Set Size. However, none of those are the "real" memory usage:
* Program code is shared between multiple instances of the same program.
* Shared library program code is shared between all processes that use that library.
* Some apps fork off processes and share memory with them (e.g. via shared memory segments).
* The virtual memory system makes the VM size report pretty much useless.
* RSS is 0 when a process is swapped out, making it not very useful.
* Etc etc.
I've found that the private dirty RSS, as reported by Linux, is the closest thing to the "real" memory usage. This can be obtained by summing all `Private_Dirty` values in `/proc/somepid/smaps`.
However, do other operating systems provide similar functionality? If not, what are the alternatives? In particular, I'm interested in FreeBSD and OS X. | On OSX the Activity Monitor gives you actually a very good guess.
Private memory is for sure memory that is only used by your application. E.g. stack memory and all memory dynamically reserved using malloc() and comparable functions/methods (alloc method for Objective-C) is private memory. If you fork, private memory will be shared with you child, but marked copy-on-write. That means as long as a page is not modified by either process (parent or child) it is shared between them. As soon as either process modifies any page, this page is copied before it is modified. Even while this memory is shared with fork children (and it can **only** be shared with fork children), it is still shown as "private" memory, because in the worst case, every page of it will get modified (sooner or later) and then it is again private to each process again.
Shared memory is either memory that is currently shared (the same pages are visible in the virtual process space of different processes) or that is likely to become shared in the future (e.g. read-only memory, since there is no reason for not sharing read-only memory). At least that's how I read the source code of some command line tools from Apple. So if you share memory between processes using mmap (or a comparable call that maps the same memory into multiple processes), this would be shared memory. However the executable code itself is also shared memory, since if another instance of your application is started there is no reason why it may not share the code already loaded in memory (executable code pages are read-only by default, unless you are running your app in a debugger). Thus shared memory is really memory used by your application, just like private one, but it might additionally be shared with another process (or it might not, but why would it not count towards your application if it was shared?)
Real memory is the amount of RAM currently "assigned" to your process, no matter if private or shared. This can be exactly the sum of private and shared, but usually it is not. Your process might have more memory assigned to it than it currently needs (this speeds up requests for more memory in the future), but that is no loss to the system. If another process needs memory and no free memory is available, before the system starts swapping, it will take that extra memory away from your process and assign it another process (which is a fast and painless operation); therefor your next malloc call might be somewhat slower. Real memory can also be smaller than private and physical memory; this is because if your process requests memory from the system, it will only receive "virtual memory". This virtual memory is not linked to any real memory pages as long as you don't use it (so malloc 10 MB of memory, use only one byte of it, your process will get only a single page, 4096 byte, of memory assigned - the rest is only assigned if you actually ever need it). Further memory that is swapped may not count towards real memory either (not sure about this), but it will count towards shared and private memory.
Virtual memory is the sum of all address blocks that are consider valid in your apps process space. These addresses might be linked to physical memory (that is again private or shared), or they might not, but in that case they will be linked to physical memory as soon as you use the address. Accessing memory addresses outside of the known addresses will cause a SIGBUS and your app will crash. When memory is swapped, the virtual address space for this memory remains valid and accessing those addresses causes memory to be swapped back in.
**Conclusion:**
If your app does not explicitly or implicitly use shared memory, private memory is the amount of memory your app needs because of the stack size (or sizes if multithreaded) and because of the malloc() calls you made for dynamic memory. You don't have to care a lot for shared or real memory in that case.
If your app uses shared memory, and this includes a graphical UI, where memory is shared between your application and the WindowServer for example, then you might have a look at shared memory as well. A very high shared memory number may mean you have too many graphical resources loaded in memory at the moment.
Real memory is of little interest for app development. If it is bigger than the sum of shared and private, then this means nothing other than that the system is lazy at taken memory away from your process. If it is smaller, then your process has requested more memory than it actually needed, which is not bad either, since as long as you don't use all of the requested memory, you are not "stealing" memory from the system. If it is much smaller than the sum of shared and private, you may only consider to request less memory where possible, as you are a bit over-requesting memory (again, this is not bad, but it tells me that your code is not optimized for minimal memory usage and if it is cross platform, other platforms may not have such a sophisticated memory handling, so you may prefer to alloc many small blocks instead of a few big ones for example, or free memory a lot sooner, and so on).
If you are still not happy with all that information, you can get even more information. Open a terminal and run:
```
sudo vmmap <pid>
```
where is the process ID of your process. This will show you statistics for **EVERY** block of memory in your process space with start and end address. It will also tell you where this memory came from (A mapped file? Stack memory? Malloc'ed memory? A \_\_DATA or \_\_TEXT section of your executable?), how big it is in KB, the access rights and whether it is private, shared or copy-on-write. If it is mapped from a file, it will even give you the path to the file.
If you want only "actual" RAM usage, use
```
sudo vmmap -resident <pid>
```
Now it will show for every memory block how big the memory block is virtually and how much of it is really currently present in physical memory.
At the end of each dump is also an overview table with the sums of different memory types. This table looks like this for Firefox right now on my system:
```
REGION TYPE [ VIRTUAL/RESIDENT]
=========== [ =======/========]
ATS (font support) [ 33.8M/ 2496K]
CG backing stores [ 5588K/ 5460K]
CG image [ 20K/ 20K]
CG raster data [ 576K/ 576K]
CG shared images [ 2572K/ 2404K]
Carbon [ 1516K/ 1516K]
CoreGraphics [ 8K/ 8K]
IOKit [ 256.0M/ 0K]
MALLOC [ 256.9M/ 247.2M]
Memory tag=240 [ 4K/ 4K]
Memory tag=242 [ 12K/ 12K]
Memory tag=243 [ 8K/ 8K]
Memory tag=249 [ 156K/ 76K]
STACK GUARD [ 101.2M/ 9908K]
Stack [ 14.0M/ 248K]
VM_ALLOCATE [ 25.9M/ 25.6M]
__DATA [ 6752K/ 3808K]
__DATA/__OBJC [ 28K/ 28K]
__IMAGE [ 1240K/ 112K]
__IMPORT [ 104K/ 104K]
__LINKEDIT [ 30.7M/ 3184K]
__OBJC [ 1388K/ 1336K]
__OBJC/__DATA [ 72K/ 72K]
__PAGEZERO [ 4K/ 0K]
__TEXT [ 108.6M/ 63.5M]
__UNICODE [ 536K/ 512K]
mapped file [ 118.8M/ 50.8M]
shared memory [ 300K/ 276K]
shared pmap [ 6396K/ 3120K]
```
What does this tell us? E.g. the Firefox binary and all library it loads have 108 MB data together in their \_\_TEXT sections, but currently only 63 MB of those are currently resident in memory. The font support (ATS) needs 33 MB, but only about 2.5 MB are really in memory. It uses a bit over 5 MB CG backing stores, CG = Core Graphics, those are most likely window contents, buttons, images and other data that is cached for fast drawing. It has requested 256 MB via malloc calls and currently 247 MB are really in mapped to memory pages. It has 14 MB space reserved for stacks, but only 248 KB stack space is really in use right now.
vmmap also has a good summary above the table
```
ReadOnly portion of Libraries: Total=139.3M resident=66.6M(48%) swapped_out_or_unallocated=72.7M(52%)
Writable regions: Total=595.4M written=201.8M(34%) resident=283.1M(48%) swapped_out=0K(0%) unallocated=312.3M(52%)
```
And this shows an interesting aspect of the OS X: For read only memory that comes from libraries, it plays no role if it is swapped out or simply unallocated; there is only resident and not resident. For writable memory this makes a difference (in my case 52% of all requested memory has never been used and is such unallocated, 0% of memory has been swapped out to disk).
The reason for that is simple: Read-only memory from mapped files is not swapped. If the memory is needed by the system, the current pages are simply dropped from the process, as the memory is already "swapped". It consisted only of content mapped directly from files and this content can be remapped whenever needed, as the files are still there. That way this memory won't waste space in the swap file either. Only writable memory must first be swapped to file before it is dropped, as its content wasn't stored on disk before. |
118,341 | <p>I have a Linq to objects statement</p>
<pre><code> var confirm = from l in lines.Lines
where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)
select l;
</code></pre>
<p>The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext()</p>
<p>If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over?</p>
<p><strong>EDIT</strong> When I said <em>I know for a fact that there are no null objects</em> it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really'</p>
<p>LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool</p>
| [
{
"answer_id": 118347,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 6,
"selected": true,
"text": "<p>I'm not sure if it's possible to debug from VS, but I find <a href=\"http://www.linqpad.net/\" rel=\"noreferrer\">LINQPad</a> to be quite useful. It'll let you dump the results of each part of the LINQ query.</p>\n"
},
{
"answer_id": 118355,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 2,
"selected": false,
"text": "<p>Check the exception stack trace and see the last bit of your code that executed.</p>\n"
},
{
"answer_id": 118362,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 2,
"selected": false,
"text": "<p>From the looks of the error I would suggest you take a look at line.Lines and make sure its enumerator is implemented properly. I think it's returning a null when it shouldn't.</p>\n\n<p>Oh and just make sure the line and line.Lines objects aren't null or returning nulls as well.</p>\n"
},
{
"answer_id": 118871,
"author": "Steve Steiner",
"author_id": 3892,
"author_profile": "https://Stackoverflow.com/users/3892",
"pm_score": 4,
"selected": false,
"text": "<p>You should be able to set a breakpoint on the expression in the <code>where</code> clause of your LINQ statement.</p>\n\n<p>In this example, put the cursor anywhere in the following section of code:</p>\n\n<pre><code>(l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)\n</code></pre>\n\n<p>Then press <kbd>F9</kbd> or use the menu or context menu to add the breakpoint.</p>\n\n<p>When set correctly, only the above code should have the breakpoint formatting in the editor rather than the entire LINQ statement. You can also look in the breakpoints window to see.</p>\n\n<p>If you've set it correctly, you will stop each time at the function that implements the above part of the query.</p>\n"
},
{
"answer_id": 716060,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Yes it is indeed possible to pause execution midway through a linq query.</p>\n\n<p>Convert your linq to query style using lambda expressions and insert a Select statement that returns itself somewhere after the point in the linq that you want to debug. Some sample code will make it clearer - </p>\n\n<pre><code> var query = dataset.Tables[0].AsEnumerable()\n .Where (i=> i.Field<string>(\"Project\").Contains(\"070932.01\"))\n // .Select(i =>\n // {return i;}\n // )\n .Select (i=>i.Field<string>(\"City\"));\n</code></pre>\n\n<p>Then uncomment the commented lines. Make sure the {return i;} is on its own line and insert a debug point there. You can put this select at any point in your long, complicated linq query.</p>\n"
},
{
"answer_id": 4410964,
"author": "Michael Sorens",
"author_id": 115690,
"author_profile": "https://Stackoverflow.com/users/115690",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote a comprehensive article addressing this very question published on Simple-Talk.com (<a href=\"http://www.simple-talk.com/dotnet/.net-framework/linq-secrets-revealed-chaining-and-debugging/\" rel=\"nofollow noreferrer\">LINQ Secrets Revealed: Chaining and Debugging</a>) back in 2010:</p>\n\n<p>I talk about LINQPad (as mentioned earlier by OwenP) as a great tool <em>external</em> to Visual Studio. Pay particular attention to its extraordinary Dump() method. You can inject this at one or more points in a LINQ chain to see your data visualized in an amazingly clean and clear fashion. Though very useful, LINQPad is external to Visual Studio. So I also present several techniques available for use <em>within</em> Visual Studio because sometimes it is just not practical to migrate a chunk of code over to LINQPad:</p>\n\n<p>(1) Inject calls to the Dump() extension method I present in my article to allow logging. I started with Bart De Smet's Watch() method in his informative article <a href=\"http://community.bartdesmet.net/blogs/bart/archive/2009/04/23/linq-to-objects-debugging.aspx\" rel=\"nofollow noreferrer\">LINQ to Objects – Debugging</a> and added some labeling and colorization to enhance the visualization, though still it pales in comparison to LINQPad's Dump output.</p>\n\n<p>(2) Bring LINQPad's visualization right into Visual Studio with Robert Ivanc's <a href=\"http://code.google.com/p/linqpadvisualizer/\" rel=\"nofollow noreferrer\">LINQPad Visualizer</a> add-in. Not sure if it was through my prodding :-), but the couple inconveniences present when I was writing my article have now all been admirably addressed in the latest release. It has full VS2010 support and lets you examine any object you like when debugging.</p>\n\n<p>(3) Embed nop statements in the middle of your LINQ chain so you can set breakpoints, as described earlier by Amazing Pete.</p>\n\n<p><strong>2016.12.01 Update</strong></p>\n\n<p>And I just wrote the sequel to the above article, titled simply <a href=\"https://www.simple-talk.com/dotnet/net-development/linq-debugging-visualization/\" rel=\"nofollow noreferrer\">LINQ Debugging and Visualization</a>, which reveals that true LINQ debugging capability has finally arrived in Visual Studio 2015 with the about-to-be-released new feature in OzCode. @Dror's answer to this question shows a tiny glimpse of it, but I encourage you to read my new article for an in-depth \"how to\". (And I do <em>not</em> work for OzCode.:-)</p>\n"
},
{
"answer_id": 38815604,
"author": "user1414213562",
"author_id": 6659843,
"author_profile": "https://Stackoverflow.com/users/6659843",
"pm_score": 3,
"selected": false,
"text": "<p>It is possible to step inside the LINQ expression without setting any temporary breakpoints. You need to step into the function which <strong>evaluates</strong> the LINQ expression, e.g.:</p>\n\n<pre><code>var confirm = from l in lines.Lines \n where (l.LineNumber == startline.LineNumber)\n || (l.LineNumber == endline.LineNumber) \n select l;\n\n confirm.ToArray(); // Press F11 (\"Step into\") when you reach this statement\n\n foreach(var o in q) // Press F11 when \"in\" keyword is highlighted as \"next statement\"\n // ...\n</code></pre>\n"
},
{
"answer_id": 39470993,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 3,
"selected": false,
"text": "<p><em>[Disclaimer: I work at OzCode]</em></p>\n\n<p>The problem with LINQ is that it's hard to impossible to debug - even when dealing simple queries a developer is forced to refactor his/her query to a bunch of foreach loops, or use logging.\nLINQ debugging is supported in a soon-to-be-released version of OzCode (<a href=\"http://o.oz-code.com/LINQ_EAP\" rel=\"noreferrer\">currently available as an Early Access Preview</a>) and it helps developers drill into their LINQ code as well and pinpoint those hard to catch exceptions inside queries </p>\n\n<p>This is what your query would look like in OzCode:<a href=\"https://i.stack.imgur.com/LfJ4T.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LfJ4T.gif\" alt=\"Debugging LINQ exception\"></a></p>\n"
},
{
"answer_id": 54784747,
"author": "Sha",
"author_id": 5891216,
"author_profile": "https://Stackoverflow.com/users/5891216",
"pm_score": 0,
"selected": false,
"text": "<p>While it isn't a way of debugging, I'd suggest using the following:</p>\n\n<pre><code>using (var db = new AppContext())\n {\n db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);\n // Rest of code\n }\n</code></pre>\n\n<p>You can then check the output window when debugging to see the SQL generated from your LINQ query.</p>\n"
},
{
"answer_id": 72167851,
"author": "QUANIT KHATRI",
"author_id": 4767449,
"author_profile": "https://Stackoverflow.com/users/4767449",
"pm_score": 0,
"selected": false,
"text": "<p>To step through the LINQ statement just put a breakpoint on linq statement and then when it starts to debug that line then\nRight click on it\nclick on Run To Cursor option\nIt will start to execute code line by line as we do normally.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
]
| I have a Linq to objects statement
```
var confirm = from l in lines.Lines
where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)
select l;
```
The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over?
**EDIT** When I said *I know for a fact that there are no null objects* it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really'
LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool | I'm not sure if it's possible to debug from VS, but I find [LINQPad](http://www.linqpad.net/) to be quite useful. It'll let you dump the results of each part of the LINQ query. |
118,342 | <p>I am aware of this command:
<code>cvs log -N -w<userid> -d"1 day ago"</code></p>
<p>Unfortunately this generates a formatted report with lots of newlines in it, such that the file-path, the file-version, and the comment-text are all on separate lines. Therefore it is difficult to scan it for all occurrences of comment text, (eg, grep), and correlate the matches to file/version.</p>
<p>(Note that the log output would be perfectly acceptable, if only cvs could perform the filtering natively.)</p>
<p>EDIT: Sample output. A block of text like this is reported for each repository file:</p>
<pre>
RCS file: /data/cvs/dps/build.xml,v
Working file: build.xml
head: 1.49
branch:
locks: strict
access list:
keyword substitution: kv
total revisions: 57; selected revisions: 1
description:
----------------------------
revision 1.48
date: 2008/07/09 17:17:32; author: noec; state: Exp; lines: +2 -2
Fixed src.jar references
----------------------------
revision 1.47
date: 2008/07/03 13:13:14; author: noec; state: Exp; lines: +1 -1
Fixed common-src.jar reference.
=============================================================================
</pre>
| [
{
"answer_id": 118372,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>This might be way overkill, but you could use <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-cvsimport.html\" rel=\"nofollow noreferrer\">git-cvsimport</a> to import the CVS history to a Git repository and search it using Git's tools. Not only can you search for text within commit messages, but you can also search for code that has ever been added <em>or removed</em> from files in your repository.</p>\n"
},
{
"answer_id": 118378,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://cvssearch.sourceforge.net/\" rel=\"nofollow noreferrer\">CVSSearch</a> might help, but it's a CGI application :'(</p>\n"
},
{
"answer_id": 118397,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>My first thoughts were to use egrep (or grep -E, I think) to search for multiple patterns such as:</p>\n\n<pre><code><Cmd> | egrep 'Filename:|Version:|Comment:'\n</code></pre>\n\n<p>but then I realised you wanted to filter more intelligently.</p>\n\n<p>To that end, I would use awk (or perl) to process the output line-by-line, setting an echo variable when you find a section of interest; pseudocode here:</p>\n\n<pre><code># Assume the sections are of the format:\n# Filename: <filename>\n# Version: <version>\n# Comment: <comment>\n# <more comment>\n\nSet echo to false\nWhile more lines left\n Get line\n If line starts with \"Filename: \" and <filename> is of interest\n Set echo to true\n If line starts with \"Filename: \" and <filename> is not of interest\n Set echo to false\n If echo is true\n Output line\nEnd while\n</code></pre>\n"
},
{
"answer_id": 381972,
"author": "s_t_e_v_e",
"author_id": 21176,
"author_profile": "https://Stackoverflow.com/users/21176",
"pm_score": 4,
"selected": true,
"text": "<p>The <code>-w</code> options seems to work better with the <code>-S</code> option. Otherwise there are additional results which don't seem related to the userid. Perhaps someone can explain it.</p>\n\n<pre><code>cvs log -N -S -w<userid> -d\"1 day ago\"\n</code></pre>\n\n<p>With that I have been getting reasonable success piping it to grep:</p>\n\n<pre><code>cvs log -N -S -w<userid> -d\"1 day ago\" | grep -B14 \"some text\" > afile\n</code></pre>\n\n<p>I'm redirecting output to a file since the cvs log is noisy and I'm not sure how to make it quiet. I suppose an alternative is to redirect the stderr to <code>/dev/null</code>. </p>\n"
},
{
"answer_id": 538867,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here is what I did - a simple Java script:</p>\n\n<pre><code>import java.io.IOException;\n\n\npublic class ParseCVSLog\n{\n\n public static final String CVS_LOG_FILE_SEPARATOR = \"=============================================================================\";\n public static final String CVS_LOG_REVISION_SEPARATOR = \"----------------------------\";\n public static final String CVS_LOG_HEADER_FILE_NAME = \"Working file\";\n public static final String CVS_LOG_VERSION_PREFIX = \"revision\";\n\n public static void main(String[] args) throws IOException\n {\n String searchString = args[0];\n\n System.out.println( \"SEARCHING FOR: \" + searchString );\n\n StringBuffer cvsLogOutputBuffer = new StringBuffer();\n byte[] bytes = new byte[1024];\n int numBytesRead = 0;\n while( (numBytesRead = System.in.read( bytes )) > 0 )\n {\n String bytesString = new String(bytes, 0, numBytesRead);\n cvsLogOutputBuffer.append( bytesString );\n }\n\n String cvsLogOutput = cvsLogOutputBuffer.toString();\n\n String newLine = System.getProperty(\"line.separator\");\n String[] fileArray = cvsLogOutput.split( CVS_LOG_FILE_SEPARATOR );\n\n\n for ( String fileRecord : fileArray )\n {\n if ( !fileRecord.contains( searchString ) )\n {\n continue;\n }\n\n String[] revisionArray = fileRecord.split( CVS_LOG_REVISION_SEPARATOR );\n String[] fileHeaderLineArray = revisionArray[ 0 ].split( newLine );\n String fileName = \"\";\n for ( String fileHeadeLine : fileHeaderLineArray )\n {\n if ( fileHeadeLine.contains( CVS_LOG_HEADER_FILE_NAME ) )\n {\n fileName = fileHeadeLine.split( \": \" )[ 1 ];\n break;\n }\n }\n System.out.print( fileName );\n for ( int i = 1; i < revisionArray.length; i++ )\n {\n String versionRecord = revisionArray[ i ];\n if ( !versionRecord.contains( searchString ) )\n {\n continue;\n }\n String[] versionLineArray = versionRecord.split( newLine );\n for ( String versionLine : versionLineArray )\n {\n if ( versionLine.contains( CVS_LOG_VERSION_PREFIX ) )\n {\n System.out.print( \" \" + versionLine.split( \" \" )[ 1 ] );\n }\n }\n\n }\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<p>And here is how I used it: </p>\n\n<pre><code>cvs log -N -S -washamsut | java ParseCVSLog GS-242\n</code></pre>\n"
},
{
"answer_id": 1752463,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You want <a href=\"http://www.cobite.com/cvsps/\" rel=\"nofollow noreferrer\">cvsps</a> - which will generate patchsets from CVS history. Then, you should only have one instance of your comment in the cvsps output, with the files listed neatly below it </p>\n"
},
{
"answer_id": 34339088,
"author": "JochenJung",
"author_id": 351893,
"author_profile": "https://Stackoverflow.com/users/351893",
"pm_score": 1,
"selected": false,
"text": "<p>This command and gawk script helps me to find only the filename, date and comment line of each log entry.</p>\n\n<pre><code>cvs log -N -S -b -w<userid> -d \">1 day ago\" 2>/dev/null | gawk 'BEGIN{out=0;} /^Working file:/ { print $0; } /^date:/ { out=1; } /^===/ { print \"\"; out=0; } (out==1){print $0;}'\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
]
| I am aware of this command:
`cvs log -N -w<userid> -d"1 day ago"`
Unfortunately this generates a formatted report with lots of newlines in it, such that the file-path, the file-version, and the comment-text are all on separate lines. Therefore it is difficult to scan it for all occurrences of comment text, (eg, grep), and correlate the matches to file/version.
(Note that the log output would be perfectly acceptable, if only cvs could perform the filtering natively.)
EDIT: Sample output. A block of text like this is reported for each repository file:
```
RCS file: /data/cvs/dps/build.xml,v
Working file: build.xml
head: 1.49
branch:
locks: strict
access list:
keyword substitution: kv
total revisions: 57; selected revisions: 1
description:
----------------------------
revision 1.48
date: 2008/07/09 17:17:32; author: noec; state: Exp; lines: +2 -2
Fixed src.jar references
----------------------------
revision 1.47
date: 2008/07/03 13:13:14; author: noec; state: Exp; lines: +1 -1
Fixed common-src.jar reference.
=============================================================================
``` | The `-w` options seems to work better with the `-S` option. Otherwise there are additional results which don't seem related to the userid. Perhaps someone can explain it.
```
cvs log -N -S -w<userid> -d"1 day ago"
```
With that I have been getting reasonable success piping it to grep:
```
cvs log -N -S -w<userid> -d"1 day ago" | grep -B14 "some text" > afile
```
I'm redirecting output to a file since the cvs log is noisy and I'm not sure how to make it quiet. I suppose an alternative is to redirect the stderr to `/dev/null`. |
118,343 | <p>Ruby on Rails has <a href="http://wiki.rubyonrails.com/rails/pages/Timestamping" rel="nofollow noreferrer">magic timestamping fields</a> that are automatically updated when a record is created or updated. I'm trying to find similar functionality in Entity Framework. I've considered database triggers and a SavingChanges event handler. Is there a more obvious method I'm overlooking?</p>
| [
{
"answer_id": 118372,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>This might be way overkill, but you could use <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-cvsimport.html\" rel=\"nofollow noreferrer\">git-cvsimport</a> to import the CVS history to a Git repository and search it using Git's tools. Not only can you search for text within commit messages, but you can also search for code that has ever been added <em>or removed</em> from files in your repository.</p>\n"
},
{
"answer_id": 118378,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://cvssearch.sourceforge.net/\" rel=\"nofollow noreferrer\">CVSSearch</a> might help, but it's a CGI application :'(</p>\n"
},
{
"answer_id": 118397,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>My first thoughts were to use egrep (or grep -E, I think) to search for multiple patterns such as:</p>\n\n<pre><code><Cmd> | egrep 'Filename:|Version:|Comment:'\n</code></pre>\n\n<p>but then I realised you wanted to filter more intelligently.</p>\n\n<p>To that end, I would use awk (or perl) to process the output line-by-line, setting an echo variable when you find a section of interest; pseudocode here:</p>\n\n<pre><code># Assume the sections are of the format:\n# Filename: <filename>\n# Version: <version>\n# Comment: <comment>\n# <more comment>\n\nSet echo to false\nWhile more lines left\n Get line\n If line starts with \"Filename: \" and <filename> is of interest\n Set echo to true\n If line starts with \"Filename: \" and <filename> is not of interest\n Set echo to false\n If echo is true\n Output line\nEnd while\n</code></pre>\n"
},
{
"answer_id": 381972,
"author": "s_t_e_v_e",
"author_id": 21176,
"author_profile": "https://Stackoverflow.com/users/21176",
"pm_score": 4,
"selected": true,
"text": "<p>The <code>-w</code> options seems to work better with the <code>-S</code> option. Otherwise there are additional results which don't seem related to the userid. Perhaps someone can explain it.</p>\n\n<pre><code>cvs log -N -S -w<userid> -d\"1 day ago\"\n</code></pre>\n\n<p>With that I have been getting reasonable success piping it to grep:</p>\n\n<pre><code>cvs log -N -S -w<userid> -d\"1 day ago\" | grep -B14 \"some text\" > afile\n</code></pre>\n\n<p>I'm redirecting output to a file since the cvs log is noisy and I'm not sure how to make it quiet. I suppose an alternative is to redirect the stderr to <code>/dev/null</code>. </p>\n"
},
{
"answer_id": 538867,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here is what I did - a simple Java script:</p>\n\n<pre><code>import java.io.IOException;\n\n\npublic class ParseCVSLog\n{\n\n public static final String CVS_LOG_FILE_SEPARATOR = \"=============================================================================\";\n public static final String CVS_LOG_REVISION_SEPARATOR = \"----------------------------\";\n public static final String CVS_LOG_HEADER_FILE_NAME = \"Working file\";\n public static final String CVS_LOG_VERSION_PREFIX = \"revision\";\n\n public static void main(String[] args) throws IOException\n {\n String searchString = args[0];\n\n System.out.println( \"SEARCHING FOR: \" + searchString );\n\n StringBuffer cvsLogOutputBuffer = new StringBuffer();\n byte[] bytes = new byte[1024];\n int numBytesRead = 0;\n while( (numBytesRead = System.in.read( bytes )) > 0 )\n {\n String bytesString = new String(bytes, 0, numBytesRead);\n cvsLogOutputBuffer.append( bytesString );\n }\n\n String cvsLogOutput = cvsLogOutputBuffer.toString();\n\n String newLine = System.getProperty(\"line.separator\");\n String[] fileArray = cvsLogOutput.split( CVS_LOG_FILE_SEPARATOR );\n\n\n for ( String fileRecord : fileArray )\n {\n if ( !fileRecord.contains( searchString ) )\n {\n continue;\n }\n\n String[] revisionArray = fileRecord.split( CVS_LOG_REVISION_SEPARATOR );\n String[] fileHeaderLineArray = revisionArray[ 0 ].split( newLine );\n String fileName = \"\";\n for ( String fileHeadeLine : fileHeaderLineArray )\n {\n if ( fileHeadeLine.contains( CVS_LOG_HEADER_FILE_NAME ) )\n {\n fileName = fileHeadeLine.split( \": \" )[ 1 ];\n break;\n }\n }\n System.out.print( fileName );\n for ( int i = 1; i < revisionArray.length; i++ )\n {\n String versionRecord = revisionArray[ i ];\n if ( !versionRecord.contains( searchString ) )\n {\n continue;\n }\n String[] versionLineArray = versionRecord.split( newLine );\n for ( String versionLine : versionLineArray )\n {\n if ( versionLine.contains( CVS_LOG_VERSION_PREFIX ) )\n {\n System.out.print( \" \" + versionLine.split( \" \" )[ 1 ] );\n }\n }\n\n }\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<p>And here is how I used it: </p>\n\n<pre><code>cvs log -N -S -washamsut | java ParseCVSLog GS-242\n</code></pre>\n"
},
{
"answer_id": 1752463,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You want <a href=\"http://www.cobite.com/cvsps/\" rel=\"nofollow noreferrer\">cvsps</a> - which will generate patchsets from CVS history. Then, you should only have one instance of your comment in the cvsps output, with the files listed neatly below it </p>\n"
},
{
"answer_id": 34339088,
"author": "JochenJung",
"author_id": 351893,
"author_profile": "https://Stackoverflow.com/users/351893",
"pm_score": 1,
"selected": false,
"text": "<p>This command and gawk script helps me to find only the filename, date and comment line of each log entry.</p>\n\n<pre><code>cvs log -N -S -b -w<userid> -d \">1 day ago\" 2>/dev/null | gawk 'BEGIN{out=0;} /^Working file:/ { print $0; } /^date:/ { out=1; } /^===/ { print \"\"; out=0; } (out==1){print $0;}'\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453303/"
]
| Ruby on Rails has [magic timestamping fields](http://wiki.rubyonrails.com/rails/pages/Timestamping) that are automatically updated when a record is created or updated. I'm trying to find similar functionality in Entity Framework. I've considered database triggers and a SavingChanges event handler. Is there a more obvious method I'm overlooking? | The `-w` options seems to work better with the `-S` option. Otherwise there are additional results which don't seem related to the userid. Perhaps someone can explain it.
```
cvs log -N -S -w<userid> -d"1 day ago"
```
With that I have been getting reasonable success piping it to grep:
```
cvs log -N -S -w<userid> -d"1 day ago" | grep -B14 "some text" > afile
```
I'm redirecting output to a file since the cvs log is noisy and I'm not sure how to make it quiet. I suppose an alternative is to redirect the stderr to `/dev/null`. |
118,370 | <p>This came up in <a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
| [
{
"answer_id": 118395,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 8,
"selected": true,
"text": "<p><code>Ellipsis</code>, or <code>...</code> is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it. </p>\n\n<p>So the syntax for it depends entirely on you, or someone else, having written code to understand it.</p>\n\n<p>Numpy uses it, as stated in the <a href=\"http://wiki.scipy.org/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb\" rel=\"noreferrer\">documentation</a>. Some examples <a href=\"http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c\" rel=\"noreferrer\">here</a>.</p>\n\n<p>In your own class, you'd use it like this:</p>\n\n<pre><code>>>> class TestEllipsis(object):\n... def __getitem__(self, item):\n... if item is Ellipsis:\n... return \"Returning all items\"\n... else:\n... return \"return %r items\" % item\n... \n>>> x = TestEllipsis()\n>>> print x[2]\nreturn 2 items\n>>> print x[...]\nReturning all items\n</code></pre>\n\n<p>Of course, there is the <a href=\"https://docs.python.org/library/constants.html#Ellipsis\" rel=\"noreferrer\" title=\"Ellipsis\">python documentation</a>, and <a href=\"https://docs.python.org/reference/expressions.html#grammar-token-slicing\" rel=\"noreferrer\">language reference</a>. But those aren't very helpful. </p>\n"
},
{
"answer_id": 118508,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 8,
"selected": false,
"text": "<p>The ellipsis is used in numpy to slice higher-dimensional data structures. </p>\n\n<p>It's designed to mean <em>at this point, insert as many full slices (<code>:</code>) to extend the multi-dimensional slice to all dimensions</em>.</p>\n\n<p><strong>Example</strong>:</p>\n\n<pre><code>>>> from numpy import arange\n>>> a = arange(16).reshape(2,2,2,2)\n</code></pre>\n\n<p>Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation</p>\n\n<pre><code>>>> a[..., 0].flatten()\narray([ 0, 2, 4, 6, 8, 10, 12, 14])\n</code></pre>\n\n<p>which is equivalent to</p>\n\n<pre><code>>>> a[:,:,:,0].flatten()\narray([ 0, 2, 4, 6, 8, 10, 12, 14])\n</code></pre>\n\n<p>In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit.</p>\n"
},
{
"answer_id": 120055,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 6,
"selected": false,
"text": "<p>This is another use for Ellipsis, which has nothing to do with slices: I often use it in intra-thread communication with queues, as a mark that signals \"Done\"; it's there, it's an object, it's a singleton, and its name means \"lack of\", and it's not the overused None (which could be put in a queue as part of normal data flow). YMMV.</p>\n"
},
{
"answer_id": 50732784,
"author": "Mauricio Perez",
"author_id": 4363295,
"author_profile": "https://Stackoverflow.com/users/4363295",
"pm_score": 4,
"selected": false,
"text": "<p>As stated in other answers, it can be used for creating slices.\nUseful when you do not want to write many full slices notations (<code>:</code>), or when you are just not sure on what is dimensionality of the array being manipulated.</p>\n\n<p>What I thought important to highlight, and that was missing on the other answers, is that it can be used even when there is no more dimensions to be filled.</p>\n\n<p>Example:</p>\n\n<pre><code>>>> from numpy import arange\n>>> a = arange(4).reshape(2,2)\n</code></pre>\n\n<p>This will result in error:</p>\n\n<pre><code>>>> a[:,0,:]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nIndexError: too many indices for array\n</code></pre>\n\n<p>This will work:</p>\n\n<pre><code>a[...,0,:]\narray([0, 1])\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15677/"
]
| This came up in [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works. | `Ellipsis`, or `...` is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it.
So the syntax for it depends entirely on you, or someone else, having written code to understand it.
Numpy uses it, as stated in the [documentation](http://wiki.scipy.org/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb). Some examples [here](http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c).
In your own class, you'd use it like this:
```
>>> class TestEllipsis(object):
... def __getitem__(self, item):
... if item is Ellipsis:
... return "Returning all items"
... else:
... return "return %r items" % item
...
>>> x = TestEllipsis()
>>> print x[2]
return 2 items
>>> print x[...]
Returning all items
```
Of course, there is the [python documentation](https://docs.python.org/library/constants.html#Ellipsis "Ellipsis"), and [language reference](https://docs.python.org/reference/expressions.html#grammar-token-slicing). But those aren't very helpful. |
118,371 | <p>When a class field is accessed via a getter method by multiple threads, how do you maintain thread safety? Is the synchronized keyword sufficient?</p>
<p>Is this safe:</p>
<pre><code>public class SomeClass {
private int val;
public synchronized int getVal() {
return val;
}
private void setVal(int val) {
this.val = val;
}
}
</code></pre>
<p>or does the setter introduce further complications?</p>
| [
{
"answer_id": 118377,
"author": "Jacob Schoen",
"author_id": 3340,
"author_profile": "https://Stackoverflow.com/users/3340",
"pm_score": 2,
"selected": false,
"text": "<p>From my understanding you should use synchronized on both the getter and the setter methods, and that is sufficient.</p>\n\n<p>Edit: Here is a <a href=\"https://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html\" rel=\"nofollow noreferrer\">link</a> to some more information on synchronization and what not.</p>\n"
},
{
"answer_id": 118388,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 5,
"selected": true,
"text": "<p>If you use 'synchronized' on the setter here too, this code is threadsafe. However it may not be sufficiently granular; if you have 20 getters and setters and they're all synchronized, you may be creating a synchronization bottleneck.</p>\n\n<p>In this specific instance, with a single int variable, then eliminating the 'synchronized' and marking the int field 'volatile' will also ensure visibility (each thread will see the latest value of 'val' when calling the getter) but it may not be synchronized enough for your needs. For example, expecting</p>\n\n<pre><code> int old = someThing.getVal();\n if (old == 1) {\n someThing.setVal(2);\n }\n</code></pre>\n\n<p>to set val to 2 if and only if it's already 1 is incorrect. For this you need an external lock, or some atomic compare-and-set method.</p>\n\n<p>I strongly suggest you read <em>Java Concurrency In Practice</em> by Brian Goetz <em>et al</em>, it has the best coverage of Java's concurrency constructs.</p>\n"
},
{
"answer_id": 118427,
"author": "user13229",
"author_id": 13229,
"author_profile": "https://Stackoverflow.com/users/13229",
"pm_score": -1,
"selected": false,
"text": "<p>Synchronization exists to protect against thread interference and memory consistency errors. By synchronizing on the getVal(), the code is guaranteeing that other synchronized methods on SomeClass do not also execute at the same time. Since there are no other synchronized methods, it isn't providing much value. Also note that reads and writes on primitives have atomic access. That means with careful programming, one doesn't need to synchronize the access to the field. </p>\n\n<p>Read <a href=\"http://java.sun.com/docs/books/tutorial/essential/concurrency/sync.html\" rel=\"nofollow noreferrer\">Sychronization</a>.</p>\n\n<p>Not really sure why this was dropped to -3. I'm simply summarizing what the Synchronization tutorial from Sun says (as well as my own experience). </p>\n\n<blockquote>\n <p>Using simple atomic variable access is\n more efficient than accessing these\n variables through synchronized code,\n but requires more care by the\n programmer to avoid memory consistency\n errors. Whether the extra effort is\n worthwhile depends on the size and\n complexity of the application.</p>\n</blockquote>\n"
},
{
"answer_id": 118452,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to <a href=\"https://stackoverflow.com/questions/118371/how-do-you-ensure-multiple-threads-can-safely-access-a-class-field#118388\">Cowan's comment</a>, you could do the following for a compare and store:</p>\n\n<pre><code>synchronized(someThing) {\n int old = someThing.getVal();\n if (old == 1) {\n someThing.setVal(2);\n }\n}\n</code></pre>\n\n<p>This works because the lock defined via a synchronized method is implicitly the same as the object's lock (<a href=\"http://java.sun.com/docs/books/jls/third_edition/html/statements.html#255769\" rel=\"nofollow noreferrer\">see java language spec</a>).</p>\n"
},
{
"answer_id": 120261,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 0,
"selected": false,
"text": "<p>For simple objects this may suffice. In most cases you should avoid the synchronized keyword because you may run into a synchronization deadlock.</p>\n\n<p>Example:</p>\n\n<pre><code>public class SomeClass {\n\n private Object mutex = new Object();\n private int val = -1; // TODO: Adjust initialization to a reasonable start\n // value\n public int getVal() {\n synchronized ( mutex ) {\n return val;\n }\n }\n\n private void setVal( int val ) {\n synchronized ( mutex ) {\n this.val = val;\n }\n }\n}\n</code></pre>\n\n<p>Assures that only one thread reads or writes to the local instance member.</p>\n\n<p>Read the book \"Concurrent Programming in Java(tm): Design Principles and Patterns (Java (Addison-Wesley))\", maybe <a href=\"http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html</a> is also helpful...</p>\n"
},
{
"answer_id": 1245596,
"author": "CaptainHastings",
"author_id": 135740,
"author_profile": "https://Stackoverflow.com/users/135740",
"pm_score": 1,
"selected": false,
"text": "<p>If your class contains just one variable, then another way of achieving thread-safety is to use the existing AtomicInteger object.</p>\n\n<pre><code>public class ThreadSafeSomeClass {\n\n private final AtomicInteger value = new AtomicInteger(0);\n\n public void setValue(int x){\n value.set(x);\n }\n\n public int getValue(){\n return value.get();\n }\n\n}\n</code></pre>\n\n<p>However, if you add additional variables such that they are dependent (state of one variable depends upon the state of another), then AtomicInteger won't work. </p>\n\n<p>Echoing the suggestion to read \"Java Concurrency in Practice\".</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119/"
]
| When a class field is accessed via a getter method by multiple threads, how do you maintain thread safety? Is the synchronized keyword sufficient?
Is this safe:
```
public class SomeClass {
private int val;
public synchronized int getVal() {
return val;
}
private void setVal(int val) {
this.val = val;
}
}
```
or does the setter introduce further complications? | If you use 'synchronized' on the setter here too, this code is threadsafe. However it may not be sufficiently granular; if you have 20 getters and setters and they're all synchronized, you may be creating a synchronization bottleneck.
In this specific instance, with a single int variable, then eliminating the 'synchronized' and marking the int field 'volatile' will also ensure visibility (each thread will see the latest value of 'val' when calling the getter) but it may not be synchronized enough for your needs. For example, expecting
```
int old = someThing.getVal();
if (old == 1) {
someThing.setVal(2);
}
```
to set val to 2 if and only if it's already 1 is incorrect. For this you need an external lock, or some atomic compare-and-set method.
I strongly suggest you read *Java Concurrency In Practice* by Brian Goetz *et al*, it has the best coverage of Java's concurrency constructs. |
118,415 | <p>My database is located in e.g. california.
My user table has all the user's timezone e.g. -0700 UTC </p>
<p>How can I adjust the time from my database server whenever I display a date to the user who lives in e.g. new york? UTC/GMT -4 hours</p>
| [
{
"answer_id": 118432,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>You should store your data in UTC format and showing it in local timezone format.</p>\n\n<pre><code>DateTime.ToUniversalTime() -> server;\nDateTime.ToLocalTime() -> client\n</code></pre>\n\n<p>You can adjust date/time using AddXXX methods group, but it can be error prone. .NET has support for time zones in <a href=\"http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx\" rel=\"nofollow noreferrer\">System.TimeZoneInfo</a> class.</p>\n"
},
{
"answer_id": 118437,
"author": "Laurent",
"author_id": 10786,
"author_profile": "https://Stackoverflow.com/users/10786",
"pm_score": 0,
"selected": false,
"text": "<p>Up until .NET 3.5 (VS 2008), .NET does not have any built-in support for timezones, apart from converting to and from UTC.</p>\n\n<p>If the time difference is always exactly 3 hours all year long (summer and winter), simply use <strong><code>yourDate.AddHours(3)</code></strong> to change it one way, and <strong><code>yourDate.AddHours(-3)</code></strong> to change it back. Be sure to factor this out into a function explaining the reason for adding/substracting these 3 hours.</p>\n"
},
{
"answer_id": 118440,
"author": "JustinD",
"author_id": 12063,
"author_profile": "https://Stackoverflow.com/users/12063",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a combination of TimeZoneInfo.GetSystemTimeZones() and then use the TimeZoneInfo.BaseUtcOffset property to offset the time in the database based on the offset difference</p>\n\n<p>Info on System.TimeZoneInfo <a href=\"http://msdn.microsoft.com/en-us/library/system.timezoneinfo_members.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 118493,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 0,
"selected": false,
"text": "<p>You know, this is a good question. This year I've done my first DB application and as my input data related to time is an Int64 value, that is what I stored off in the DB. My client applications retrieve it and do DateTime.FromUTC() or FromFileTimeUTC() on that value and do a .LocalTime() to show things in their local time. I've wondered whether this was good/bad/terrible but it has worked well enough for my needs thus far. Of course the work ends up being done by a data access layer library I wrote and not in the DB itself.</p>\n\n<p>Seems to work well enough, but I trust others who have more experience with this sort of thing could point out where this is not the best approach.</p>\n\n<p>Good Luck!</p>\n"
},
{
"answer_id": 1183172,
"author": "jpbochi",
"author_id": 123897,
"author_profile": "https://Stackoverflow.com/users/123897",
"pm_score": 2,
"selected": false,
"text": "<p>If you use .Net, you can use <code>TimeZoneInfo</code>. Since you tagged the question with 'c#', I'll assume you do.</p>\n\n<p>The first step is getting the <code>TimeZoneInfo</code> for the time zone in want to convert to. In your example, NY's time zone. Here's a way you can do it:</p>\n\n<pre><code>//This will get EST time zone\nTimeZoneInfo clientTimeZone\n = TimeZoneInfo.FindSystemTimeZoneById(\"Eastern Standard Time\");\n\n//This will get the local time zone, might be useful\n// if your application is a fat client\nTimeZoneInfo clientTimeZone = TimeZoneInfo.Local;\n</code></pre>\n\n<p>Then, after you read a <code>DateTime</code> from your DB, you need to make sure its <code>Kind</code> is correctly set. Supposing the <code>DateTime</code>'s in the DB are in UTC (by the way, that's usually recommended), you can prepare it to be converted like this:</p>\n\n<pre><code>DateTime aDateTime = dataBaseSource.ReadADateTime();\nDateTime utcDateTime = DateTime.SpecifyKind(aDateTime, DateTimeKind.Utc);\n</code></pre>\n\n<p>Finally, in order to convert to a different time zone, simply do this:</p>\n\n<pre><code>DateTime clientTime = TimeZoneInfo.ConvertTime(utcDateTime, clientTimeZone);\n</code></pre>\n\n<p>Some extra remarks:</p>\n\n<ul>\n<li><code>TimeZoneInfo</code> can be stored in static fields, if you are only interested in a few specific time zones;</li>\n<li><code>TimeZoneInfo</code> store information about daylight saving. So, you wouldn't have to worry about that;</li>\n<li>If your application is web, finding out in which time zone your client is in might be hard. One way is explained here: <a href=\"http://kohari.org/2009/06/15/automagic-time-localization/\" rel=\"nofollow noreferrer\">http://kohari.org/2009/06/15/automagic-time-localization/</a></li>\n</ul>\n\n<p>I hope this helps. :)</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
| My database is located in e.g. california.
My user table has all the user's timezone e.g. -0700 UTC
How can I adjust the time from my database server whenever I display a date to the user who lives in e.g. new york? UTC/GMT -4 hours | You should store your data in UTC format and showing it in local timezone format.
```
DateTime.ToUniversalTime() -> server;
DateTime.ToLocalTime() -> client
```
You can adjust date/time using AddXXX methods group, but it can be error prone. .NET has support for time zones in [System.TimeZoneInfo](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx) class. |
118,423 | <p>I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)?</p>
<p>The reason why I'm asking is that I'm going to be trying out CodeIgniter, and I would like to use it for multiple projects. I would rather not clutter up my machine's DocumentRoot with each one. Suggestions on how to do database migrations are also welcome.</p>
<hr />
<p>Thank you for your responses so far. I should clarify that I'm on Mac OS X. It looks like WAMP is Windows-only. Also, XAMPP looks like a great way to install Apache and many other web tools, but I don't see a way of loading up an instance to serve up a project directory. Mac OS X has both Apache and PHP installed - I'm just looking for a way to get it to serve up a project on a non-standard port.</p>
<p>I just found <a href="http://www.mamp.info/en/mamp-pro/" rel="nofollow noreferrer">MAMP Pro</a> which does what I want, but a more minimalist approach would be better if it's possible. Does anyone have a <code>httpd.conf</code> file that can be edited and dropped into a project directory?</p>
<p>Also, sorry that I just threw in that database migration question. What I'm hoping to find is something that will enable me to push schema changes onto a live server without losing the existing data. I suspect that this is difficult and highly dependent on environmental factors.</p>
| [
{
"answer_id": 118450,
"author": "phloopy",
"author_id": 8507,
"author_profile": "https://Stackoverflow.com/users/8507",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a low up front setup package such as <a href=\"http://www.apachefriends.org/en/index.html\" rel=\"nofollow noreferrer\">XAMPP</a> and run it as a separate instance. There are many other similar projects as well.</p>\n"
},
{
"answer_id": 118460,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 0,
"selected": false,
"text": "<p>For PHP you have several high-quality packages for deploying Apache+Mysql+PHP, such as <a href=\"http://www.wampserver.com/en/\" rel=\"nofollow noreferrer\">WAMP</a> and <a href=\"http://www.apachefriends.org/en/xampp.html\" rel=\"nofollow noreferrer\">XAMPP</a>. Personally, I download the latest binaries of each and install manually to have more fine grained control. There are plenty of online tutorials on how to handle that.</p>\n\n<p>Database migrations should be straightforward - dump the database on the server, either at the command line or through an interface such as <a href=\"http://www.phpmyadmin.net/home_page/index.php\" rel=\"nofollow noreferrer\">PHPMyAdmin</a>, and export it back in similar ways (PHPMyAdmin is recommended if you have no experience with the Mysql command line).</p>\n"
},
{
"answer_id": 118522,
"author": "Bazman",
"author_id": 18521,
"author_profile": "https://Stackoverflow.com/users/18521",
"pm_score": 2,
"selected": false,
"text": "<p>I also download the latest binaries for each and set them up manually. I've found it to be a painless process, as long as you know a little bit about configuring Apache.</p>\n<p>On my development machine, I have apache setup with <a href=\"http://httpd.apache.org/docs/1.3/vhosts/name-based.html\" rel=\"nofollow noreferrer\">name-based virtual hosting</a>. I also have a <a href=\"http://www.dyndns.com/\" rel=\"nofollow noreferrer\">dyndns.org</a> account which maps my development domain to my local machine. <a href=\"http://www.dyndns.com/\" rel=\"nofollow noreferrer\">DynDNS</a> provides a wildcard domain and therefore using name-based virtual hosts I can easily create as many sites (with separate document roots) for as many development domains as I want, all running off the one Apache instance.</p>\n<p>e.g. Apache config for the virtual hosts might be something like</p>\n<pre><code>NameVirtualHost *:80\n\n<virtualhost *:80>\nServerName site1.mydyndns.dyndns.org\nDocumentRoot /site1/documentroot\n</virtualhost>\n\n<virtualhost *:80>\nServerName site2.mydyndns.dyndns.org\nDocumentRoot /site2/documentroot\n</virtualhost>\n</code></pre>\n<p>This has been the quickest and easiest way for me to easily maintain many development sites on my local machine.</p>\n<p>I hope that makes sense.</p>\n"
},
{
"answer_id": 118559,
"author": "Jurassic_C",
"author_id": 20572,
"author_profile": "https://Stackoverflow.com/users/20572",
"pm_score": 1,
"selected": false,
"text": "<p>I don't use macOS, but I do use Apache. In my apache configuration file (on Linux it's usually at <code>/etc/apache2/apache2.conf</code>), look for a reference to a file called <code>ports.conf</code>. Find this file and add the line</p>\n<pre><code>Listen 8080\n</code></pre>\n<p>Then restart the apache process. After that, you should be in business. I apologize in advance if this doesn't work on a mac :)</p>\n"
},
{
"answer_id": 118616,
"author": "Jurassic_C",
"author_id": 20572,
"author_profile": "https://Stackoverflow.com/users/20572",
"pm_score": 3,
"selected": false,
"text": "<p>Sorry Kyle, I don't have enough cred to respond directly to your comment. But if you want to have each project be served on a different port, try setting up your virtual host config exactly like Kelly's above (minus the DNS stuff) except instead of 80, give each virtual host its own port number, assuming that you've added this port to your <code>ports.conf</code> file.</p>\n<pre><code>NameVirtualHost *\n\n<virtualhost *:80>\nDocumentRoot /site1/documentroot\n</virtualhost>\n\n<virtualhost *:81>\nDocumentRoot /site2/documentroot\n</virtualhost>\n\n<virtualhost *:82>\nDocumentRoot /site3/documentroot\n</virtualhost>\n\n<virtualhost *:83>\nDocumentRoot /site4/documentroot\n</virtualhost>\n</code></pre>\n<p>Hope that helps</p>\n"
},
{
"answer_id": 118682,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 6,
"selected": true,
"text": "<p>Your Mac comes with both an Apache Web Server and a build of PHP. It's one of the big reasons the platform is well loved by web developers.</p>\n\n<p>Since you're using Code Igniter, you'll want PHP 5, which is the default version of PHP shipped with 10.5. If you're on a previous version of the OS hop on over to <a href=\"http://www.entropy.ch/home/\" rel=\"nofollow noreferrer\">entropy.ch</a> and install the provided PHP5 package.</p>\n\n<p>Next, you'll want to turn Apache on. In the sharing preferences panel, turn on personal web sharing. This will start up apache on your local machine.</p>\n\n<p>Next, you'll want to setup some fake development URLs to use for your sites. Long standing tradition was that we'd use the fake TLD .dev for this (ex. stackoverflow.dev). However, <code>.dev</code> is now an actual TLD so you probably don't want to do this -- <code>.localhost</code> seems like an emerging defacto standard. Edit your /etc/hosts file and add the following lines</p>\n\n<pre><code>127.0.0.1 www.example.localhost\n127.0.0.1 example.localhost\n</code></pre>\n\n<p>This points the above URLs at your local machine. The last step is configuring apache. Specifically, enabling named virtual hosting, enabling PHP and setting up a few virtual hosts. If you used the entropy PHP package, enabling PHP will already be done. If not, you'll need to edit your http.conf file as described <a href=\"http://foundationphp.com/tutorials/php_leopard.php\" rel=\"nofollow noreferrer\">here</a>. Basically, you're uncommenting the lines that will load the PHP module.</p>\n\n<p>Whenever you make a change to your apache config, you'll need to restart apache for the changes to take effect. At a terminal window, type the following command</p>\n\n<pre><code>sudo apachectl graceful\n</code></pre>\n\n<p>This will gracefully restart apache. If you've made a syntax error in the config file apache won't restart. You can highlight config problems with</p>\n\n<pre><code>sudo apachectl configtest\n</code></pre>\n\n<p>So,with PHP enabled, you'll want to turn on NamedVirtualHosts. This will let apache respond to multiple URLs. Look for the following (or similar) line in your http.conf file and uncomment it.</p>\n\n<pre><code>#NameVirtualHost * \n</code></pre>\n\n<p>Finally, you'll need to tell apache where it should look for the files for your new virtual hosts. You can do so by adding the following to your http.conf file. NOTE: I find it's a good best practice to break out config rules like this into a separate file and use the include directive to include your changes. This will stop any automatic updates from wiping out your changes.</p>\n\n<pre><code><VirtualHost *>\n DocumentRoot /Users/username/Sites/example.localhost\n ServerName example.localhost\n ServerAlias www.example.localhost\n</VirtualHost>\n</code></pre>\n\n<p>You can specify any folder as the DocumentRoot, but I find it convenient to use your personal Sites folder, as it's already been configured with the correct permissions to include files.</p>\n"
},
{
"answer_id": 118788,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 0,
"selected": false,
"text": "<p>You can use MAMP pro but the free version is a very good choice as well. Get it here: <a href=\"http://www.mamp.info/en/mamp.html\" rel=\"nofollow noreferrer\">http://www.mamp.info/en/mamp.html</a></p>\n"
},
{
"answer_id": 122101,
"author": "EmmEff",
"author_id": 9188,
"author_profile": "https://Stackoverflow.com/users/9188",
"pm_score": 0,
"selected": false,
"text": "<p>I might recommend using a separate LAMP virtual appliance for each development environment you wish to experiment with.</p>\n<p>Run them on VMware Server or VirtualBox.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
]
| I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)?
The reason why I'm asking is that I'm going to be trying out CodeIgniter, and I would like to use it for multiple projects. I would rather not clutter up my machine's DocumentRoot with each one. Suggestions on how to do database migrations are also welcome.
---
Thank you for your responses so far. I should clarify that I'm on Mac OS X. It looks like WAMP is Windows-only. Also, XAMPP looks like a great way to install Apache and many other web tools, but I don't see a way of loading up an instance to serve up a project directory. Mac OS X has both Apache and PHP installed - I'm just looking for a way to get it to serve up a project on a non-standard port.
I just found [MAMP Pro](http://www.mamp.info/en/mamp-pro/) which does what I want, but a more minimalist approach would be better if it's possible. Does anyone have a `httpd.conf` file that can be edited and dropped into a project directory?
Also, sorry that I just threw in that database migration question. What I'm hoping to find is something that will enable me to push schema changes onto a live server without losing the existing data. I suspect that this is difficult and highly dependent on environmental factors. | Your Mac comes with both an Apache Web Server and a build of PHP. It's one of the big reasons the platform is well loved by web developers.
Since you're using Code Igniter, you'll want PHP 5, which is the default version of PHP shipped with 10.5. If you're on a previous version of the OS hop on over to [entropy.ch](http://www.entropy.ch/home/) and install the provided PHP5 package.
Next, you'll want to turn Apache on. In the sharing preferences panel, turn on personal web sharing. This will start up apache on your local machine.
Next, you'll want to setup some fake development URLs to use for your sites. Long standing tradition was that we'd use the fake TLD .dev for this (ex. stackoverflow.dev). However, `.dev` is now an actual TLD so you probably don't want to do this -- `.localhost` seems like an emerging defacto standard. Edit your /etc/hosts file and add the following lines
```
127.0.0.1 www.example.localhost
127.0.0.1 example.localhost
```
This points the above URLs at your local machine. The last step is configuring apache. Specifically, enabling named virtual hosting, enabling PHP and setting up a few virtual hosts. If you used the entropy PHP package, enabling PHP will already be done. If not, you'll need to edit your http.conf file as described [here](http://foundationphp.com/tutorials/php_leopard.php). Basically, you're uncommenting the lines that will load the PHP module.
Whenever you make a change to your apache config, you'll need to restart apache for the changes to take effect. At a terminal window, type the following command
```
sudo apachectl graceful
```
This will gracefully restart apache. If you've made a syntax error in the config file apache won't restart. You can highlight config problems with
```
sudo apachectl configtest
```
So,with PHP enabled, you'll want to turn on NamedVirtualHosts. This will let apache respond to multiple URLs. Look for the following (or similar) line in your http.conf file and uncomment it.
```
#NameVirtualHost *
```
Finally, you'll need to tell apache where it should look for the files for your new virtual hosts. You can do so by adding the following to your http.conf file. NOTE: I find it's a good best practice to break out config rules like this into a separate file and use the include directive to include your changes. This will stop any automatic updates from wiping out your changes.
```
<VirtualHost *>
DocumentRoot /Users/username/Sites/example.localhost
ServerName example.localhost
ServerAlias www.example.localhost
</VirtualHost>
```
You can specify any folder as the DocumentRoot, but I find it convenient to use your personal Sites folder, as it's already been configured with the correct permissions to include files. |
118,443 | <p>I have an application that tracks high scores in a game. </p>
<p>I have a <strong>user_scores</strong> table that maps a user_id to a score.</p>
<p>I need to return the 5 highest scores, but only 1 high score for any <em>specific</em> user.</p>
<p>So if user X has the 5 highest scores on a purely numerical basis, I simply return the highest one and then the next 4 user scores.</p>
<p>I have tried to use:</p>
<pre><code>SELECT user_id, score
FROM user_scores
ORDER BY score DESC
GROUP BY user_id
LIMIT 5
</code></pre>
<p>But it seems that MySQL drops any user_id with more than 1 score. </p>
| [
{
"answer_id": 118446,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>You can't group by without a summary-function (SUM, COUNT, etc.)</p>\n\n<p>The GROUP BY clause says how to group the SUMs or COUNTs.</p>\n\n<p>If you simply want to break the long list into bunches with a common value, that's not SQL. That's what your application has to do.</p>\n"
},
{
"answer_id": 118451,
"author": "JustinD",
"author_id": 12063,
"author_profile": "https://Stackoverflow.com/users/12063",
"pm_score": 0,
"selected": false,
"text": "<p>Can you use the Distinct operator to say</p>\n\n<pre><code>SELECT DISTINCT(user_id), score\nFROM user_scores\nORDER BY score DESC\nLIMIT 5\n</code></pre>\n\n<p>didn't test so not sure if that will definitely work</p>\n"
},
{
"answer_id": 118457,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 4,
"selected": true,
"text": "<p>This should work:</p>\n\n<pre><code>SELECT user_id, MAX(score)\nFROM user_scores \nGROUP BY user_id \nORDER BY MAX(score) DESC \nLIMIT 5\n</code></pre>\n"
},
{
"answer_id": 118485,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>Returning only the maximum score for a given user is something like the following.</p>\n\n<pre><code>SELECT user_id, max(score) FROM user_scores\nGROUP BY user_id\n</code></pre>\n"
},
{
"answer_id": 118489,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT user_id, MAX(score) AS score\nFROM user_scores \nGROUP BY user_id\nORDER BY score DESC\nLIMIT 5\n</code></pre>\n\n<p>Should do the job for you... though don't forget to create indexes...</p>\n"
},
{
"answer_id": 118562,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know whether it was a lack of caffeine or just brain explosion, but the answers here were so easy.</p>\n\n<p>I actually got it working with this monstrosity:</p>\n\n<pre><code>SELECT s1.user_id, \n (SELECT score FROM user_scores s2 WHERE s2.user_id = s1.user_id ORDER BY score DESC LIMIT 1) AS score \nFROM user_scores s1 \nGROUP BY s1.user_id\nORDER BY s1.score DESC \nLIMIT 5\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14971/"
]
| I have an application that tracks high scores in a game.
I have a **user\_scores** table that maps a user\_id to a score.
I need to return the 5 highest scores, but only 1 high score for any *specific* user.
So if user X has the 5 highest scores on a purely numerical basis, I simply return the highest one and then the next 4 user scores.
I have tried to use:
```
SELECT user_id, score
FROM user_scores
ORDER BY score DESC
GROUP BY user_id
LIMIT 5
```
But it seems that MySQL drops any user\_id with more than 1 score. | This should work:
```
SELECT user_id, MAX(score)
FROM user_scores
GROUP BY user_id
ORDER BY MAX(score) DESC
LIMIT 5
``` |
118,458 | <p>Along the lines of my previous <a href="https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">question</a>, how can i join a list of strings into a string such that values get quoted cleanly. Something like:</p>
<pre><code>['a', 'one "two" three', 'foo, bar', """both"'"""]
</code></pre>
<p>into:</p>
<pre><code>a, 'one "two" three', "foo, bar", "both\"'"
</code></pre>
<p>I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.</p>
| [
{
"answer_id": 118462,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 4,
"selected": true,
"text": "<p>Using the <code>csv</code> module you can do that way:</p>\n\n<pre><code>import csv\nwriter = csv.writer(open(\"some.csv\", \"wb\"))\nwriter.writerow(the_list)\n</code></pre>\n\n<p>If you need a string just use <code>StringIO</code> instance as a file:</p>\n\n<pre><code>f = StringIO.StringIO()\nwriter = csv.writer(f)\nwriter.writerow(the_list)\nprint f.getvalue()\n</code></pre>\n\n<p>The output: <code>a,\"one \"\"two\"\" three\",\"foo, bar\",\"both\"\"'\"</code></p>\n\n<p><code>csv</code> will write in a way it can read back later.\nYou can fine-tune its output by defining a <code>dialect</code>, just set <code>quotechar</code>, <code>escapechar</code>, etc, as needed:</p>\n\n<pre><code>class SomeDialect(csv.excel):\n delimiter = ','\n quotechar = '\"'\n escapechar = \"\\\\\"\n doublequote = False\n lineterminator = '\\n'\n quoting = csv.QUOTE_MINIMAL\n\nf = cStringIO.StringIO()\nwriter = csv.writer(f, dialect=SomeDialect)\nwriter.writerow(the_list)\nprint f.getvalue()\n</code></pre>\n\n<p>The output: <code>a,one \\\"two\\\" three,\"foo, bar\",both\\\"'</code></p>\n\n<p>The same dialect can be used with csv module to read the string back later to a list.</p>\n"
},
{
"answer_id": 118625,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a slightly simpler alternative.</p>\n\n<pre><code>def quote(s):\n if \"'\" in s or '\"' in s or \",\" in str(s):\n return repr(s)\n return s\n</code></pre>\n\n<p>We only need to quote a value that might have commas or quotes.</p>\n\n<pre><code>>>> x= ['a', 'one \"two\" three', 'foo, bar', 'both\"\\'']\n>>> print \", \".join( map(quote,x) )\na, 'one \"two\" three', 'foo, bar', 'both\"\\''\n</code></pre>\n"
},
{
"answer_id": 121745,
"author": "Alec Thomas",
"author_id": 7980,
"author_profile": "https://Stackoverflow.com/users/7980",
"pm_score": 2,
"selected": false,
"text": "<p>On a related note, Python's <a href=\"http://docs.python.org/lib/standard-encodings.html\" rel=\"nofollow noreferrer\">builtin encoders</a> can also do string escaping:</p>\n\n<pre><code>>>> print \"that's interesting\".encode('string_escape')\nthat\\'s interesting\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
]
| Along the lines of my previous [question](https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat), how can i join a list of strings into a string such that values get quoted cleanly. Something like:
```
['a', 'one "two" three', 'foo, bar', """both"'"""]
```
into:
```
a, 'one "two" three', "foo, bar", "both\"'"
```
I suspect that the csv module will come into play here, but i'm not sure how to get the output I want. | Using the `csv` module you can do that way:
```
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)
```
If you need a string just use `StringIO` instance as a file:
```
f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()
```
The output: `a,"one ""two"" three","foo, bar","both""'"`
`csv` will write in a way it can read back later.
You can fine-tune its output by defining a `dialect`, just set `quotechar`, `escapechar`, etc, as needed:
```
class SomeDialect(csv.excel):
delimiter = ','
quotechar = '"'
escapechar = "\\"
doublequote = False
lineterminator = '\n'
quoting = csv.QUOTE_MINIMAL
f = cStringIO.StringIO()
writer = csv.writer(f, dialect=SomeDialect)
writer.writerow(the_list)
print f.getvalue()
```
The output: `a,one \"two\" three,"foo, bar",both\"'`
The same dialect can be used with csv module to read the string back later to a list. |
118,474 | <p>Has anybody established a good naming convention for action in MVC? I was specifically looking at ASP.net MVC but it is a general question. For instance I have an action which displays the login screen (Login) and one which process the login request from that page (LoginTest). I'm not keen on the names and I have a lot of the applicaiton left to write. </p>
| [
{
"answer_id": 118495,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>The builtin Django actions suffix _done. So LoginDone would be the page that processes Login (in ASP.NET MVC camel case style).</p>\n"
},
{
"answer_id": 120208,
"author": "Jimmeh",
"author_id": 20749,
"author_profile": "https://Stackoverflow.com/users/20749",
"pm_score": 0,
"selected": false,
"text": "<p>It's fairly irrelevant which convention you use for the Controller Action naming, as long as it's consistant for you and easily understood by those working on it. </p>\n\n<p>In the case of your login Actions, LoginDone is fine and in the same was ProcessLogin will is easy to understand, so use a convention that you feel comfortable with. </p>\n\n<p>Personally I would probably side with Login and ProcessLogin, as LoginDone is probably slightly misleading in terms of what the Action is doing - this is of course assuming that the Action is reacting to the users' credentials and checking whether they are valid. You could then pass through to another Action called LoginDone once the login is successful, or LoginFailed if it's not.</p>\n"
},
{
"answer_id": 120227,
"author": "Paul Shannon",
"author_id": 11503,
"author_profile": "https://Stackoverflow.com/users/11503",
"pm_score": 7,
"selected": true,
"text": "<p>Rob Conery at MS suggested some useful RESTful style naming for actions.</p>\n\n<blockquote>\n<pre><code>* Index - the main \"landing\" page. This is also the default endpoint.\n* List - a list of whatever \"thing\" you're showing them - like a list of Products.\n* Show - a particular item of whatever \"thing\" you're showing them (like a Product)\n* Edit - an edit page for the \"thing\"\n* New - a create page for the \"thing\"\n* Create - creates a new \"thing\" (and saves it if you're using a DB)\n* Update - updates the \"thing\"\n* Delete - deletes the \"thing\"\n</code></pre>\n</blockquote>\n\n<p>results in URLs along the lines of (for a forum)</p>\n\n<blockquote>\n<pre><code>* http://mysite/forum/group/list - shows all the groups in my forum\n* http://mysite/forum/forums/show/1 - shows all the topics in forum id=1\n* http://mysite/forums/topic/show/20 - shows all the posts for topic id=20\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://blog.wekeroad.com/2007/12/06/aspnet-mvc-using-restful-architecture/\" rel=\"noreferrer\">Rob Conery on RESTful Architecture for MVC</a></p>\n"
},
{
"answer_id": 122476,
"author": "Dave Weaver",
"author_id": 11991,
"author_profile": "https://Stackoverflow.com/users/11991",
"pm_score": 1,
"selected": false,
"text": "<p>I've found a <a href=\"http://stephenwalther.com/archive/2008/06/27/asp-net-mvc-tip-11-use-standard-controller-action-names.aspx\" rel=\"nofollow noreferrer\">blog post by Stephen Walther</a> useful for finding a consistent naming scheme. His are also derived from a REST-style naming scheme, with some unique exceptions that he explains.</p>\n"
},
{
"answer_id": 30370417,
"author": "Grilse",
"author_id": 1171227,
"author_profile": "https://Stackoverflow.com/users/1171227",
"pm_score": 2,
"selected": false,
"text": "<p>Rails has a nice action naming convention for CRUD operations: <a href=\"http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions\" rel=\"nofollow noreferrer\">Rails Routing from the Outside In</a>.</p>\n\n<p><code>\nHTTP Verb Path Controller#Action Used for\nGET /photos photos#index display a list of all photos\nGET /photos/new photos#new return an HTML form for creating a new photo\nPOST /photos photos#create create a new photo\nGET /photos/:id photos#show display a specific photo\nGET /photos/:id/edit photos#edit return an HTML form for editing a photo\nPATCH/PUT /photos/:id photos#update update a specific photo\nDELETE /photos/:id photos#destroy delete a specific photo\n</code></p>\n\n<p><em>This is essentially an update to <a href=\"https://stackoverflow.com/a/120227/1171227\">Paul Shannon's answer</a>,\nsince his source (Rob Conery) implicitly says that he copied his list from Rails.</em></p>\n"
},
{
"answer_id": 38994001,
"author": "Murat Yıldız",
"author_id": 1604048,
"author_profile": "https://Stackoverflow.com/users/1604048",
"pm_score": 1,
"selected": false,
"text": "<p>Stephen Walther's post on <a href=\"http://stephenwalther.com/archive/2008/06/27/asp-net-mvc-tip-11-use-standard-controller-action-names\" rel=\"nofollow\">ASP.NET MVC Tip #11 – Use Standard Controller Action Names</a> would probably clarify you regarding to naming convention of <code>MVC Action</code> naming convention...</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
]
| Has anybody established a good naming convention for action in MVC? I was specifically looking at ASP.net MVC but it is a general question. For instance I have an action which displays the login screen (Login) and one which process the login request from that page (LoginTest). I'm not keen on the names and I have a lot of the applicaiton left to write. | Rob Conery at MS suggested some useful RESTful style naming for actions.
>
>
> ```
> * Index - the main "landing" page. This is also the default endpoint.
> * List - a list of whatever "thing" you're showing them - like a list of Products.
> * Show - a particular item of whatever "thing" you're showing them (like a Product)
> * Edit - an edit page for the "thing"
> * New - a create page for the "thing"
> * Create - creates a new "thing" (and saves it if you're using a DB)
> * Update - updates the "thing"
> * Delete - deletes the "thing"
>
> ```
>
>
results in URLs along the lines of (for a forum)
>
>
> ```
> * http://mysite/forum/group/list - shows all the groups in my forum
> * http://mysite/forum/forums/show/1 - shows all the topics in forum id=1
> * http://mysite/forums/topic/show/20 - shows all the posts for topic id=20
>
> ```
>
>
[Rob Conery on RESTful Architecture for MVC](http://blog.wekeroad.com/2007/12/06/aspnet-mvc-using-restful-architecture/) |
118,487 | <p>Sorry the title isn't more help. I have a database of media-file URLs that came from two sources: </p>
<p>(1) RSS feeds and (2) manual entries. </p>
<p>I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table '<code>urls</code>' has columns <code>'url, feed_id, timestamp'</code>. </p>
<p><code>feed_id=''</code> for any URL that was entered manually.</p>
<p>How would I write the query? Remember, I want the ten most-recent urls, but only one from any single <code>feed_id</code>.</p>
| [
{
"answer_id": 118523,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 0,
"selected": false,
"text": "<p>You probably want a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/union.html\" rel=\"nofollow noreferrer\">union</a>. Something like this should work:</p>\n\n<pre><code> (SELECT \n url, feed_id, timestamp \n FROM rss_items \n GROUP BY feed_id \n ORDER BY timestamp DESC \n LIMIT 10)\nUNION\n (SELECT \n url, feed_id, timestamp \n FROM manual_items \n GROUP BY feed_id \n ORDER BY timestamp DESC \n LIMIT 10)\nORDER BY timestamp DESC\nLIMIT 10\n</code></pre>\n"
},
{
"answer_id": 118545,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 0,
"selected": false,
"text": "<p>MySQL doesn't have the greatest support for this type of query.</p>\n\n<p>You can do it using a combination of \"GROUP-BY\" and \"HAVING\" clauses, but you'll scan the whole table, which can get costly.</p>\n\n<p>There is a more efficient solution published here, assuming you have an index on group ids:\n<a href=\"http://www.artfulsoftware.com/infotree/queries.php?&bw=1390#104\" rel=\"nofollow noreferrer\">http://www.artfulsoftware.com/infotree/queries.php?&bw=1390#104</a></p>\n\n<p>(Basically, create a temp table, insert into it top K for every group, select from the table, drop the table. This way you get the benefit of the early termination from the LIMIT clause).</p>\n"
},
{
"answer_id": 118563,
"author": "don",
"author_id": 15905,
"author_profile": "https://Stackoverflow.com/users/15905",
"pm_score": 0,
"selected": false,
"text": "<p>Would it work to group by the field that you want to be distinct?</p>\n\n<p>SELECT url, feedid FROM urls GROUP BY feedid ORDER BY timestamp DESC LIMIT 10;</p>\n"
},
{
"answer_id": 118621,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": true,
"text": "<p>Assuming feed_id = 0 is the manually entered stuff this does the trick: </p>\n\n<pre><code>select p.* from programs p\nleft join \n(\n select max(id) id1 from programs\n where feed_id <> 0\n group by feed_id\n order by max(id) desc\n limit 10\n) t on id1 = id\nwhere id1 is not null or feed_id = 0 \norder by id desc\nlimit 10;\n</code></pre>\n\n<p>It works cause the id column is constantly increasing, its also pretty speedy. t is a table alias. </p>\n\n<p>This was my original answer:</p>\n\n<pre><code>(\nselect \n feed_id, url, dt \n from feeds \n where feed_id = ''\n order by dt desc \n limit 10\n)\nunion\n(\n\nselect feed_id, min(url), max(dt) \n from feeds\n where feed_id <> '' \n group by feed_id\n order by dt desc \n limit 10\n)\norder by dt desc\nlimit 10\n</code></pre>\n"
},
{
"answer_id": 118690,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming this table</p>\n\n<pre><code> CREATE TABLE feed (\n feed varchar(20) NOT NULL,\n add_date datetime NOT NULL,\n info varchar(45) NOT NULL,\n PRIMARY KEY (feed,add_date);\n</code></pre>\n\n<p><strong>this query should do what you want</strong>. The inner query selects the last entry by feed and picks the 10 most recent, and then the outer query returns the original records for those entries.</p>\n\n<pre><code> select f2.*\n from (select feed, max(add_date) max_date\n from feed f1\n group by feed\n order by add_date desc\n limit 10) f1\n left join feed f2 on f1.feed=f2.feed and f1.max_date=f2.add_date;\n</code></pre>\n"
},
{
"answer_id": 118722,
"author": "Doug Kaye",
"author_id": 17307,
"author_profile": "https://Stackoverflow.com/users/17307",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the (abbreviated) table:</p>\n\n<pre><code>CREATE TABLE programs (\n id int(11) NOT NULL auto_increment,\n feed_id int(11) NOT NULL,\n `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,\n PRIMARY KEY (id)\n) ENGINE=InnoDB;\n</code></pre>\n\n<p>And here's my query based on sambo99's concept:</p>\n\n<pre><code>(SELECT feed_id,id,timestamp \n FROM programs WHERE feed_id='' \n ORDER BY timestamp DESC LIMIT 10)\nUNION\n (SELECT feed_id,min(id),max(timestamp) \n FROM programs WHERE feed_id<>'' GROUP BY feed_id \n ORDER BY timestamp DESC LIMIT 10)\nORDER BY timestamp DESC LIMIT 10;\n</code></pre>\n\n<p>Seems to work. More testing needed, but at least I understand it. (A good thing!). What's the enhancement using the 'id' column?</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17307/"
]
| Sorry the title isn't more help. I have a database of media-file URLs that came from two sources:
(1) RSS feeds and (2) manual entries.
I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table '`urls`' has columns `'url, feed_id, timestamp'`.
`feed_id=''` for any URL that was entered manually.
How would I write the query? Remember, I want the ten most-recent urls, but only one from any single `feed_id`. | Assuming feed\_id = 0 is the manually entered stuff this does the trick:
```
select p.* from programs p
left join
(
select max(id) id1 from programs
where feed_id <> 0
group by feed_id
order by max(id) desc
limit 10
) t on id1 = id
where id1 is not null or feed_id = 0
order by id desc
limit 10;
```
It works cause the id column is constantly increasing, its also pretty speedy. t is a table alias.
This was my original answer:
```
(
select
feed_id, url, dt
from feeds
where feed_id = ''
order by dt desc
limit 10
)
union
(
select feed_id, min(url), max(dt)
from feeds
where feed_id <> ''
group by feed_id
order by dt desc
limit 10
)
order by dt desc
limit 10
``` |
118,490 | <p>Can anyone recommend a cheap and good RTF control for .Net 1.1 Windows development. It needs to be able to do print/preview and some basic text formatting, fonts etc but nothing too advanced.</p>
<p>Cheers</p>
<p>Andreas</p>
| [
{
"answer_id": 118523,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 0,
"selected": false,
"text": "<p>You probably want a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/union.html\" rel=\"nofollow noreferrer\">union</a>. Something like this should work:</p>\n\n<pre><code> (SELECT \n url, feed_id, timestamp \n FROM rss_items \n GROUP BY feed_id \n ORDER BY timestamp DESC \n LIMIT 10)\nUNION\n (SELECT \n url, feed_id, timestamp \n FROM manual_items \n GROUP BY feed_id \n ORDER BY timestamp DESC \n LIMIT 10)\nORDER BY timestamp DESC\nLIMIT 10\n</code></pre>\n"
},
{
"answer_id": 118545,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 0,
"selected": false,
"text": "<p>MySQL doesn't have the greatest support for this type of query.</p>\n\n<p>You can do it using a combination of \"GROUP-BY\" and \"HAVING\" clauses, but you'll scan the whole table, which can get costly.</p>\n\n<p>There is a more efficient solution published here, assuming you have an index on group ids:\n<a href=\"http://www.artfulsoftware.com/infotree/queries.php?&bw=1390#104\" rel=\"nofollow noreferrer\">http://www.artfulsoftware.com/infotree/queries.php?&bw=1390#104</a></p>\n\n<p>(Basically, create a temp table, insert into it top K for every group, select from the table, drop the table. This way you get the benefit of the early termination from the LIMIT clause).</p>\n"
},
{
"answer_id": 118563,
"author": "don",
"author_id": 15905,
"author_profile": "https://Stackoverflow.com/users/15905",
"pm_score": 0,
"selected": false,
"text": "<p>Would it work to group by the field that you want to be distinct?</p>\n\n<p>SELECT url, feedid FROM urls GROUP BY feedid ORDER BY timestamp DESC LIMIT 10;</p>\n"
},
{
"answer_id": 118621,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": true,
"text": "<p>Assuming feed_id = 0 is the manually entered stuff this does the trick: </p>\n\n<pre><code>select p.* from programs p\nleft join \n(\n select max(id) id1 from programs\n where feed_id <> 0\n group by feed_id\n order by max(id) desc\n limit 10\n) t on id1 = id\nwhere id1 is not null or feed_id = 0 \norder by id desc\nlimit 10;\n</code></pre>\n\n<p>It works cause the id column is constantly increasing, its also pretty speedy. t is a table alias. </p>\n\n<p>This was my original answer:</p>\n\n<pre><code>(\nselect \n feed_id, url, dt \n from feeds \n where feed_id = ''\n order by dt desc \n limit 10\n)\nunion\n(\n\nselect feed_id, min(url), max(dt) \n from feeds\n where feed_id <> '' \n group by feed_id\n order by dt desc \n limit 10\n)\norder by dt desc\nlimit 10\n</code></pre>\n"
},
{
"answer_id": 118690,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming this table</p>\n\n<pre><code> CREATE TABLE feed (\n feed varchar(20) NOT NULL,\n add_date datetime NOT NULL,\n info varchar(45) NOT NULL,\n PRIMARY KEY (feed,add_date);\n</code></pre>\n\n<p><strong>this query should do what you want</strong>. The inner query selects the last entry by feed and picks the 10 most recent, and then the outer query returns the original records for those entries.</p>\n\n<pre><code> select f2.*\n from (select feed, max(add_date) max_date\n from feed f1\n group by feed\n order by add_date desc\n limit 10) f1\n left join feed f2 on f1.feed=f2.feed and f1.max_date=f2.add_date;\n</code></pre>\n"
},
{
"answer_id": 118722,
"author": "Doug Kaye",
"author_id": 17307,
"author_profile": "https://Stackoverflow.com/users/17307",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the (abbreviated) table:</p>\n\n<pre><code>CREATE TABLE programs (\n id int(11) NOT NULL auto_increment,\n feed_id int(11) NOT NULL,\n `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,\n PRIMARY KEY (id)\n) ENGINE=InnoDB;\n</code></pre>\n\n<p>And here's my query based on sambo99's concept:</p>\n\n<pre><code>(SELECT feed_id,id,timestamp \n FROM programs WHERE feed_id='' \n ORDER BY timestamp DESC LIMIT 10)\nUNION\n (SELECT feed_id,min(id),max(timestamp) \n FROM programs WHERE feed_id<>'' GROUP BY feed_id \n ORDER BY timestamp DESC LIMIT 10)\nORDER BY timestamp DESC LIMIT 10;\n</code></pre>\n\n<p>Seems to work. More testing needed, but at least I understand it. (A good thing!). What's the enhancement using the 'id' column?</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Can anyone recommend a cheap and good RTF control for .Net 1.1 Windows development. It needs to be able to do print/preview and some basic text formatting, fonts etc but nothing too advanced.
Cheers
Andreas | Assuming feed\_id = 0 is the manually entered stuff this does the trick:
```
select p.* from programs p
left join
(
select max(id) id1 from programs
where feed_id <> 0
group by feed_id
order by max(id) desc
limit 10
) t on id1 = id
where id1 is not null or feed_id = 0
order by id desc
limit 10;
```
It works cause the id column is constantly increasing, its also pretty speedy. t is a table alias.
This was my original answer:
```
(
select
feed_id, url, dt
from feeds
where feed_id = ''
order by dt desc
limit 10
)
union
(
select feed_id, min(url), max(dt)
from feeds
where feed_id <> ''
group by feed_id
order by dt desc
limit 10
)
order by dt desc
limit 10
``` |
118,501 | <p>If I was, for example, going to <em>count</em> "activities" across many computers and show a rollup of that activity, what would the database look like to store the data? </p>
<p>Simply this? Seems too simple. I'm overthinking this.</p>
<pre><code>ACTIVITYID COUNT
---------- -----
</code></pre>
| [
{
"answer_id": 118568,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, I'm afraid it's that simple, assuming you are only interested in the number of times each activity occurs. Once you have that table populated, you could easily create, for example, a <a href=\"http://en.wikipedia.org/wiki/Histogram\" rel=\"nofollow noreferrer\">histogram</a> of the results by sorting on count and plotting.</p>\n"
},
{
"answer_id": 118580,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 0,
"selected": false,
"text": "<p>I think you could add a DateTime field so that you can do reports of the events in between a certain time interval, or at least know when the last activity count was taken.</p>\n"
},
{
"answer_id": 118672,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 4,
"selected": true,
"text": "<p>If the volume is not going to be ridiculously large, I'd probably create a table that logs each event individually, with a DateTime as @Turnkey suggests, and possibly the machine that logged it, etc.</p>\n\n<pre><code>LOGID (PK) ACTIVITYID SOURCE DATELOGGED\n---------- ---------- ------ ----------\n</code></pre>\n\n<p>That would give you the ability to run a query to get the current count, and also to use the data to determine events in a time period, and/or coming from a specific machine. A clustered index on ActivityID should give you good query performance, and the table is narrow so inserts shouldn't be too costly.</p>\n"
},
{
"answer_id": 118841,
"author": "Metro",
"author_id": 18978,
"author_profile": "https://Stackoverflow.com/users/18978",
"pm_score": 2,
"selected": false,
"text": "<p>I think that the actual activity would create some type of record with at least an ActivityId and ActivityDate in a logging table. An other column might be the identifier of the computer creating the log entry.</p>\n\n<p>You would then create the count by aggregating the activity records over a specified time period.</p>\n\n<p>Metro.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6380/"
]
| If I was, for example, going to *count* "activities" across many computers and show a rollup of that activity, what would the database look like to store the data?
Simply this? Seems too simple. I'm overthinking this.
```
ACTIVITYID COUNT
---------- -----
``` | If the volume is not going to be ridiculously large, I'd probably create a table that logs each event individually, with a DateTime as @Turnkey suggests, and possibly the machine that logged it, etc.
```
LOGID (PK) ACTIVITYID SOURCE DATELOGGED
---------- ---------- ------ ----------
```
That would give you the ability to run a query to get the current count, and also to use the data to determine events in a time period, and/or coming from a specific machine. A clustered index on ActivityID should give you good query performance, and the table is narrow so inserts shouldn't be too costly. |
118,506 | <p>The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.</p>
<p>I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures.</p>
| [
{
"answer_id": 118582,
"author": "Gleb Popoff",
"author_id": 18076,
"author_profile": "https://Stackoverflow.com/users/18076",
"pm_score": 2,
"selected": false,
"text": "<p>You'll need to use <strong>MySQLI</strong> (MySQL Improved Extension) to call stored procedures. Here's how you would call an <strong>SP</strong>:</p>\n\n<pre><code>$mysqli = new MySQLI(user,pass,db);\n\n$result = $mysqli->query(\"CALL sp_mysp()\");\n</code></pre>\n\n<p>When using SPs you'll need close first resultset or you'll receive an error. Here's some more information :</p>\n\n<blockquote>\n <p><a href=\"http://blog.rvdavid.net/using-stored-procedures-mysqli-in-php-5/\" rel=\"nofollow noreferrer\">http://blog.rvdavid.net/using-stored-procedures-mysqli-in-php-5/</a> \n (broken link)</p>\n</blockquote>\n\n<p>Alternatively, you can use <strong>Prepared Statements</strong>, which I find very straight-forward:</p>\n\n<pre><code> $stmt = $mysqli->prepare(\"SELECT Phone FROM MyTable WHERE Name=?\");\n\n $stmt->bind_param(\"s\", $myName);\n\n $stmt->execute();\n</code></pre>\n\n<p>MySQLI Documentation: <a href=\"http://no.php.net/manual/en/book.mysqli.php\" rel=\"nofollow noreferrer\">http://no.php.net/manual/en/book.mysqli.php</a></p>\n"
},
{
"answer_id": 120252,
"author": "mike",
"author_id": 19217,
"author_profile": "https://Stackoverflow.com/users/19217",
"pm_score": 3,
"selected": true,
"text": "<p>Forget about <code>mysqli</code>, it's much harder to use than PDO and should have been already removed. It is true that it introduced huge improvements over mysql, but to achieve the same effect in mysqli sometimes requires enormous effort over PDO i.e. associative <code>fetchAll</code>.</p>\n\n<p>Instead, take a look at <a href=\"http://www.php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">PDO</a>, specifically <a href=\"http://www.php.net/manual/en/pdo.prepared-statements.php\" rel=\"nofollow noreferrer\">\nprepared statements and stored procedures</a>.</p>\n\n<pre><code>$stmt = $dbh->prepare(\"CALL sp_takes_string_returns_string(?)\");\n$value = 'hello';\n$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); \n\n// call the stored procedure\n$stmt->execute();\n\nprint \"procedure returned $value\\n\";\n</code></pre>\n"
},
{
"answer_id": 123991,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 2,
"selected": false,
"text": "<p>It isn't actually mandatory to use mysqli or PDO to call stored procedures in MySQL 5. You can call them just fine with the old mysql_ functions. The only thing you can't do is return multiple result sets.</p>\n\n<p>I've found that returning multiple result sets is somewhat error prone anyway; it does work in some cases but only if the application remembers to consume them all, otherwise the connection is left in a broken state.</p>\n"
},
{
"answer_id": 347393,
"author": "SuperRoach",
"author_id": 25031,
"author_profile": "https://Stackoverflow.com/users/25031",
"pm_score": 0,
"selected": false,
"text": "<p>I have been using ADODB, which is a great thing for abstracting actual commands to make it portable between different SQL Servers (ie mysql to mssql). However, Stored procedures do not appear to be directly supported. What this means, is that I have run a SQL query as if it is a normal one, but to \"call\" the SP. \nAn example query:</p>\n\n<pre><code>$query = \"Call HeatMatchInsert('$mMatch', '$mOpponent', '$mDate', $mPlayers, $mRound, '$mMap', '$mServer', '$mPassword', '$mGame', $mSeason, $mMatchType)\";\n</code></pre>\n\n<p>This isn't accounting for returned data,which is important. I'm guessing that this would be done by setting a @Var , that you can select yourself as the return @Variable .</p>\n\n<p>To be Abstract though, although making a first php stored procedure based web app was very difficult to work around (mssql is very well documented, this is not), It's great after its done - changes are very easy to make due to the seperation.</p>\n"
},
{
"answer_id": 4502524,
"author": "Dan Straw",
"author_id": 345918,
"author_profile": "https://Stackoverflow.com/users/345918",
"pm_score": 3,
"selected": false,
"text": "<p>@michal kralik - unfortunately there's a bug with the MySQL C API that PDO uses which means that running your code as above with some versions of MySQL results in the error: </p>\n\n<blockquote>\n <p>\"Syntax error or access violation: 1414 OUT or INOUT argument $parameter_number for routine $procedure_name is not a variable or NEW pseudo-variable\". </p>\n</blockquote>\n\n<p>You can see the bug report on <a href=\"http://bugs.mysql.com/bug.php?id=11638\" rel=\"noreferrer\">bugs.mysql.com</a>. It's been fixed for version 5.5.3+ & 6.0.8+.</p>\n\n<p>To workaround the issue, you would need to separate in & out parameters, and use user variables to store the result like this:</p>\n\n<pre><code>$stmt = $dbh->prepare(\"CALL sp_takes_string_returns_string(:in_string, @out_string)\");\n$stmt->bindParam(':in_string', 'hello'); \n\n// call the stored procedure\n$stmt->execute();\n\n// fetch the output\n$outputArray = $this->dbh->query(\"select @out_string\")->fetch(PDO::FETCH_ASSOC);\n\nprint \"procedure returned \" . $outputArray['@out_string'] . \"\\n\";\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4665/"
]
| The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.
I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures. | Forget about `mysqli`, it's much harder to use than PDO and should have been already removed. It is true that it introduced huge improvements over mysql, but to achieve the same effect in mysqli sometimes requires enormous effort over PDO i.e. associative `fetchAll`.
Instead, take a look at [PDO](http://www.php.net/manual/en/book.pdo.php), specifically [prepared statements and stored procedures](http://www.php.net/manual/en/pdo.prepared-statements.php).
```
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
``` |
118,516 | <p>My issue is below but would be interested comments from anyone with experience with xlrd.</p>
<p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages" rel="nofollow noreferrer">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p>
<p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p>
<p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties" rel="nofollow noreferrer">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p>
<p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p>
<p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq" rel="nofollow noreferrer">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p>
<p>Any thoughts on:
How to trick xlrd into recognizing the file so I can extract data?
How to use python to automate the explicit 'save as' format to one that xlrd will accept?
Plan B?</p>
| [
{
"answer_id": 118586,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 0,
"selected": false,
"text": "<p>Well here is some code that I did: (look down the bottom): <a href=\"http://anonsvn.labs.jboss.com/labs/jbossrules/trunk/drools-decisiontables/src/main/resources/python-dt/pydt.py\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Not sure about the newer formats - if xlrd can't read it, xlrd needs to have a new version released !</p>\n"
},
{
"answer_id": 118803,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": -1,
"selected": false,
"text": "<p>Do you have to use xlrd? I just downloaded 'UPDATED - Dow Jones Industrial Average Movers - 2008' from that website and had no trouble reading it with <a href=\"http://sourceforge.net/projects/pyexcelerator\" rel=\"nofollow noreferrer\">pyExcelerator</a>.</p>\n\n<pre><code>import pyExcelerator\nbook = pyExcelerator.parse_xls('DJIAMovers.xls')\n</code></pre>\n"
},
{
"answer_id": 125001,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 1,
"selected": false,
"text": "<p>More info on pyExcelerator: To read a file, do this:</p>\n\n<pre><code>import pyExcelerator\nbook = pyExcelerator.parse_xls(filename)\n</code></pre>\n\n<p>where filename is a string that is the filename to read (not a file-like object). This will give you a data structure representing the workbook: a list of pairs, where the first element of the pair is the worksheet name and the second element is the worksheet data.</p>\n\n<p>The worksheet data is a dictionary, where the keys are (row, col) pairs (starting with 0) and the values are the cell contents -- generally int, float, or string. So, for instance, in the simple case of all the data being on the first worksheet:</p>\n\n<pre><code>data = book[0][1]\nprint 'Cell A1 of worksheet %s is: %s' % (book[0][0], repr(data[(0, 0)]))\n</code></pre>\n\n<p>If the cell is empty, you'll get a KeyError. If you're dealing with dates, they <em>may</em> (I forget) come through as integers or floats; if this is the case, you'll need to convert. Basically the rule is: datetime.datetime(1899, 12, 31) + datetime.timedelta(days=n) but that might be off by 1 or 2 (because Excel treats 1900 as a leap-year for compatibility with Lotus, and because I can't remember if 1900-1-1 is 0 or 1), so do some trial-and-error to check. Datetimes are stored as floats, I think (days and fractions of a day).</p>\n\n<p>I think there is partial support for forumulas, but I wouldn't guarantee anything.</p>\n"
},
{
"answer_id": 272170,
"author": "msanders",
"author_id": 1002,
"author_profile": "https://Stackoverflow.com/users/1002",
"pm_score": 2,
"selected": false,
"text": "<p>xlrd support for Office 2007/2008 (OpenXML) format is in alpha test - see the following post in the python-excel newsgroup:\n<a href=\"http://groups.google.com/group/python-excel/msg/0c5f15ad122bf24b?hl=en\" rel=\"nofollow noreferrer\">http://groups.google.com/group/python-excel/msg/0c5f15ad122bf24b?hl=en</a> </p>\n"
},
{
"answer_id": 694688,
"author": "John Machin",
"author_id": 84270,
"author_profile": "https://Stackoverflow.com/users/84270",
"pm_score": 5,
"selected": false,
"text": "<p>FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points:</p>\n\n<ol>\n<li><p>The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python:</p>\n\n<pre><code>>>> open('ComponentReport-DJI.xls', 'rb').read(200)\n'COMPANY NAME\\tPRIMARY EXCHANGE\\tTICKER\\tSTYLE\\tICB SUBSECTOR\\tMARKET CAP RANGE\\\ntWEIGHT PCT\\tUSD CLOSE\\t\\r\\n3M Co.\\tNew York SE\\tMMM\\tN/A\\tDiversified Industria\nls\\tBroad\\t5.15676229508\\t50.33\\t\\r\\nAlcoa Inc.\\tNew York SE\\tA'\n</code></pre>\n\n<p>You can read this file using Python's csv module ... just use <code>delimiter=\"\\t\"</code> in your call to <code>csv.reader()</code>.</p></li>\n<li><p>xlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation.</p></li>\n<li><p>pyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out <a href=\"http://groups.google.com/group/python-excel\" rel=\"noreferrer\">http://groups.google.com/group/python-excel</a></p></li>\n</ol>\n\n<p>HTH\nJohn</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| My issue is below but would be interested comments from anyone with experience with xlrd.
I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <http://www.djindexes.com/mdsidx/?event=showAverages>)
When I open the file unmodified I get a nasty BIFF error (binary format not recognized)
However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <http://skitch.com/alok/ssa3/componentreport-dji.xls-properties>)
If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls
Here is a pastebin of an ipython session replicating the issue: <http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq>
Any thoughts on:
How to trick xlrd into recognizing the file so I can extract data?
How to use python to automate the explicit 'save as' format to one that xlrd will accept?
Plan B? | FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points:
1. The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python:
```
>>> open('ComponentReport-DJI.xls', 'rb').read(200)
'COMPANY NAME\tPRIMARY EXCHANGE\tTICKER\tSTYLE\tICB SUBSECTOR\tMARKET CAP RANGE\
tWEIGHT PCT\tUSD CLOSE\t\r\n3M Co.\tNew York SE\tMMM\tN/A\tDiversified Industria
ls\tBroad\t5.15676229508\t50.33\t\r\nAlcoa Inc.\tNew York SE\tA'
```
You can read this file using Python's csv module ... just use `delimiter="\t"` in your call to `csv.reader()`.
2. xlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation.
3. pyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out <http://groups.google.com/group/python-excel>
HTH
John |
118,528 | <h2>I've actually solved this, but I'm posting it for posterity.</h2>
<p>I ran into a very odd issue with the DataGridView on my dual-monitor system. The issue manifests itself as an EXTREMELY slow repaint of the control (<em>like 30 seconds for a full repaint</em>), but only when it is on one of my screens. When on the other, the repaint speed is fine.</p>
<p>I have an Nvidia 8800 GT with the latest non-beta drivers (175. something). Is it a driver bug? I'll leave that up in the air, since I have to live with this particular configuration. (It does not happen on ATI cards, though...)</p>
<p>The paint speed has nothing to do with the cell contents, and custom drawing doesn't improve the performance at all - even when just painting a solid rectangle.</p>
<p>I later find out that placing a ElementHost (from the System.Windows.Forms.Integration namespace) on the form corrects the problem. It doesn't have to be messed with; it just needs to be a child of the form the DataGridView is also on. It can be resized to (0, 0) as long as the <em>Visible</em> property is true.</p>
<p>I don't want to explicitly add the .NET 3/3.5 dependency to my application; I make a method to create this control at runtime (if it can) using reflection. It works, and at least it fails gracefully on machines that don't have the required library - it just goes back to being slow.</p>
<p>This method also lets me apply to fix while the app is running, making it easier to see what the WPF libraries are changing on my form (using Spy++).</p>
<p>After a lot of trial and error, I notice that enabling double buffering on the control itself (as opposed to just the form) corrects the issue!</p>
<hr>
<p>So, you just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!</p>
<pre><code>class CustomDataGridView: DataGridView
{
public CustomDataGridView()
{
DoubleBuffered = true;
}
}
</code></pre>
<p>As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (<em>although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency</em>).</p>
<p>It is sad that such a trivially simple thing ate up so much of my time...</p>
| [
{
"answer_id": 157386,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 7,
"selected": true,
"text": "<p>You just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!</p>\n\n<pre><code>\nclass CustomDataGridView: DataGridView\n{\n public CustomDataGridView()\n {\n DoubleBuffered = true;\n } \n}\n</code></pre>\n\n<p>As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency).</p>\n\n<p>It is sad that such a trivially simple thing ate up so much of my time...</p>\n\n<p>Note: Making the answer an answer so the question can be marked as answered</p>\n"
},
{
"answer_id": 180044,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>We've experienced a similar problem using .NET 3.0 and DataGridView on a dual monitor system.</p>\n\n<p>Our application would display the grid with a gray background, indicating that the cells could not be changed. Upon selecting a \"change settings\" button, the program would change the background color of the cells white to indicate to the user that the cell text could be changed. A \"cancel\" button would change the background color of the aforementioned cells back to gray.</p>\n\n<p>As the background color changed there would be a flicker, a brief impression of a default sized grid with the same number of rows and columns. This problem would only occur on the primary monitor (never the secondary) and it would not occur on a single monitor system.</p>\n\n<p>Double buffering the control, using the above example, solved our problem. We greatly appreciated your help.</p>\n"
},
{
"answer_id": 592780,
"author": "Richard Morgan",
"author_id": 2258,
"author_profile": "https://Stackoverflow.com/users/2258",
"pm_score": 1,
"selected": false,
"text": "<p>Just to add what we did to fix this issue: We upgraded to the latest Nvidia drivers solved the problem. No code had to be rewritten.</p>\n\n<p>For completeness, the card was an Nvidia Quadro NVS 290 with drivers dated March 2008 (v. 169). Upgrading to the latest (v. 182 dated Feb 2009) significantly improved the paint events for all my controls, especially for the DataGridView.</p>\n\n<p>This issue was not seen on any ATI cards (where development occurs).</p>\n"
},
{
"answer_id": 1506066,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 6,
"selected": false,
"text": "<p>Here is some code that sets the property using reflection, without subclassing as Benoit suggests.</p>\n\n<pre><code>typeof(DataGridView).InvokeMember(\n \"DoubleBuffered\", \n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty,\n null, \n myDataGridViewObject, \n new object[] { true });\n</code></pre>\n"
},
{
"answer_id": 1533992,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I found a solution to the problem. Go to troubleshoot tab in the advanced display properties and check the hardware acceleration slider. When I got my new company PC from IT, it was set to one tick from full and I didn't have any problems with datagrids. Once I updated the video card driver and set it to full, painting of datagrid controls became very slow. So I reset it back to where it was and the problem went away. </p>\n\n<p>Hope this trick works for you as well. </p>\n"
},
{
"answer_id": 10304220,
"author": "GELR",
"author_id": 1354522,
"author_profile": "https://Stackoverflow.com/users/1354522",
"pm_score": 4,
"selected": false,
"text": "<p>For people searching how to do it in VB.NET, here is the code:</p>\n\n<pre><code>DataGridView1.GetType.InvokeMember(\"DoubleBuffered\", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.SetProperty, Nothing, DataGridView1, New Object() {True})\n</code></pre>\n"
},
{
"answer_id": 15990262,
"author": "Kev",
"author_id": 745813,
"author_profile": "https://Stackoverflow.com/users/745813",
"pm_score": 3,
"selected": false,
"text": "<p>The answer to this worked for me too. I thought I would add a refinement that I think should be standard practise for anyone implementing the solution.</p>\n\n<p>The solution works well except when the UI is being run as a client session under remote desktop, especially where the available network bandwidth is low. In such a case, performance can be made worse by the use of double-buffering. Therefore, I suggest the following as a more complete answer:</p>\n\n<pre><code>class CustomDataGridView: DataGridView\n{\n public CustomDataGridView()\n {\n // if not remote desktop session then enable double-buffering optimization\n if (!System.Windows.Forms.SystemInformation.TerminalServerSession)\n DoubleBuffered = true;\n } \n}\n</code></pre>\n\n<p>For more details, refer to <a href=\"https://stackoverflow.com/questions/973802/detecting-remote-desktop-connection\">Detecting remote desktop connection</a></p>\n"
},
{
"answer_id": 16625788,
"author": "brtmckn",
"author_id": 2396973,
"author_profile": "https://Stackoverflow.com/users/2396973",
"pm_score": 4,
"selected": false,
"text": "<p>Adding to previous posts, for Windows Forms applications this is what I use for DataGridView components to make them fast. The code for the class DrawingControl is below.</p>\n\n<pre><code>DrawingControl.SetDoubleBuffered(control)\nDrawingControl.SuspendDrawing(control)\nDrawingControl.ResumeDrawing(control)\n</code></pre>\n\n<p>Call DrawingControl.SetDoubleBuffered(control) after InitializeComponent() in the constructor.</p>\n\n<p>Call DrawingControl.SuspendDrawing(control) before doing big data updates.</p>\n\n<p>Call DrawingControl.ResumeDrawing(control) after doing big data updates.</p>\n\n<p>These last 2 are best done with a try/finally block. (or even better rewrite the class as <code>IDisposable</code> and call <code>SuspendDrawing()</code> in the constructor and <code>ResumeDrawing()</code> in <code>Dispose()</code>.)</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\npublic static class DrawingControl\n{\n [DllImport(\"user32.dll\")]\n public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);\n\n private const int WM_SETREDRAW = 11;\n\n /// <summary>\n /// Some controls, such as the DataGridView, do not allow setting the DoubleBuffered property.\n /// It is set as a protected property. This method is a work-around to allow setting it.\n /// Call this in the constructor just after InitializeComponent().\n /// </summary>\n /// <param name=\"control\">The Control on which to set DoubleBuffered to true.</param>\n public static void SetDoubleBuffered(Control control)\n {\n // if not remote desktop session then enable double-buffering optimization\n if (!System.Windows.Forms.SystemInformation.TerminalServerSession)\n {\n\n // set instance non-public property with name \"DoubleBuffered\" to true\n typeof(Control).InvokeMember(\"DoubleBuffered\",\n System.Reflection.BindingFlags.SetProperty |\n System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.NonPublic,\n null,\n control,\n new object[] { true });\n }\n }\n\n /// <summary>\n /// Suspend drawing updates for the specified control. After the control has been updated\n /// call DrawingControl.ResumeDrawing(Control control).\n /// </summary>\n /// <param name=\"control\">The control to suspend draw updates on.</param>\n public static void SuspendDrawing(Control control)\n {\n SendMessage(control.Handle, WM_SETREDRAW, false, 0);\n }\n\n /// <summary>\n /// Resume drawing updates for the specified control.\n /// </summary>\n /// <param name=\"control\">The control to resume draw updates on.</param>\n public static void ResumeDrawing(Control control)\n {\n SendMessage(control.Handle, WM_SETREDRAW, true, 0);\n control.Refresh();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24146731,
"author": "user3727004",
"author_id": 3727004,
"author_profile": "https://Stackoverflow.com/users/3727004",
"pm_score": 1,
"selected": false,
"text": "<p>Best!:</p>\n\n<pre><code>Private Declare Function SendMessage Lib \"user32\" _\n Alias \"SendMessageA\" _\n (ByVal hWnd As Integer, ByVal wMsg As Integer, _\n ByVal wParam As Integer, ByRef lParam As Object) _\n As Integer\n\nConst WM_SETREDRAW As Integer = &HB\n\nPublic Sub SuspendControl(this As Control)\n SendMessage(this.Handle, WM_SETREDRAW, 0, 0)\nEnd Sub\n\nPublic Sub ResumeControl(this As Control)\n RedrawControl(this, True)\nEnd Sub\n\nPublic Sub RedrawControl(this As Control, refresh As Boolean)\n SendMessage(this.Handle, WM_SETREDRAW, 1, 0)\n If refresh Then\n this.Refresh()\n End If\nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5927/"
]
| I've actually solved this, but I'm posting it for posterity.
------------------------------------------------------------
I ran into a very odd issue with the DataGridView on my dual-monitor system. The issue manifests itself as an EXTREMELY slow repaint of the control (*like 30 seconds for a full repaint*), but only when it is on one of my screens. When on the other, the repaint speed is fine.
I have an Nvidia 8800 GT with the latest non-beta drivers (175. something). Is it a driver bug? I'll leave that up in the air, since I have to live with this particular configuration. (It does not happen on ATI cards, though...)
The paint speed has nothing to do with the cell contents, and custom drawing doesn't improve the performance at all - even when just painting a solid rectangle.
I later find out that placing a ElementHost (from the System.Windows.Forms.Integration namespace) on the form corrects the problem. It doesn't have to be messed with; it just needs to be a child of the form the DataGridView is also on. It can be resized to (0, 0) as long as the *Visible* property is true.
I don't want to explicitly add the .NET 3/3.5 dependency to my application; I make a method to create this control at runtime (if it can) using reflection. It works, and at least it fails gracefully on machines that don't have the required library - it just goes back to being slow.
This method also lets me apply to fix while the app is running, making it easier to see what the WPF libraries are changing on my form (using Spy++).
After a lot of trial and error, I notice that enabling double buffering on the control itself (as opposed to just the form) corrects the issue!
---
So, you just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!
```
class CustomDataGridView: DataGridView
{
public CustomDataGridView()
{
DoubleBuffered = true;
}
}
```
As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (*although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency*).
It is sad that such a trivially simple thing ate up so much of my time... | You just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!
```
class CustomDataGridView: DataGridView
{
public CustomDataGridView()
{
DoubleBuffered = true;
}
}
```
As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency).
It is sad that such a trivially simple thing ate up so much of my time...
Note: Making the answer an answer so the question can be marked as answered |
118,540 | <p>First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.</p>
<p>Here's the situation</p>
<p>I have an abstract concept of a grid, with Y steps exactly Y_STEP apart (the x steps are working fine so ignore them for now)</p>
<p>The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y_OFFSET</p>
<p>to snap to the grid I've got the following code (python)</p>
<pre><code>def snapToGrid(originalPos, offset, step):
index = int((originalPos - offset) / step) #truncates the remainder away
return index * gap + offset
</code></pre>
<p>so I pass the cursor position, Y_OFFSET and Y_STEP into that function and it returns me the nearest floored y position on the grid</p>
<p>That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird.</p>
<p>Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it.</p>
<p>Here's a snippet of the cursor's mouseMotion code:</p>
<pre><code>def mouseMotion(self, event):
pixelPos = event.pos[Y]
odePos = Scroll.pixelPosToOdePos(pixelPos)
self.tool.positionChanged(odePos)
</code></pre>
<p>So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step.</p>
<p>Here's the relevant Scroll code</p>
<pre><code>def pixelPosToOdePos(pixelPos):
offsetPixelPos = pixelPos - self.viewPortOffset
return pixelsToOde(offsetPixelPos)
def pixelsToOde(pixels):
return float(pixels) / float(pixels_in_an_ode_unit)
</code></pre>
<p>And the tools update code</p>
<pre><code>def positionChanged(self, newPos):
self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP)
</code></pre>
<p>The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code:</p>
<pre><code>#in Tool
def render(self, screen):
Scroll.render(screen, self.image, self.snappedPos)
#in Scroll
def render(self, screen, image, odePos):
pixelPos = self.odePosToPixelPos(odePos)
screen.blit(image, pixelPos) # screen is a surface from pygame for the curious
def odePosToPixelPos(self.odePos):
offsetPos = odePos + self.viewPortOffset
return odeToPixels(offsetPos)
def odeToPixels(odeUnits):
return int(odeUnits * pixels_in_an_ode_unit)
</code></pre>
<p>Whew, that was a long explanation. Hope you're still with me... </p>
<p>The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor.<br>
It starts snapping to the Y step exactly 1 step below the cursor.
Additionally it appears to phase in and out of allignment.<br>
At some scrolls it is out by 1 and other scrolls it is spot on.<br>
It's never out by more than 1 and it's always snapping to a valid grid location.</p>
<p>Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior.</p>
<p>Anyone familiar with coordinate spaces, scrolling and snapping?</p>
| [
{
"answer_id": 118645,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have a typo in positionChanged() ?</p>\n\n<pre><code>def positionChanged(self, newPos):\n self.snappedPos = snapToGrid(newPos, Y_OFFSET, Y_STEP)\n</code></pre>\n\n<p>I guess you are off by one pixel because of the accuracy problems during float division. Try changing your snapToGrid() to this:</p>\n\n<pre><code>def snapToGrid(originalPos, offset, step):\n EPS = 1e-6\n index = int((originalPos - offset) / step + EPS) #truncates the remainder away\n return index * gap + offset\n</code></pre>\n"
},
{
"answer_id": 118847,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for the answer, there may be a typo, but I can't see it...</p>\n\n<p>Unfortunately the change to snapToGrid didn't make a difference, so I don't think that's the issue.</p>\n\n<p>It's not off by one pixel, but rather it's off by Y_STEP. Playing around with it some more I've found that I can't get it to be exact at any point that the screen is scrolled up and also that it happens towards the top of the screen, which I suspect is ODE position zero, so I'm guessing my problem is around small or negative values.</p>\n"
},
{
"answer_id": 119022,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>Ok, I'm answering my own question here, as alexk mentioned, using int to truncate was my mistake. </p>\n\n<p>The behaviour I'm after is best modeled by math.floor().</p>\n\n<p>Apologies, the original question does not contain enough information to really work out what the problem is. I didn't have the extra bit of information at that point.</p>\n\n<p>With regards to the typo note, I think I may be using the context in a confusing manner... From the perspective of the positionChanged() function, the parameter is a new position coming in.<br>\nFrom the perspective of the snapToGrid() function the parameter is an original position which is being changed to a snapped position.\nThe language is like that because part of it is in my event handling code and the other part is in my general services code. I should have changed it for the example</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.
Here's the situation
I have an abstract concept of a grid, with Y steps exactly Y\_STEP apart (the x steps are working fine so ignore them for now)
The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y\_OFFSET
to snap to the grid I've got the following code (python)
```
def snapToGrid(originalPos, offset, step):
index = int((originalPos - offset) / step) #truncates the remainder away
return index * gap + offset
```
so I pass the cursor position, Y\_OFFSET and Y\_STEP into that function and it returns me the nearest floored y position on the grid
That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird.
Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it.
Here's a snippet of the cursor's mouseMotion code:
```
def mouseMotion(self, event):
pixelPos = event.pos[Y]
odePos = Scroll.pixelPosToOdePos(pixelPos)
self.tool.positionChanged(odePos)
```
So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step.
Here's the relevant Scroll code
```
def pixelPosToOdePos(pixelPos):
offsetPixelPos = pixelPos - self.viewPortOffset
return pixelsToOde(offsetPixelPos)
def pixelsToOde(pixels):
return float(pixels) / float(pixels_in_an_ode_unit)
```
And the tools update code
```
def positionChanged(self, newPos):
self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP)
```
The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code:
```
#in Tool
def render(self, screen):
Scroll.render(screen, self.image, self.snappedPos)
#in Scroll
def render(self, screen, image, odePos):
pixelPos = self.odePosToPixelPos(odePos)
screen.blit(image, pixelPos) # screen is a surface from pygame for the curious
def odePosToPixelPos(self.odePos):
offsetPos = odePos + self.viewPortOffset
return odeToPixels(offsetPos)
def odeToPixels(odeUnits):
return int(odeUnits * pixels_in_an_ode_unit)
```
Whew, that was a long explanation. Hope you're still with me...
The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor.
It starts snapping to the Y step exactly 1 step below the cursor.
Additionally it appears to phase in and out of allignment.
At some scrolls it is out by 1 and other scrolls it is spot on.
It's never out by more than 1 and it's always snapping to a valid grid location.
Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior.
Anyone familiar with coordinate spaces, scrolling and snapping? | Ok, I'm answering my own question here, as alexk mentioned, using int to truncate was my mistake.
The behaviour I'm after is best modeled by math.floor().
Apologies, the original question does not contain enough information to really work out what the problem is. I didn't have the extra bit of information at that point.
With regards to the typo note, I think I may be using the context in a confusing manner... From the perspective of the positionChanged() function, the parameter is a new position coming in.
From the perspective of the snapToGrid() function the parameter is an original position which is being changed to a snapped position.
The language is like that because part of it is in my event handling code and the other part is in my general services code. I should have changed it for the example |
118,547 | <p>I am looking for a way to create a ZIP file from a folder in Windows C/C++ APIs. I can find the way to do this in VBScript using the Shell32.Application CopyHere method, and I found a tutorial explaining how to do it in C# also, but nothing for the C API (C++ is fine too, project already uses MFC).</p>
<p>I'd be really grateful if anyone can share some sample C code that can successfully create a zip file on Windows XP/2003. Failing that, if someone can find solid docs or a tutorial that would be great, since MSDN searches don't turn up much. I'm really hoping to avoid having to ship a third-party lib for this, because the functionality is obviously there, I just can't figure out how to access it. Google searches turn up nothing useful, just tantalizing bits and pieces of information. Here's hoping someone in the community has sorted this out and can share it for posterity!</p>
| [
{
"answer_id": 118602,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 1,
"selected": false,
"text": "<p>I do not think that MFC or the Windows standard C/C++ APIs provide an interface to the built in zip functionality.</p>\n"
},
{
"answer_id": 118606,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 4,
"selected": true,
"text": "<p>EDIT: This answer is old, but I cannot delete it because it was accepted. See the next one</p>\n\n<p><a href=\"https://stackoverflow.com/a/121720/3937\">https://stackoverflow.com/a/121720/3937</a></p>\n\n<p>----- ORIGINAL ANSWER -----</p>\n\n<p>There is sample code to do that here</p>\n\n<p>[EDIT: Link is now broken]</p>\n\n<p><a href=\"http://www.eggheadcafe.com/software/aspnet/31056644/using-shfileoperation-to.aspx\" rel=\"nofollow noreferrer\">http://www.eggheadcafe.com/software/aspnet/31056644/using-shfileoperation-to.aspx</a></p>\n\n<p>Make sure you read about how to handle monitoring for the thread to complete.</p>\n\n<p>Edit: From the comments, this code only works on existing zip file, but @<a href=\"https://stackoverflow.com/users/20135/simonbuchanmyopenidcom\">Simon</a> provided this code to create a blank zip file</p>\n\n<pre><code>FILE* f = fopen(\"path\", \"wb\");\nfwrite(\"\\x50\\x4B\\x05\\x06\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\", 22, 1, f);\nfclose(f);\n</code></pre>\n"
},
{
"answer_id": 118607,
"author": "EmmEff",
"author_id": 9188,
"author_profile": "https://Stackoverflow.com/users/9188",
"pm_score": 0,
"selected": false,
"text": "<p>You could always statically link to the freeware zip library if you don't want to ship another library...</p>\n"
},
{
"answer_id": 118611,
"author": "Vincent McNabb",
"author_id": 16299,
"author_profile": "https://Stackoverflow.com/users/16299",
"pm_score": 2,
"selected": false,
"text": "<p>A quick Google search came up with this site: <a href=\"http://www.example-code.com/vcpp/vcUnzip.asp\" rel=\"nofollow noreferrer\">http://www.example-code.com/vcpp/vcUnzip.asp</a> which has a very short example to unzip a file using a downloadable library. There are plenty of other libraries available. Another example is availaible on Code Project entitled <a href=\"https://www.codeproject.com/Articles/611/Zip-and-Unzip-in-the-MFC-way\" rel=\"nofollow noreferrer\">Zip and Unzip in the MFC way</a> which has an entire gui example. If you want to do it with .NET then there is always the classes under System.Compression.</p>\n\n<p>There is also the 7-Zip libarary <a href=\"http://www.7-zip.org/sdk.html\" rel=\"nofollow noreferrer\">http://www.7-zip.org/sdk.html</a>. This includes source for several languages, and examples.</p>\n"
},
{
"answer_id": 118943,
"author": "Sergey Kornilov",
"author_id": 10969,
"author_profile": "https://Stackoverflow.com/users/10969",
"pm_score": 3,
"selected": false,
"text": "<p>We use XZip for this purpose. It's free, comes as C++ source code and works nicely. </p>\n\n<p><a href=\"http://www.codeproject.com/KB/cpp/xzipunzip.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cpp/xzipunzip.aspx</a></p>\n"
},
{
"answer_id": 121720,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 4,
"selected": false,
"text": "<p>As noted elsewhere in the comments, this will only work on a already-created Zip file. The content must also not already exist in the zip file, or an error will be displayed. Here is the working sample code I was able to create based on the accepted answer. You need to link to shell32.lib and also kernel32.lib (for CreateToolhelp32Snapshot).</p>\n\n<pre><code>#include <windows.h>\n#include <shldisp.h>\n#include <tlhelp32.h>\n#include <stdio.h>\n\nint main(int argc, TCHAR* argv[])\n{\n DWORD strlen = 0;\n char szFrom[] = \"C:\\\\Temp\",\n szTo[] = \"C:\\\\Sample.zip\";\n HRESULT hResult;\n IShellDispatch *pISD;\n Folder *pToFolder = NULL;\n VARIANT vDir, vFile, vOpt;\n BSTR strptr1, strptr2;\n\n CoInitialize(NULL);\n\n hResult = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, IID_IShellDispatch, (void **)&pISD);\n\n if (SUCCEEDED(hResult) && pISD != NULL)\n {\n strlen = MultiByteToWideChar(CP_ACP, 0, szTo, -1, 0, 0);\n strptr1 = SysAllocStringLen(0, strlen);\n MultiByteToWideChar(CP_ACP, 0, szTo, -1, strptr1, strlen);\n\n VariantInit(&vDir);\n vDir.vt = VT_BSTR;\n vDir.bstrVal = strptr1;\n hResult = pISD->NameSpace(vDir, &pToFolder);\n\n if (SUCCEEDED(hResult))\n {\n strlen = MultiByteToWideChar(CP_ACP, 0, szFrom, -1, 0, 0);\n strptr2 = SysAllocStringLen(0, strlen);\n MultiByteToWideChar(CP_ACP, 0, szFrom, -1, strptr2, strlen);\n\n VariantInit(&vFile);\n vFile.vt = VT_BSTR;\n vFile.bstrVal = strptr2;\n\n VariantInit(&vOpt);\n vOpt.vt = VT_I4;\n vOpt.lVal = 4; // Do not display a progress dialog box\n\n hResult = NULL;\n printf(\"Copying %s to %s ...\\n\", szFrom, szTo);\n hResult = pToFolder->CopyHere(vFile, vOpt); //NOTE: this appears to always return S_OK even on error\n /*\n * 1) Enumerate current threads in the process using Thread32First/Thread32Next\n * 2) Start the operation\n * 3) Enumerate the threads again\n * 4) Wait for any new threads using WaitForMultipleObjects\n *\n * Of course, if the operation creates any new threads that don't exit, then you have a problem. \n */\n if (hResult == S_OK) {\n //NOTE: hard-coded for testing - be sure not to overflow the array if > 5 threads exist\n HANDLE hThrd[5]; \n HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPALL ,0); //TH32CS_SNAPMODULE, 0);\n DWORD NUM_THREADS = 0;\n if (h != INVALID_HANDLE_VALUE) {\n THREADENTRY32 te;\n te.dwSize = sizeof(te);\n if (Thread32First(h, &te)) {\n do {\n if (te.dwSize >= (FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) ) {\n //only enumerate threads that are called by this process and not the main thread\n if((te.th32OwnerProcessID == GetCurrentProcessId()) && (te.th32ThreadID != GetCurrentThreadId()) ){\n //printf(\"Process 0x%04x Thread 0x%04x\\n\", te.th32OwnerProcessID, te.th32ThreadID);\n hThrd[NUM_THREADS] = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);\n NUM_THREADS++;\n }\n }\n te.dwSize = sizeof(te);\n } while (Thread32Next(h, &te));\n }\n CloseHandle(h);\n\n printf(\"waiting for all threads to exit...\\n\");\n //Wait for all threads to exit\n WaitForMultipleObjects(NUM_THREADS, hThrd , TRUE , INFINITE);\n\n //Close All handles\n for ( DWORD i = 0; i < NUM_THREADS ; i++ ){\n CloseHandle( hThrd[i] );\n }\n } //if invalid handle\n } //if CopyHere() hResult is S_OK\n\n SysFreeString(strptr2);\n pToFolder->Release();\n }\n\n SysFreeString(strptr1);\n pISD->Release();\n }\n\n CoUninitialize();\n\n printf (\"Press ENTER to exit\\n\");\n getchar();\n return 0;\n\n}\n</code></pre>\n\n<p>I have decided not to go this route despite getting semi-functional code, since after further investigation, it appears the Folder::CopyHere() method does not actually respect the vOptions passed to it, which means you cannot force it to overwrite files or not display error dialogs to the user.</p>\n\n<p>In light of that, I tried the XZip library mentioned by another poster as well. This library functions fine for creating a Zip archive, but note that the ZipAdd() function called with ZIP_FOLDER is not recursive - it merely creates a folder in the archive. In order to recursively zip an archive you will need to use the AddFolderContent() function. For example, to create a C:\\Sample.zip and Add the C:\\Temp folder to it, use the following:</p>\n\n<pre><code>HZIP newZip = CreateZip(\"C:\\\\Sample.zip\", NULL, ZIP_FILENAME);\nBOOL retval = AddFolderContent(newZip, \"C:\", \"temp\");\n</code></pre>\n\n<p>Important note: the AddFolderContent() function is not functional as included in the XZip library. It will recurse into the directory structure but fails to add any files to the zip archive, due to a bug in the paths passed to ZipAdd(). In order to use this function you'll need to edit the source and change this line:</p>\n\n<pre><code>if (ZipAdd(hZip, RelativePathNewFileFound, RelativePathNewFileFound, 0, ZIP_FILENAME) != ZR_OK)\n</code></pre>\n\n<p>To the following:</p>\n\n<pre><code>ZRESULT ret;\nTCHAR real_path[MAX_PATH] = {0};\n_tcscat(real_path, AbsolutePath);\n_tcscat(real_path, RelativePathNewFileFound);\nif (ZipAdd(hZip, RelativePathNewFileFound, real_path, 0, ZIP_FILENAME) != ZR_OK)\n</code></pre>\n"
},
{
"answer_id": 230762,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The above code to create an empty zip file is broken, as the comments state, but I was able to get it to work. I opened an empty zip in a hex editor, and noted a few differences. Here is my modified example:</p>\n\n<pre><code>FILE* f = fopen(\"path\", \"wb\"); \nfwrite(\"\\x50\\x4B\\x05\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\", 22, 1, f);\nfclose(f);\n</code></pre>\n\n<p>This worked for me. I was able to then open the compressed folder. Not tested with 3rd party apps such as winzip.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20840/"
]
| I am looking for a way to create a ZIP file from a folder in Windows C/C++ APIs. I can find the way to do this in VBScript using the Shell32.Application CopyHere method, and I found a tutorial explaining how to do it in C# also, but nothing for the C API (C++ is fine too, project already uses MFC).
I'd be really grateful if anyone can share some sample C code that can successfully create a zip file on Windows XP/2003. Failing that, if someone can find solid docs or a tutorial that would be great, since MSDN searches don't turn up much. I'm really hoping to avoid having to ship a third-party lib for this, because the functionality is obviously there, I just can't figure out how to access it. Google searches turn up nothing useful, just tantalizing bits and pieces of information. Here's hoping someone in the community has sorted this out and can share it for posterity! | EDIT: This answer is old, but I cannot delete it because it was accepted. See the next one
<https://stackoverflow.com/a/121720/3937>
----- ORIGINAL ANSWER -----
There is sample code to do that here
[EDIT: Link is now broken]
<http://www.eggheadcafe.com/software/aspnet/31056644/using-shfileoperation-to.aspx>
Make sure you read about how to handle monitoring for the thread to complete.
Edit: From the comments, this code only works on existing zip file, but @[Simon](https://stackoverflow.com/users/20135/simonbuchanmyopenidcom) provided this code to create a blank zip file
```
FILE* f = fopen("path", "wb");
fwrite("\x50\x4B\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 22, 1, f);
fclose(f);
``` |
118,565 | <p>Say I have a web service <a href="http://www.example.com/webservice.pl?q=google" rel="noreferrer">http://www.example.com/webservice.pl?q=google</a> which returns text "google.com". I need to call this web service (<a href="http://www.example.com/webservice.pl" rel="noreferrer">http://www.example.com/webservice.pl</a>) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.</p>
<p>What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated.</p>
| [
{
"answer_id": 118574,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": true,
"text": "<p>Take a look at one of the many javascript libraries out there. I'd recommend <a href=\"http://www.jquery.com\" rel=\"noreferrer\">jQuery</a>, personally. Aside from all the fancy UI stuff they can do, it has really good <a href=\"http://docs.jquery.com/Ajax\" rel=\"noreferrer\">cross-browser AJAX libraries</a>.</p>\n\n<pre><code>$.get(\n \"http://xyz.com/webservice.pl\",\n { q : \"google\" },\n function(data) {\n alert(data); // \"google.com\"\n }\n);\n</code></pre>\n"
},
{
"answer_id": 118906,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 4,
"selected": false,
"text": "<p><strong>EDIT:</strong> </p>\n\n<p>It has been a decade since I answered this question and we now have support for cross-domain XHR in the form of <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\" rel=\"nofollow noreferrer\">CORS</a>.</p>\n\n<p>For any modern app consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\">fetch</a> to make your requests. If you need support for older browsers you can add a <a href=\"https://github.com/github/fetch\" rel=\"nofollow noreferrer\">polyfill</a>.</p>\n\n<p><strong>Original answer:</strong></p>\n\n<p>Keep in mind that you cannot make requests across domains. For example, if your page is on yourexample.com and the web service is on myexample.com you cannot make a request to it directly.</p>\n\n<p>If you do need to make a request like this then you will need to set up a proxy on your server. You would make a request to that proxy page, and it will retrieve the data from the web service and return it to your page.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5734/"
]
| Say I have a web service <http://www.example.com/webservice.pl?q=google> which returns text "google.com". I need to call this web service (<http://www.example.com/webservice.pl>) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.
What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated. | Take a look at one of the many javascript libraries out there. I'd recommend [jQuery](http://www.jquery.com), personally. Aside from all the fancy UI stuff they can do, it has really good [cross-browser AJAX libraries](http://docs.jquery.com/Ajax).
```
$.get(
"http://xyz.com/webservice.pl",
{ q : "google" },
function(data) {
alert(data); // "google.com"
}
);
``` |
118,591 | <p>I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:</p>
<pre><code>find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
</code></pre>
<p>I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current:</p>
<pre><code>def AllFiles(filepath, depth=1, flist=[]):
fpath=os.walk(filepath)
fpath=[item for item in fpath]
while depth < len(fpath):
for item in fpath[depth][-1]:
flist.append(fpath[depth][0]+os.sep+item)
depth+=1
return flist
</code></pre>
<p>First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list_member).st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.</p>
<p>Of course, anything with the concision of the bash command would also be illuminating.</p>
| [
{
"answer_id": 118647,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>That's not a Bash command, it's a <code>find</code> command. If you really want to port it to Python it's possible, but you'll never be able to write a Python version that's as concise. <code>find</code> has been optimized over 20 years to be excellent at manipulating filesystems, while Python is a general-purpose programming language.</p>\n"
},
{
"answer_id": 118658,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import os, stat\nos.stat(\"test\")[stat.ST_MTIME]\n</code></pre>\n\n<p>Will give you the mtime. I suggest fixing those in <code>walk_results[2]</code>, and then recursing, calling the function for each dir in <code>walk_results[1]</code>.</p>\n"
},
{
"answer_id": 118817,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 4,
"selected": true,
"text": "<pre><code>import os\nimport shutil\nfrom os import path\nfrom os.path import join, getmtime\nfrom time import time\n\narchive = \"bak\"\ncurrent = \"cur\"\n\ndef archive_old_versions(days = 3):\n for root, dirs, files in os.walk(current):\n for name in files:\n fullname = join(root, name)\n if (getmtime(fullname) < time() - days * 60 * 60 * 24):\n shutil.move(fullname, join(archive, name))\n</code></pre>\n"
},
{
"answer_id": 118879,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import subprocess\nsubprocess.call(['find', '~/podcasts/current', '-mindepth', '2', '-mtime', '+5',\n '-exec', 'mv', '{}', '~/podcasts/old', ';'], shell=True)\n</code></pre>\n\n<p>That is not a joke. This python script will do exactly what the bash one does.</p>\n\n<p><strong>EDIT</strong>: Dropped the backslash on the last param because it is not needed.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596/"
]
| I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:
```
find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
```
I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current:
```
def AllFiles(filepath, depth=1, flist=[]):
fpath=os.walk(filepath)
fpath=[item for item in fpath]
while depth < len(fpath):
for item in fpath[depth][-1]:
flist.append(fpath[depth][0]+os.sep+item)
depth+=1
return flist
```
First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list\_member).st\_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.
Of course, anything with the concision of the bash command would also be illuminating. | ```
import os
import shutil
from os import path
from os.path import join, getmtime
from time import time
archive = "bak"
current = "cur"
def archive_old_versions(days = 3):
for root, dirs, files in os.walk(current):
for name in files:
fullname = join(root, name)
if (getmtime(fullname) < time() - days * 60 * 60 * 24):
shutil.move(fullname, join(archive, name))
``` |
118,599 | <p>I'm trying to store a password in a file that I'd like to retrieve for later. Hashing is not an option as I need the password for connecting to a remote server for later.</p>
<p>The following code works well, but it creates a different output each time even though the key is the same. This is bad as when the application shuts down and restarts I won't be able to retrieve my password any more. How can I store passwords in a file and retrieve them later?</p>
<pre><code>public class EncyptDecrypt {
static System.Security.Cryptography.TripleDESCryptoServiceProvider keyProv = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
public static System.Security.Cryptography.TripleDESCryptoServiceProvider KeyProvider {
get {
keyProv.Key = new byte[] { /* redacted with prejudice */ };
return keyProv;
}
}
public static string Encrypt(string text, SymmetricAlgorithm key) {
if (text.Equals(string.Empty)) return text;
// Create a memory stream.
MemoryStream ms = new MemoryStream();
// Create a CryptoStream using the memory stream and the
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);
// Create a StreamWriter to write a string
// to the stream.
StreamWriter sw = new StreamWriter(encStream);
// Write the plaintext to the stream.
sw.WriteLine(text);
// Close the StreamWriter and CryptoStream.
sw.Close();
encStream.Close();
// Get an array of bytes that represents
// the memory stream.
byte[] buffer = ms.ToArray();
// Close the memory stream.
ms.Close();
// Return the encrypted byte array.
return System.Convert.ToBase64String(buffer);
}
// Decrypt the byte array.
public static string Decrypt(string cypherText, SymmetricAlgorithm key) {
if (cypherText.Equals(string.Empty)) return cypherText;
string val;
try {
// Create a memory stream to the passed buffer.
MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(cypherText));
// Create a CryptoStream using the memory stream and the
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);
// Create a StreamReader for reading the stream.
StreamReader sr = new StreamReader(encStream);
// Read the stream as a string.
val = sr.ReadLine();
// Close the streams.
sr.Close();
encStream.Close();
ms.Close();
}
catch (System.Exception) {
return string.Empty;
}
return val;
}
}
</code></pre>
| [
{
"answer_id": 118613,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 4,
"selected": true,
"text": "<p>I believe that what's happening is that the crypto provider is randomly generating an IV. Specify this and it should no longer differ.</p>\n\n<p>Edit: You can do this in your 'keyProvider' by setting the IV property.</p>\n"
},
{
"answer_id": 118628,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 2,
"selected": false,
"text": "<p>According to the docs of CreateEncryptor:</p>\n\n<blockquote>\n <p>If the current IV property is a null\n reference (Nothing in Visual Basic),\n the GenerateIV method is called to\n create a new random IV.</p>\n</blockquote>\n\n<p>This will make the ciphertext different every time.</p>\n\n<p>Note: a way around this is discussed <a href=\"https://stackoverflow.com/questions/65879/should-i-use-an-initialization-vector-iv-along-with-my-encryption#66259\">here</a> where I suggest you can prepend the plaintext with a mac ... then the first block of ciphertext is effectively the IV, but it's all repeatable</p>\n"
},
{
"answer_id": 466104,
"author": "Chochos",
"author_id": 10165,
"author_profile": "https://Stackoverflow.com/users/10165",
"pm_score": 2,
"selected": false,
"text": "<p>You need to specify an IV (initialization vector), even if you generate a random one. If you use random IV then you must store it along with the ciphertext so you can use it later on decryption, or you can derive an IV from some other data (for example if you're encrypting a password, you can derive the IV from the username).</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
]
| I'm trying to store a password in a file that I'd like to retrieve for later. Hashing is not an option as I need the password for connecting to a remote server for later.
The following code works well, but it creates a different output each time even though the key is the same. This is bad as when the application shuts down and restarts I won't be able to retrieve my password any more. How can I store passwords in a file and retrieve them later?
```
public class EncyptDecrypt {
static System.Security.Cryptography.TripleDESCryptoServiceProvider keyProv = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
public static System.Security.Cryptography.TripleDESCryptoServiceProvider KeyProvider {
get {
keyProv.Key = new byte[] { /* redacted with prejudice */ };
return keyProv;
}
}
public static string Encrypt(string text, SymmetricAlgorithm key) {
if (text.Equals(string.Empty)) return text;
// Create a memory stream.
MemoryStream ms = new MemoryStream();
// Create a CryptoStream using the memory stream and the
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);
// Create a StreamWriter to write a string
// to the stream.
StreamWriter sw = new StreamWriter(encStream);
// Write the plaintext to the stream.
sw.WriteLine(text);
// Close the StreamWriter and CryptoStream.
sw.Close();
encStream.Close();
// Get an array of bytes that represents
// the memory stream.
byte[] buffer = ms.ToArray();
// Close the memory stream.
ms.Close();
// Return the encrypted byte array.
return System.Convert.ToBase64String(buffer);
}
// Decrypt the byte array.
public static string Decrypt(string cypherText, SymmetricAlgorithm key) {
if (cypherText.Equals(string.Empty)) return cypherText;
string val;
try {
// Create a memory stream to the passed buffer.
MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(cypherText));
// Create a CryptoStream using the memory stream and the
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);
// Create a StreamReader for reading the stream.
StreamReader sr = new StreamReader(encStream);
// Read the stream as a string.
val = sr.ReadLine();
// Close the streams.
sr.Close();
encStream.Close();
ms.Close();
}
catch (System.Exception) {
return string.Empty;
}
return val;
}
}
``` | I believe that what's happening is that the crypto provider is randomly generating an IV. Specify this and it should no longer differ.
Edit: You can do this in your 'keyProvider' by setting the IV property. |
118,630 | <p>I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this:</p>
<pre><code>const T operator+(const T& lhs, const T& rhs)
{
return T(lhs) +=rhs;
}
</code></pre>
<p>But it was pointed out to me that this would also work:</p>
<pre><code>const T operator+ (T lhs, const T& rhs)
{
return lhs+=rhs;
}
</code></pre>
<p>In essence, this form transfers creation of the temporary from the body of the implementation to the function call.</p>
<p>It seems a little awkward to have different types for the two parameters, but is there anything wrong with the second form? Is there a reason to prefer one over the other?</p>
| [
{
"answer_id": 118664,
"author": "Kris Kumler",
"author_id": 4281,
"author_profile": "https://Stackoverflow.com/users/4281",
"pm_score": 3,
"selected": true,
"text": "<p>With the edited question, the first form would be preferred. The compiler will more likely optimize the return value (you could verify this by placing a breakpoint in the constructor for T). The first form also takes both parameters as const, which would be more desirable.</p>\n\n<p>Research on the topic of <strong>return value optimization</strong>, such as this link as a quick example: <a href=\"http://www.cs.cmu.edu/~gilpin/c++/performance.html\" rel=\"nofollow noreferrer\">http://www.cs.cmu.edu/~gilpin/c++/performance.html</a></p>\n"
},
{
"answer_id": 118677,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure if there is much difference in the generated code for either.</p>\n\n<p>Between these two, I would (personally) prefer the first form since it better conveys the intention. This is with respect to both your reuse of the += operator and the idiom of passing templatized types by const&.</p>\n"
},
{
"answer_id": 118775,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>I would prefer the first form for readability.</p>\n\n<p>I had to think twice before I saw that the first parameter was being copied in. I was not expecting that. Therefore as both versions are probably just as efficient I would pick them one that is easier to read.</p>\n"
},
{
"answer_id": 119049,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 1,
"selected": false,
"text": "<pre><code>const T operator+(const T& lhs, const T& rhs)\n{\n return T(lhs)+=rhs;\n}\n</code></pre>\n\n<p>why not this if you want the terseness?</p>\n"
},
{
"answer_id": 119502,
"author": "Jan de Vos",
"author_id": 11215,
"author_profile": "https://Stackoverflow.com/users/11215",
"pm_score": 1,
"selected": false,
"text": "<p>My first thought is that the second version might be infinitessimally faster than the first, because no reference is pushed on the stack as an argument. However, this would be very compiler-dependant, and depends for instance on whether the compiler performs Named Return Value Optimization or not.</p>\n\n<p>Anyway, in case of any doubt, never choose for a very small performance gain that might not even exist and you more than likely won't need -- choose the clearest version, which is the first.</p>\n"
},
{
"answer_id": 256351,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, the second is preferred. As stated in the c++ standard,</p>\n\n<blockquote>\n <p>3.7.2/2: Automatic storage duration</p>\n \n <p>If a named automatic object has\n initialization or a destructor with\n side effects, it shall not be\n destroyed before the end of its block,\n nor shall it be eliminated as an\n optimization even if it appears to be\n unused, except that a class object or\n its copy may be eliminated as\n specified in 12.8.</p>\n</blockquote>\n\n<p>That is, because an unnamed temporary object is created using a copy constructor, the compiler may not use the return value optimization. For the second case, however, the unnamed return value optimization is allowed. Note that if your compiler implements named return value optimization, the best code is</p>\n\n<pre><code>const T operator+(const T& lhs, const T& rhs)\n{\n T temp(lhs);\n temp +=rhs;\n return temp;\n}\n</code></pre>\n"
},
{
"answer_id": 256361,
"author": "Drew Hall",
"author_id": 23934,
"author_profile": "https://Stackoverflow.com/users/23934",
"pm_score": 0,
"selected": false,
"text": "<p>I think that if you inlined them both (I would since they're just forwarding functions, and presumably the operator+=() function is out-of-line), you'd get near indistinguishable code generation. That said, the first is more canonical. The second version is needlessly \"cute\".</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1674/"
]
| I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this:
```
const T operator+(const T& lhs, const T& rhs)
{
return T(lhs) +=rhs;
}
```
But it was pointed out to me that this would also work:
```
const T operator+ (T lhs, const T& rhs)
{
return lhs+=rhs;
}
```
In essence, this form transfers creation of the temporary from the body of the implementation to the function call.
It seems a little awkward to have different types for the two parameters, but is there anything wrong with the second form? Is there a reason to prefer one over the other? | With the edited question, the first form would be preferred. The compiler will more likely optimize the return value (you could verify this by placing a breakpoint in the constructor for T). The first form also takes both parameters as const, which would be more desirable.
Research on the topic of **return value optimization**, such as this link as a quick example: <http://www.cs.cmu.edu/~gilpin/c++/performance.html> |
118,632 | <p>I need to layout a html datatable with CSS. </p>
<p>The actual content of the table can differ, but there is always one main column and 2 or more other columns. I'd like to make the main column take up as MUCH width as possible, regardless of its contents, while the other columns take up as little width as possible. I can't specify exact widths for any of the columns because their contents can change.</p>
<p>How can I do this using a simple semantically valid html table and css only?</p>
<p>For example:</p>
<pre>
| Main column | Col 2 | Column 3 |
<------------------ fixed width in px ------------------->
<------- as wide as possible --------->
Thin as possible depending on contents: <-----> <-------->
</pre>
| [
{
"answer_id": 118655,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 4,
"selected": true,
"text": "<p>I'm far from being a CSS expert but this works for me (in IE, FF, Safari and Chrome):</p>\n\n<pre><code>td.zero_width {\n width: 1%;\n}\n</code></pre>\n\n<p>Then in your HTML:</p>\n\n<pre><code><td class=\"zero_width\">...</td>\n</code></pre>\n"
},
{
"answer_id": 118749,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 3,
"selected": false,
"text": "<p>Similar to Alexk's solution, but possibly a little easier to implement depending on your situation:</p>\n\n<pre><code><table>\n <tr>\n <td>foo</td>\n <td class=\"importantColumn\">bar</td>\n <td>woo</td>\n <td>pah</td>\n </tr>\n</table>\n\n.importantColumn{\n width: 100%;\n}\n</code></pre>\n\n<p>You might also want to apply <code>white-space:nowrap</code> to the cells if you want to avoid wrapping.</p>\n"
},
{
"answer_id": 16863688,
"author": "daveomcd",
"author_id": 394241,
"author_profile": "https://Stackoverflow.com/users/394241",
"pm_score": 1,
"selected": false,
"text": "<p>I've not had success with <code>width: 100%;</code> as it seems that without a container div that has a fixed width this will not get the intended results. Instead I use something like the following and it seems to give me my best results.</p>\n\n<pre><code>.column-fill { min-width: 325px; }\n</code></pre>\n\n<p>This way it can get larger if it needs to, and it seems that the browser will give all the extra space to whichever column is set this way. Not sure if it works for everyone but did for me in chrome (haven't tried others)... worth a shot.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20851/"
]
| I need to layout a html datatable with CSS.
The actual content of the table can differ, but there is always one main column and 2 or more other columns. I'd like to make the main column take up as MUCH width as possible, regardless of its contents, while the other columns take up as little width as possible. I can't specify exact widths for any of the columns because their contents can change.
How can I do this using a simple semantically valid html table and css only?
For example:
```
| Main column | Col 2 | Column 3 |
<------------------ fixed width in px ------------------->
<------- as wide as possible --------->
Thin as possible depending on contents: <-----> <-------->
``` | I'm far from being a CSS expert but this works for me (in IE, FF, Safari and Chrome):
```
td.zero_width {
width: 1%;
}
```
Then in your HTML:
```
<td class="zero_width">...</td>
``` |
118,643 | <p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
| [
{
"answer_id": 118651,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 4,
"selected": false,
"text": "<p>I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited.</p>\n\n<p>I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python?</p>\n\n<p>I'd assume that you use a screen reader here however for the output? So the tabs would seem \"invisible\" to you? With a Braille output, it might be easier to read, but I can understand exactly how confusing this could be.</p>\n\n<p>In fact, this is very interesting to me. I wish that I knew enough to be able to write an app that will do this for you. </p>\n\n<p>I think it's definately something that I'll put in a bug report for, unless you've already done so yourself, or want to.</p>\n\n<p>Edit: Also, as <a href=\"https://stackoverflow.com/questions/118643#118656\">noted</a> by <a href=\"https://stackoverflow.com/users/3560/john-millikin\">John Millikin</a> There is also <a href=\"http://timhatch.com/projects/pybraces/\" rel=\"nofollow noreferrer\">PyBraces</a> Which might be a viable solution to you, and may be possible to be hacked together dependant on your coding skills to be exactly what you need (and I hope that if that's the case, you release it out for others like yourself to use)</p>\n\n<p>Edit 2: I've just <a href=\"http://bugs.python.org/issue3942\" rel=\"nofollow noreferrer\">reported this</a> to the python bug tracker</p>\n"
},
{
"answer_id": 118656,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>You should be able to configure your editor to speak the tabs and spaces -- I know it's possible to <em>display</em> whitespace in most editors, so there must be an accessibility option somewhere to speak them.</p>\n\n<p>Failing that, there is <a href=\"http://timhatch.com/projects/pybraces/\" rel=\"nofollow noreferrer\">pybraces</a>, which was written as a practical joke but might actually be useful to you with a bit of work.</p>\n"
},
{
"answer_id": 118676,
"author": "andy",
"author_id": 6152,
"author_profile": "https://Stackoverflow.com/users/6152",
"pm_score": 2,
"selected": false,
"text": "<p>I appreciate your problem, but think you are specifying the implementation instead of the problem you need solved. Instead of converting to braces, how about working on a way for your screen reader to tell you the indentation level?\n<p>\nFor example, <a href=\"http://viming.blogspot.com/2007/02/indent-level-highlighting.html\" rel=\"nofollow noreferrer\">some people</a> have worked on vim syntax coloring to represent python indentation levels. Perhaps a modified syntax coloring could produce something your screen reader would read?</p>\n"
},
{
"answer_id": 118706,
"author": "technomalogical",
"author_id": 6173,
"author_profile": "https://Stackoverflow.com/users/6173",
"pm_score": 3,
"selected": false,
"text": "<p>Although I am not blind, I have heard good things about <a href=\"http://emacspeak.sourceforge.net/\" rel=\"noreferrer\">Emacspeak</a>. They've had a Python mode since their <a href=\"http://emacspeak.sourceforge.net/releases/release-8.0.html\" rel=\"noreferrer\">8.0 release</a> in 1998 (they seem to be up to release 28.0!). Definitely worth checking out.</p>\n"
},
{
"answer_id": 118744,
"author": "Ryan",
"author_id": 8819,
"author_profile": "https://Stackoverflow.com/users/8819",
"pm_score": 7,
"selected": true,
"text": "<p>There's a solution to your problem that is distributed with python itself. <code>pindent.py</code>, it's located in the Tools\\Scripts directory in a windows install (my path to it is C:\\Python25\\Tools\\Scripts), it looks like you'd have to <a href=\"https://svn.python.org/projects/python/trunk/Tools/scripts/pindent.py\" rel=\"nofollow noreferrer\">grab it from svn.python.org</a> if you are running on Linux or OSX. </p>\n\n<p>It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command:</p>\n\n<p><code>pindent.py -c myfile.py</code></p>\n\n<pre><code>def foobar(a, b):\n if a == b:\n a = a+1\n elif a < b:\n b = b-1\n if b > a: a = a-1\n # end if\n else:\n print 'oops!'\n # end if\n# end def foobar\n</code></pre>\n\n<p>Where the original <code>myfile.py</code> was: </p>\n\n<pre><code>def foobar(a, b):\n if a == b:\n a = a+1\n elif a < b:\n b = b-1\n if b > a: a = a-1\n else:\n print 'oops!'\n</code></pre>\n\n<p>You can also use <code>pindent.py -r</code> to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation.</p>\n\n<p>For example, running <code>pindent.py -r myfile.py</code> will convert the following code in <code>myfile.py</code> into the same properly indented (and also commented) code as produced by the <code>pindent.py -c</code> example above:</p>\n\n<pre><code>def foobar(a, b):\nif a == b:\na = a+1\nelif a < b:\nb = b-1\nif b > a: a = a-1\n# end if\nelse:\nprint 'oops!'\n# end if\n# end def foobar\n</code></pre>\n\n<p>I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help.</p>\n"
},
{
"answer_id": 236957,
"author": "Jared",
"author_id": 14744,
"author_profile": "https://Stackoverflow.com/users/14744",
"pm_score": 2,
"selected": false,
"text": "<p>I use eclipse with the pydev extensions since it's an IDE I have a lot of experience with. I also appreciate the smart indentation it offers for coding if statements, loops, etc. I have configured the pindent.py script as an external tool that I can run on the currently focused python module which makes my life easier so I can see what is closed where with out having to constantly check indentation.</p>\n"
},
{
"answer_id": 453806,
"author": "Saqib",
"author_id": 56241,
"author_profile": "https://Stackoverflow.com/users/56241",
"pm_score": 1,
"selected": false,
"text": "<p>There are various answers explaining how to do this. But I would recommend not taking this route. While you could use a script to do the conversion, it would make it hard to work on a team project.</p>\n\n<p>My recommendation would be to configure your screen reader to announce the tabs. This isn't as annoying as it sounds, since it would only say \"indent 5\" rather than \"tab tab tab tab tab\". Furthermore, the indentation would only be read whenever it changed, so you could go through an entire block of code without hearing the indentation level. In this way hearing the indentation is no more verbose than hearing the braces.</p>\n\n<p>As I don't know which operating system or screen reader you use I unfortunately can't give the exact steps for achieving this.</p>\n"
},
{
"answer_id": 1479855,
"author": "NevilleDNZ",
"author_id": 77431,
"author_profile": "https://Stackoverflow.com/users/77431",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Edsger_Dijkstra\" rel=\"nofollow noreferrer\">Edsger Dijkstra</a> used <a href=\"http://en.wikipedia.org/wiki/Guarded_Command_Language#Selection:_if\" rel=\"nofollow noreferrer\">if ~ fi</a> and <a href=\"http://en.wikipedia.org/wiki/Guarded_Command_Language#Repetition:_do\" rel=\"nofollow noreferrer\">do ~ od</a> in his \"Guarded Command Language\", these appear to originate from the <a href=\"https://sourceforge.net/projects/algol68/\" rel=\"nofollow noreferrer\">Algol68</a>. There were also some example python guarded blocks used in <a href=\"http://rosettacode.org/wiki/Python\" rel=\"nofollow noreferrer\">RosettaCode.org</a>. </p>\n\n<pre><code>fi = od = yrt = end = lambda object: None;\nclass MyClass(object):\n def myfunction(self, arg1, arg2):\n for i in range(arg1) :# do\n if i > 5 :# then\n print i\n fi\n od # or end(i) #\n end(myfunction)\nend(MyClass)\n</code></pre>\n\n<p>Whitespace mangled python code can be unambiguously unmangled and reindented if one uses\nguarded blocks if/fi, do/od & try/yrt together with semicolons \";\" to separate statements. Excellent for unambiguous magazine listings or cut/pasting from web pages.</p>\n\n<p>It should be easy enough to write a short python program to insert/remove the guard blocks and semicolons.</p>\n"
},
{
"answer_id": 11382155,
"author": "la11111",
"author_id": 1212685,
"author_profile": "https://Stackoverflow.com/users/1212685",
"pm_score": 3,
"selected": false,
"text": "<p>All of these \"no you can't\" types of answers are really annoying. Of course you can.</p>\n\n<p>It's a hack, but you can do it.</p>\n\n<p><a href=\"http://timhatch.com/projects/pybraces/\" rel=\"noreferrer\">http://timhatch.com/projects/pybraces/</a></p>\n\n<p>uses a custom encoding to convert braces to indented blocks before handing it off to the interpreter.</p>\n\n<hr>\n\n<p>As an aside, and as someone new to python - I don't accept the reasoning behind not even <em>allowing</em> braces/generic block delimiters ... apart from that being the preference of the python devs. Braces at least won't get eaten accidentally if you're doing some automatic processing of your code or working in an editor that doesn't understand that white space is important. If you're generating code automatically, it's handy to not have to keep track of indent levels. If you want to use python to do a perl-esque one-liner, you're automatically crippled. If nothing else, just as a safeguard. What if your 1000 line python program gets all of its tabs eaten? You're going to go line-by-line and figure out where the indenting should be?</p>\n\n<p>Asking about it will invariably get a tongue-in-cheek response like \"just do 'from __ future __ import braces'\", \"configure your IDE correctly\", \"it's better anyway so get used to it\" ... </p>\n\n<p>I see their point, but hey, if i wanted to, i could put a semicolon after every single line. So I don't understand why everyone is so adamant about the braces thing. If you need your language to force you to indent properly, you're not doing it right in the first place.</p>\n\n<p>Just my 2c - I'm going to use braces anyway.</p>\n"
},
{
"answer_id": 11996920,
"author": "Andre Polykanine",
"author_id": 1604592,
"author_profile": "https://Stackoverflow.com/users/1604592",
"pm_score": 2,
"selected": false,
"text": "<p>Searching an accessible Python IDE, found this and decided to answer.\nUnder Windows with JAWS:</p>\n\n<ol>\n<li>Go to Settings Center by pressing <kbd>JawsKey</kbd>+<kbd>6</kbd> (on the number row above the letters) in your favorite text editor. If JAWS prompts to create a new configuration file, agree.</li>\n<li>In the search field, type \"indent\"</li>\n<li>There will be only one result: \"Say indent characters\". Turn this on.</li>\n<li>Enjoy!</li>\n</ol>\n\n<p>The only thing that is frustrating for us is that we can't enjoy code examples on websites (since indent speaking in browsers is not too comfortable — it generates superfluous speech).</p>\n\n<p>Happy coding from another Python beginner).</p>\n"
},
{
"answer_id": 13292321,
"author": "fastfinge",
"author_id": 1809750,
"author_profile": "https://Stackoverflow.com/users/1809750",
"pm_score": 3,
"selected": false,
"text": "<p>If you're on Windows, I strongly recommend you take a look at EdSharp from:\n<a href=\"http://empowermentzone.com/EdSharp.htm\">http://empowermentzone.com/EdSharp.htm</a>\nIt supports all of the leading Windows screenreaders, it can be configured to speak the indentation levels of code, or it has a built in utility called PyBrace that can convert to and from braces syntax if you want to do that instead, and it supports all kinds of other features programmers have come to expect in our text editors. I've been using it for years, for everything from PHP to JavaScript to HTML to Python, and I love it. </p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744/"
]
| I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use? | There's a solution to your problem that is distributed with python itself. `pindent.py`, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have to [grab it from svn.python.org](https://svn.python.org/projects/python/trunk/Tools/scripts/pindent.py) if you are running on Linux or OSX.
It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command:
`pindent.py -c myfile.py`
```
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
```
Where the original `myfile.py` was:
```
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
else:
print 'oops!'
```
You can also use `pindent.py -r` to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation.
For example, running `pindent.py -r myfile.py` will convert the following code in `myfile.py` into the same properly indented (and also commented) code as produced by the `pindent.py -c` example above:
```
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
```
I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help. |
118,654 | <p>Does beautiful soup work with iron python?
If so with which version of iron python?
How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
| [
{
"answer_id": 118671,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't tested it, but I'd say it'll most likely work with the latest IPy2.</p>\n\n<p>As for distribution, it's very simple. Use the -X:SaveAssemblies option to compile your Python code down to a binary and then ship it with your other DLLs and the IPy dependencies.</p>\n"
},
{
"answer_id": 118680,
"author": "Devin Jeanpierre",
"author_id": 18515,
"author_profile": "https://Stackoverflow.com/users/18515",
"pm_score": 3,
"selected": false,
"text": "<p>If BeautifulSoup doesn't work on IronPython, it's because IronPython doesn't implement the whole Python language (the same way CPython does). BeautifulSoup is pure-python, no C-extensions, so the only problem is the compatibility of IronPython with CPython in terms of Python source code.There shouldn't be one, but if there is, the error will be obvious (\"no module named ...\", \"no method named ...\", etc.). Google says that only one of BS's tests fails with IronPython. it probably works, and that test may be fixed by now. I wouldn't know.</p>\n\n<p>Try it out and see, would be my advice, unless anybody has anything more concrete.</p>\n"
},
{
"answer_id": 118713,
"author": "technomalogical",
"author_id": 6173,
"author_profile": "https://Stackoverflow.com/users/6173",
"pm_score": 3,
"selected": false,
"text": "<p>I've tested and used BeautifulSoup with both IPy 1.1 and 2.0 (forget which beta, but this was a few months back). Leave a comment if you are still having trouble and I'll dig out my test code and post it.</p>\n"
},
{
"answer_id": 119713,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": -1,
"selected": false,
"text": "<p>If you have the complete standard library and the real <code>re</code> module (google for IronPython community edition) it might work. But IronPython is an incredible bad python implementation, I wouldn't count on that.</p>\n\n<p>Besides, give <code>html5lib</code> a try. That parser parses with the same rules firefox parses documents.</p>\n"
},
{
"answer_id": 123532,
"author": "Srivatsn Narayanan",
"author_id": 1157248,
"author_profile": "https://Stackoverflow.com/users/1157248",
"pm_score": 1,
"selected": false,
"text": "<p>Regarding the second part of your question, you can use the DLR Hosting APIs to run IronPython code from within a C# application. The DLR hosting spec is <a href=\"http://compilerlab.members.winisp.net/dlr-spec-hosting.pdf\" rel=\"nofollow noreferrer\">here</a>. This <a href=\"http://blogs.msdn.com/seshadripv/\" rel=\"nofollow noreferrer\">blog</a> also contains some sample hosting applications</p>\n"
},
{
"answer_id": 123589,
"author": "Srivatsn Narayanan",
"author_id": 1157248,
"author_profile": "https://Stackoverflow.com/users/1157248",
"pm_score": 2,
"selected": false,
"text": "<p>Also, regarding one of the previous comments about compiling with -X:SaveAssemblies - that is wrong. -X:SaveAssemblies is meant as a debugging feature. There is a API meant for compiling python code into binaries. <a href=\"http://blogs.msdn.com/srivatsn/archive/2008/08/06/static-compilation-of-ironpython-scripts.aspx\" rel=\"nofollow noreferrer\">This post</a> explains the API and the difference between the two modes.</p>\n"
},
{
"answer_id": 170856,
"author": "bouvard",
"author_id": 24608,
"author_profile": "https://Stackoverflow.com/users/24608",
"pm_score": 6,
"selected": true,
"text": "<p>I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was anything comparable available for .NET, but then I found the <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"noreferrer\">HTML Agility Pack</a> and if anything I think I've actually gained some maintainability over BeautifulSoup. It takes clean or crufty HTML and produces a elegant XML DOM from it that can be queried via XPath. With a couple lines of code you can even get back a raw XDocument and then <a href=\"http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx\" rel=\"noreferrer\">craft your queries in LINQ to XML</a>. Honestly, if web scraping is your goal, this is about the cleanest solution you are likely to find.</p>\n\n<p><b>Edit</b></p>\n\n<p>Here is a simple (read: not robust at all) example that parses out the US House of Representatives holiday schedule:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing HtmlAgilityPack;\n\nnamespace GovParsingTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n HtmlWeb hw = new HtmlWeb();\n string url = @\"http://www.house.gov/house/House_Calendar.shtml\";\n HtmlDocument doc = hw.Load(url);\n\n HtmlNode docNode = doc.DocumentNode;\n HtmlNode div = docNode.SelectSingleNode(\"//div[@id='primary']\");\n HtmlNodeCollection tableRows = div.SelectNodes(\".//tr\");\n\n foreach (HtmlNode row in tableRows)\n {\n HtmlNodeCollection cells = row.SelectNodes(\".//td\");\n HtmlNode dateNode = cells[0];\n HtmlNode eventNode = cells[1];\n\n while (eventNode.HasChildNodes)\n {\n eventNode = eventNode.FirstChild;\n }\n\n Console.WriteLine(dateNode.InnerText);\n Console.WriteLine(eventNode.InnerText);\n Console.WriteLine();\n }\n\n //Console.WriteLine(div.InnerHtml);\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 287247,
"author": "Jonathan Hartley",
"author_id": 10176,
"author_profile": "https://Stackoverflow.com/users/10176",
"pm_score": 1,
"selected": false,
"text": "<p>We are distributing a 40k line IronPython application. We have not been able to compile the whole thing into a single binary distributable. Instead we have been distributing it as a zillion tiny dlls, one for each IronPython module. This works fine though.</p>\n\n<p>However, on the newer release, IronPython 2.0, we have a recent spike which seems to be able to compile everything into a single binary file. This also results in faster application start-up too (module importing is faster.) Hopefully this spike will migrate into our main tree in the next few days.</p>\n\n<p>To do the distribution we are using WiX, which is a Microsoft internal tool for creating msi installs, that has been open-sourced (or made freely available, at least.) It has given us no problems, even though our install has some quite fiddly requirements. I will definitely look at using WiX to distribute other IronPython projects in the future.</p>\n"
},
{
"answer_id": 6549240,
"author": "Mark Heath",
"author_id": 7532,
"author_profile": "https://Stackoverflow.com/users/7532",
"pm_score": 1,
"selected": false,
"text": "<p>Seems to work just fine with IronPython 2.7. Just need to point it at the right folder and away you go:</p>\n\n<pre><code>D:\\Code>ipy\nIronPython 2.7 (2.7.0.40) on .NET 4.0.30319.235\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> sys.path.append(\"D:\\Code\\IronPython\\BeautifulSoup-3.2.0\")\n>>> import urllib2\n>>> from BeautifulSoup import BeautifulSoup\n>>> page = urllib2.urlopen(\"http://www.example.com\")\n>>> soup = BeautifulSoup(page)\n<string>:1: DeprecationWarning: object.__new__() takes no parameters\n>>> i = soup('img')[0]\n>>> i['src']\n'http://example.com/blah.png'\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
]
| Does beautiful soup work with iron python?
If so with which version of iron python?
How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? | I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was anything comparable available for .NET, but then I found the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) and if anything I think I've actually gained some maintainability over BeautifulSoup. It takes clean or crufty HTML and produces a elegant XML DOM from it that can be queried via XPath. With a couple lines of code you can even get back a raw XDocument and then [craft your queries in LINQ to XML](http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx). Honestly, if web scraping is your goal, this is about the cleanest solution you are likely to find.
**Edit**
Here is a simple (read: not robust at all) example that parses out the US House of Representatives holiday schedule:
```
using System;
using System.Collections.Generic;
using HtmlAgilityPack;
namespace GovParsingTest
{
class Program
{
static void Main(string[] args)
{
HtmlWeb hw = new HtmlWeb();
string url = @"http://www.house.gov/house/House_Calendar.shtml";
HtmlDocument doc = hw.Load(url);
HtmlNode docNode = doc.DocumentNode;
HtmlNode div = docNode.SelectSingleNode("//div[@id='primary']");
HtmlNodeCollection tableRows = div.SelectNodes(".//tr");
foreach (HtmlNode row in tableRows)
{
HtmlNodeCollection cells = row.SelectNodes(".//td");
HtmlNode dateNode = cells[0];
HtmlNode eventNode = cells[1];
while (eventNode.HasChildNodes)
{
eventNode = eventNode.FirstChild;
}
Console.WriteLine(dateNode.InnerText);
Console.WriteLine(eventNode.InnerText);
Console.WriteLine();
}
//Console.WriteLine(div.InnerHtml);
Console.ReadKey();
}
}
}
``` |
118,686 | <p>I'm using GDI+ in C++. (This issue might exist in C# too). </p>
<p>I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right.</p>
<p>For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP".</p>
<p>My question is: is this intended or documented behaviour, and how do I disable this? </p>
<pre><code>RectF Rect(0,0,32767,32767);
RectF Bounds1, Bounds2;
graphics->MeasureString(L"PP", 1, font, Rect, &Bounds1);
graphics->MeasureString(L"PP", 2, font, Rect, &Bounds2);
margin = Bounds1.Width * 2 - Bounds2.Width;
</code></pre>
| [
{
"answer_id": 118764,
"author": "HitScan",
"author_id": 9490,
"author_profile": "https://Stackoverflow.com/users/9490",
"pm_score": 5,
"selected": true,
"text": "<p>It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of overhangs.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx\" rel=\"noreferrer\">MSDN</a> suggests using a different method if you need more accuracy:</p>\n\n<blockquote>\n <p>To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurecharacterranges.aspx\" rel=\"noreferrer\">MeasureCharacterRanges</a> method or one of the <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurestring.aspx\" rel=\"noreferrer\">MeasureString</a> methods that takes a <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.aspx\" rel=\"noreferrer\">StringFormat</a>, and pass <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.generictypographic.aspx\" rel=\"noreferrer\">GenericTypographic</a>. Also, ensure the <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint.aspx\" rel=\"noreferrer\">TextRenderingHint</a> for the <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.graphics.aspx\" rel=\"noreferrer\">Graphics</a> is <a href=\"http://msdn.microsoft.com/en-us/library/ssazt6bs.aspx\" rel=\"noreferrer\">AntiAlias</a>.</p>\n</blockquote>\n"
},
{
"answer_id": 118770,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like it might also be connecting to hinting, based on this kb article, <a href=\"http://support.microsoft.com/?id=307208\" rel=\"nofollow noreferrer\">Why text appears different when drawn with GDIPlus versus GDI</a></p>\n"
},
{
"answer_id": 283310,
"author": "Cory",
"author_id": 8207,
"author_profile": "https://Stackoverflow.com/users/8207",
"pm_score": 3,
"selected": false,
"text": "<p>It's true that is by design, however the link on the accepted answer is actually not perfect. The issue is the use of floats in all those methods when what you really want to be using is pixels (ints).</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.textrenderer.aspx\" rel=\"noreferrer\">TextRenderer class</a> is meant for this purpose and works with the true sizes. See this <a href=\"http://msdn.microsoft.com/en-us/library/7sy6awsb.aspx\" rel=\"noreferrer\">link from msdn</a> for a walkthrough of using this. </p>\n"
},
{
"answer_id": 342138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>TextRenderer was great for getting the size of the font. But in the drawing loop, using TextRenderer.DrawText was excruciatingly slow compared to graphics.DrawString().</p>\n\n<p>Since the width of a string is the problem, your much better off using a combination of TextRenderer.MeasureText and graphics.DrawString..</p>\n"
},
{
"answer_id": 8515930,
"author": "vscpp",
"author_id": 245582,
"author_profile": "https://Stackoverflow.com/users/245582",
"pm_score": 3,
"selected": false,
"text": "<p>Append <code>StringFormat.GenericTypographic</code> will fix your issue:</p>\n\n<pre><code>graphics->MeasureString(L\"PP\", 1, font, width, StringFormat.GenericTypographic);\n</code></pre>\n\n<p>Apply the same attribute to <code>DrawString</code>.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10592/"
]
| I'm using GDI+ in C++. (This issue might exist in C# too).
I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right.
For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP".
My question is: is this intended or documented behaviour, and how do I disable this?
```
RectF Rect(0,0,32767,32767);
RectF Bounds1, Bounds2;
graphics->MeasureString(L"PP", 1, font, Rect, &Bounds1);
graphics->MeasureString(L"PP", 2, font, Rect, &Bounds2);
margin = Bounds1.Width * 2 - Bounds2.Width;
``` | It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of overhangs.
[MSDN](http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx) suggests using a different method if you need more accuracy:
>
> To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the [MeasureCharacterRanges](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurecharacterranges.aspx) method or one of the [MeasureString](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurestring.aspx) methods that takes a [StringFormat](http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.aspx), and pass [GenericTypographic](http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.generictypographic.aspx). Also, ensure the [TextRenderingHint](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint.aspx) for the [Graphics](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.aspx) is [AntiAlias](http://msdn.microsoft.com/en-us/library/ssazt6bs.aspx).
>
>
> |
118,693 | <p>Dynamically creating a radio button using eg </p>
<pre><code>var radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
</code></pre>
<p>works in Firefox but not in IE. Why not?</p>
| [
{
"answer_id": 118702,
"author": "Patrick Wilkes",
"author_id": 6370,
"author_profile": "https://Stackoverflow.com/users/6370",
"pm_score": 3,
"selected": false,
"text": "<p>Based on this post and its comments:\n<a href=\"http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html\" rel=\"noreferrer\">http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html</a></p>\n\n<p>the following works. Apparently the problem is that you can't dynamically set the name property in IE. I also found that you can't dynamically set the checked attribute either.</p>\n\n<pre><code>function createRadioElement( name, checked ) {\n var radioInput;\n try {\n var radioHtml = '<input type=\"radio\" name=\"' + name + '\"';\n if ( checked ) {\n radioHtml += ' checked=\"checked\"';\n }\n radioHtml += '/>';\n radioInput = document.createElement(radioHtml);\n } catch( err ) {\n radioInput = document.createElement('input');\n radioInput.setAttribute('type', 'radio');\n radioInput.setAttribute('name', name);\n if ( checked ) {\n radioInput.setAttribute('checked', 'checked');\n }\n }\n\n return radioInput;\n}\n</code></pre>\n"
},
{
"answer_id": 118703,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": -1,
"selected": false,
"text": "<p>My suggestion is not to use document.Create(). Better solution is to construct actual HTML of future control and then assign it like innerHTML to some placeholder - it allows browser to render it itself which is much faster than any JS DOM manipulations.</p>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 118709,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "<p>Patrick's answer works, or you can set the \"defaultChecked\" attribute too (this will work in IE for radio or checkbox elements, and won't cause errors in other browsers.</p>\n\n<p>PS Full list of attributes you can't set in IE is listed here:</p>\n\n<p><a href=\"http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html\" rel=\"nofollow noreferrer\">http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html</a></p>\n"
},
{
"answer_id": 119079,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 5,
"selected": false,
"text": "<p>Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch:</p>\n\n<pre><code>function createRadioElement(name, checked) {\n var radioHtml = '<input type=\"radio\" name=\"' + name + '\"';\n if ( checked ) {\n radioHtml += ' checked=\"checked\"';\n }\n radioHtml += '/>';\n\n var radioFragment = document.createElement('div');\n radioFragment.innerHTML = radioHtml;\n\n return radioFragment.firstChild;\n}\n</code></pre>\n"
},
{
"answer_id": 120372,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example of more general solution which detects IE up front and handles other attributes IE also has problems with, extracted from <a href=\"http://code.google.com/p/dombuilder/\" rel=\"nofollow noreferrer\">DOMBuilder</a>:</p>\n\n<pre><code>var createElement = (function()\n{\n // Detect IE using conditional compilation\n if (/*@cc_on @*//*@if (@_win32)!/*@end @*/false)\n {\n // Translations for attribute names which IE would otherwise choke on\n var attrTranslations =\n {\n \"class\": \"className\",\n \"for\": \"htmlFor\"\n };\n\n var setAttribute = function(element, attr, value)\n {\n if (attrTranslations.hasOwnProperty(attr))\n {\n element[attrTranslations[attr]] = value;\n }\n else if (attr == \"style\")\n {\n element.style.cssText = value;\n }\n else\n {\n element.setAttribute(attr, value);\n }\n };\n\n return function(tagName, attributes)\n {\n attributes = attributes || {};\n\n // See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs\n if (attributes.hasOwnProperty(\"name\") ||\n attributes.hasOwnProperty(\"checked\") ||\n attributes.hasOwnProperty(\"multiple\"))\n {\n var tagParts = [\"<\" + tagName];\n if (attributes.hasOwnProperty(\"name\"))\n {\n tagParts[tagParts.length] =\n ' name=\"' + attributes.name + '\"';\n delete attributes.name;\n }\n if (attributes.hasOwnProperty(\"checked\") &&\n \"\" + attributes.checked == \"true\")\n {\n tagParts[tagParts.length] = \" checked\";\n delete attributes.checked;\n }\n if (attributes.hasOwnProperty(\"multiple\") &&\n \"\" + attributes.multiple == \"true\")\n {\n tagParts[tagParts.length] = \" multiple\";\n delete attributes.multiple;\n }\n tagParts[tagParts.length] = \">\";\n\n var element =\n document.createElement(tagParts.join(\"\"));\n }\n else\n {\n var element = document.createElement(tagName);\n }\n\n for (var attr in attributes)\n {\n if (attributes.hasOwnProperty(attr))\n {\n setAttribute(element, attr, attributes[attr]);\n }\n }\n\n return element;\n };\n }\n // All other browsers\n else\n {\n return function(tagName, attributes)\n {\n attributes = attributes || {};\n var element = document.createElement(tagName);\n for (var attr in attributes)\n {\n if (attributes.hasOwnProperty(attr))\n {\n element.setAttribute(attr, attributes[attr]);\n }\n }\n return element;\n };\n }\n})();\n\n// Usage\nvar rb = createElement(\"input\", {type: \"radio\", checked: true});\n</code></pre>\n\n<p>The full DOMBuilder version also handles event listener registration and specification of child nodes.</p>\n"
},
{
"answer_id": 120418,
"author": "roundcrisis",
"author_id": 162325,
"author_profile": "https://Stackoverflow.com/users/162325",
"pm_score": 0,
"selected": false,
"text": "<p>why not creating the input, set the style to dispaly: none and then change the display when necesary\nthis way you can also probably handle users whitout js better.</p>\n"
},
{
"answer_id": 120433,
"author": "ujh",
"author_id": 4936,
"author_profile": "https://Stackoverflow.com/users/4936",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I wouldn't create nodes myself. As you've noticed there are just too many browser specific problems. Normally I use <a href=\"http://github.com/madrobby/scriptaculous/wikis/builder\" rel=\"nofollow noreferrer\">Builder.node</a> from <a href=\"http://script.aculo.us/\" rel=\"nofollow noreferrer\">script.aculo.us</a>. Using this your code would become something like this:</p>\n\n<pre><code>Builder.node('input', {type: 'radio', name: name})\n</code></pre>\n"
},
{
"answer_id": 1936533,
"author": "Cypher",
"author_id": 235584,
"author_profile": "https://Stackoverflow.com/users/235584",
"pm_score": 1,
"selected": false,
"text": "<p>Quick reply to an older post:</p>\n\n<p>The post above by Roundcrisis is fine, IF AND ONLY IF, you know the number of radio/checkbox controls that will be used before-hand. In some situations, addressed by this topic of 'dynamically creating radio buttons', the number of controls that will be needed by the user is not known. Further, I do not recommend 'skipping' the 'try-catch' error trapping, as this allows for ease of catching future browser implementations which may not comply with the current standards. Of these solutions, I recommend using the solution proposed by Patrick Wilkes in his reply to his own question.</p>\n\n<p>This is repeated here in an effort to avoid confusion:</p>\n\n<pre><code>function createRadioElement( name, checked ) {\n var radioInput;\n try {\n var radioHtml = '<input type=\"radio\" name=\"' + name + '\"';\n if ( checked ) {\n radioHtml += ' checked=\"checked\"';\n }\n radioHtml += '/>';\n radioInput = document.createElement(radioHtml);\n } catch( err ) {\n radioInput = document.createElement('input');\n radioInput.setAttribute('type', 'radio');\n radioInput.setAttribute('name', name);\n if ( checked ) {\n radioInput.setAttribute('checked', 'checked');\n }\n }\n return radioInput;}\n</code></pre>\n"
},
{
"answer_id": 8503100,
"author": "Dheeraj",
"author_id": 1097598,
"author_profile": "https://Stackoverflow.com/users/1097598",
"pm_score": 2,
"selected": false,
"text": "<p>My solution:</p>\n\n<pre><code>html\n head\n script(type='text/javascript')\n function createRadioButton()\n {\n var newRadioButton\n = document.createElement(input(type='radio',name='radio',value='1st'));\n document.body.insertBefore(newRadioButton);\n }\n body\n input(type='button',onclick='createRadioButton();',value='Create Radio Button')\n</code></pre>\n"
},
{
"answer_id": 12387980,
"author": "Sandeep Shekhawat",
"author_id": 1390850,
"author_profile": "https://Stackoverflow.com/users/1390850",
"pm_score": 2,
"selected": false,
"text": "<p>Dynamically created radio button in javascript:</p>\n\n<pre><code><%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”RadioDemo.aspx.cs” Inherits=”JavascriptTutorial.RadioDemo” %>\n\n<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>\n\n<html xmlns=”http://www.w3.org/1999/xhtml”>\n<head runat=”server”>\n<title></title>\n<script type=”text/javascript”>\n\n/* Getting Id of Div in which radio button will be add*/\nvar containerDivClientId = “<%= containerDiv.ClientID %>”;\n\n/*variable count uses for define unique Ids of radio buttons and group name*/\nvar count = 100;\n\n/*This function call by button OnClientClick event and uses for create radio buttons*/\nfunction dynamicRadioButton()\n{\n/* create a radio button */\nvar radioYes = document.createElement(“input”);\nradioYes.setAttribute(“type”, “radio”);\n\n/*Set id of new created radio button*/\nradioYes.setAttribute(“id”, “radioYes” + count);\n\n/*set unique group name for pair of Yes / No */\nradioYes.setAttribute(“name”, “Boolean” + count);\n\n/*creating label for Text to Radio button*/\nvar lblYes = document.createElement(“lable”);\n\n/*create text node for label Text which display for Radio button*/\nvar textYes = document.createTextNode(“Yes”);\n\n/*add text to new create lable*/\nlblYes.appendChild(textYes);\n\n/*add radio button to Div*/\ncontainerDiv.appendChild(radioYes);\n\n/*add label text for radio button to Div*/\ncontainerDiv.appendChild(lblYes);\n\n/*add space between two radio buttons*/\nvar space = document.createElement(“span”);\nspace.setAttribute(“innerHTML”, “&nbsp;&nbsp”);\ncontainerDiv.appendChild(space);\n\nvar radioNo = document.createElement(“input”);\nradioNo.setAttribute(“type”, “radio”);\nradioNo.setAttribute(“id”, “radioNo” + count);\nradioNo.setAttribute(“name”, “Boolean” + count);\n\nvar lblNo = document.createElement(“label”);\nlblNo.innerHTML = “No”;\ncontainerDiv.appendChild(radioNo);\ncontainerDiv.appendChild(lblNo);\n\n/*add new line for new pair of radio buttons*/\nvar spaceBr= document.createElement(“br”);\ncontainerDiv.appendChild(spaceBr);\n\ncount++;\nreturn false;\n}\n</script>\n</head>\n<body>\n<form id=”form1″ runat=”server”>\n<div>\n<asp:Button ID=”btnCreate” runat=”server” Text=”Click Me” OnClientClick=”return dynamicRadioButton();” />\n<div id=”containerDiv” runat=”server”></div>\n</div>\n</form>\n</body>\n</html>\n</code></pre>\n\n<p>(<a href=\"http://knowpacific.wordpress.com/2012/09/12/dynamically-created-radio-buttons-in-javascript/\" rel=\"nofollow\">source</a>)</p>\n"
},
{
"answer_id": 33281875,
"author": "Saravana Kumar",
"author_id": 1599942,
"author_profile": "https://Stackoverflow.com/users/1599942",
"pm_score": 2,
"selected": false,
"text": "<pre><code>for(i=0;i<=10;i++){\n var selecttag1=document.createElement(\"input\");\n selecttag1.setAttribute(\"type\", \"radio\");\n selecttag1.setAttribute(\"name\", \"irrSelectNo\"+i);\n selecttag1.setAttribute(\"value\", \"N\");\n selecttag1.setAttribute(\"id\",\"irrSelectNo\"+i);\n\n var lbl1 = document.createElement(\"label\");\n lbl1.innerHTML = \"YES\";\n cell3Div.appendChild(lbl);\n cell3Div.appendChild(selecttag1);\n}\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6370/"
]
| Dynamically creating a radio button using eg
```
var radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
```
works in Firefox but not in IE. Why not? | Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch:
```
function createRadioElement(name, checked) {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
``` |
118,698 | <p>In JavaScript, you can use <a href="http://peter.michaux.ca/article/3556" rel="noreferrer">Lazy Function Definitions</a> to optimize the 2nd - Nth call to a function by performing the <strong>expensive</strong> one-time operations only on the first call to the function.</p>
<p>I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed, nor is overloading a function.</p>
<p>Effectively what I'd like to do is like the following, only optimized so the 2nd - Nth calls (say 25-100) don't need to re-check if they are the first call.</p>
<pre><code>$called = false;
function foo($param_1){
global $called;
if($called == false){
doExpensiveStuff($param_1);
$called = true;
}
echo '<b>'.$param_1.'</b>';
}
</code></pre>
<p>PS I've thought about using an include_once() or require_once() as the first line in the function to execute the external code just once, but I've heard that these too are expensive.</p>
<p>Any Ideas? or is there a better way to tackle this?</p>
| [
{
"answer_id": 118717,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>Have you actually profiled this code? I'm doubtful that an extra boolean test is going to have any measurable impact on page rendering time.</p>\n"
},
{
"answer_id": 118718,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "<p>you can do <strong>conditional</strong> function definiton.</p>\n\n<pre><code>if( !function_exists('baz') )\n{ \n function baz( $args ){ \n echo $args; \n }\n}\n</code></pre>\n\n<p>But at present, a function becomes a brick when defined. </p>\n\n<p>You can use <code>create_function</code>, but I would suggest you <strong>DONT</strong> because it is slow, uses lots of memory, doesn't get free()'d untill php exits, and is a security hole as big as eval(). </p>\n\n<p>Wait till PHP5.3, where we have \"closures\" <a href=\"http://wiki.php.net/rfc/closures\" rel=\"nofollow noreferrer\">http://wiki.php.net/rfc/closures</a></p>\n\n<p>Then you'll be permitted to do </p>\n\n<pre><code>if( !isset( $baz ) ) \n { \n $baz = function( $args )\n { \n echo $args;\n }\n}\n\n$baz('hello');\n\n$baz = function( $args )\n{ \n echo $args + \"world\"; \n}\n$baz('hello');\n</code></pre>\n\n<p>Upon further reading, this is the effect you want. </p>\n\n<pre><code>$fname = 'f_first'; \nfunction f_first( $even ) \n{ \n global $fname; \n doExpensiveStuff(); \n $fname = 'f_others';\n $fname( $even );\n /* code */ \n}\nfunction f_others( $odd ) \n{\n print \"<b>\".$odd.\"</b>\";\n}\n\nforeach( $blah as $i=>$v ) \n{\n $fname($v);\n}\n</code></pre>\n\n<p>It'll do what you want, but the call might be a bit more expensive than a normal function call. </p>\n\n<p>In PHP5.3 This should be valid too:</p>\n\n<pre><code>$func = function( $x ) use ( $func ) \n{ \n doexpensive(); \n $func = function( $y )\n { \n print \"<b>\".$y.\"</b>\";\n }\n $func($x);\n}\nforeach( range(1..200) as $i=>$v ) \n{ \n $func( $v ); \n}\n</code></pre>\n\n<p>( Personally, I think of course that all these neat tricks are going to be epically slower than your earlier comparison of 2 positive bits. ;) ) </p>\n\n<p>If you're really concerned about getting the <em>best</em> speed everywhere</p>\n\n<pre><code>$data = // some array structure\ndoslowthing(); \nforeach( $data as $i => $v ) \n{\n // code here \n}\n</code></pre>\n\n<p>You may not be able to do that however, but you've not given enough scope to clarify. If you can do that however, then well, simple answers are often the best :)</p>\n"
},
{
"answer_id": 118752,
"author": "Jurassic_C",
"author_id": 20572,
"author_profile": "https://Stackoverflow.com/users/20572",
"pm_score": 0,
"selected": false,
"text": "<p>If you do wind up finding that an extra boolean test is going to be too expensive, you can set a variable to the name of a function and call it:</p>\n\n<pre><code>$func = \"foo\"; \n\nfunction foo()\n{\n global $func;\n $func = \"bar\";\n echo \"expensive stuff\";\n};\n\n\nfunction bar()\n{\n echo \"do nothing, i guess\";\n};\n\nfor($i=0; $i<5; $i++)\n{\n $func();\n}\n</code></pre>\n\n<p>Give that a shot</p>\n"
},
{
"answer_id": 118767,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 0,
"selected": false,
"text": "<p>Any reason you're commited to a functional style pattern? Despite having anonymous functions and plans for closure, PHP really isn't a functional language. It seems like a class and object would be the better solution here.</p>\n\n<pre><code>Class SomeClass{\n protected $whatever_called;\n function __construct(){\n $this->called = false;\n }\n public function whatever(){\n if(!$this->whatever_called){\n //expensive stuff\n $this->whatever_called = true;\n }\n //rest of the function\n }\n} \n</code></pre>\n\n<p>If you wanted to get fancy you could use the magic methods to avoid having to predefine the called booleans. If you don't want to instantiate an object, go static.</p>\n"
},
{
"answer_id": 118792,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 1,
"selected": false,
"text": "<p>Please don't use <code>include()</code> or <code>include_once()</code>, unless you don't care if the <code>include()</code> fails. If you're including code, then you care. Always use <code>require_once()</code>.</p>\n"
},
{
"answer_id": 119235,
"author": "dirtside",
"author_id": 20903,
"author_profile": "https://Stackoverflow.com/users/20903",
"pm_score": 5,
"selected": true,
"text": "<p>Use a local static var:</p>\n\n<pre><code>function foo() {\n static $called = false;\n if ($called == false) {\n $called = true;\n expensive_stuff();\n }\n}\n</code></pre>\n\n<p>Avoid using a global for this. It clutters the global namespace and makes the function less encapsulated. If other places besides the innards of the function need to know if it's been called, then it'd be worth it to put this function inside a class like Alan Storm indicated.</p>\n"
},
{
"answer_id": 119913,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 0,
"selected": false,
"text": "<p>PHP doesn't have lexical scope, so you can't do what you want with a function. However, PHP has classes, which conceptually works in exactly the same way for this purpose.</p>\n\n<p>In javascript, you would do:</p>\n\n<pre><code>var cache = null;\nfunction doStuff() {\n if (cache == null) {\n cache = doExpensiveStuff();\n }\n return cache;\n}\n</code></pre>\n\n<p>With classes (In PHP), you would do:</p>\n\n<pre><code>class StuffDoer {\n function doStuff() {\n if ($this->cache == null) {\n $this->cache = $this->doExpensiveStuff();\n }\n return $this->cache;\n }\n}\n</code></pre>\n\n<p>Yes, class-based oop is more verbose than functional programming, but performance-wise they should be about similar.</p>\n\n<p>All that aside, PHP 5.3 will probably get lexical scope/closure support, so when that comes out you can write in a more fluent functional-programming style. See the PHP rfc-wiki for a <a href=\"http://wiki.php.net/rfc/closures\" rel=\"nofollow noreferrer\">detailed description of this feature</a>.</p>\n"
},
{
"answer_id": 120044,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 0,
"selected": false,
"text": "<p>How about using local static variables?</p>\n\n<pre><code>function doStuff($param1) {\n static $called = false;\n if (!$called) {\n doExpensiveStuff($param1);\n $called = true;\n }\n // do the rest\n}\n</code></pre>\n\n<p>If you need to do expensive stuff only once for given parameter value, you could use an array buffer:</p>\n\n<pre><code>function doStuff($param1) {\n static $buffer = array();\n if (!array_key_exists($param1, $buffer)) {\n doExpensiveStuff($param1);\n $buffer[$param1] = true;\n }\n // do the rest\n}\n</code></pre>\n\n<p>Local static variables are persistent across function calls. They remember the value after return.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6144/"
]
| In JavaScript, you can use [Lazy Function Definitions](http://peter.michaux.ca/article/3556) to optimize the 2nd - Nth call to a function by performing the **expensive** one-time operations only on the first call to the function.
I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed, nor is overloading a function.
Effectively what I'd like to do is like the following, only optimized so the 2nd - Nth calls (say 25-100) don't need to re-check if they are the first call.
```
$called = false;
function foo($param_1){
global $called;
if($called == false){
doExpensiveStuff($param_1);
$called = true;
}
echo '<b>'.$param_1.'</b>';
}
```
PS I've thought about using an include\_once() or require\_once() as the first line in the function to execute the external code just once, but I've heard that these too are expensive.
Any Ideas? or is there a better way to tackle this? | Use a local static var:
```
function foo() {
static $called = false;
if ($called == false) {
$called = true;
expensive_stuff();
}
}
```
Avoid using a global for this. It clutters the global namespace and makes the function less encapsulated. If other places besides the innards of the function need to know if it's been called, then it'd be worth it to put this function inside a class like Alan Storm indicated. |
118,719 | <p>Usecase: The user makes font customizations to an object on the design surface, that I need to load/save to my datastore. I.e. settings like Bold, Italics, Size, Font Name need to persisted.</p>
<p>Is there some easy (and reliable) mechanism to convert/read back from a string representation of the font object (in which case I would need just one attribute)? Or is multiple properties combined with custom logic the right option? </p>
| [
{
"answer_id": 118754,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": true,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx\" rel=\"noreferrer\">TypeConverter</a>:</p>\n\n<pre><code>Font font = new Font(\"Arial\", 12, GraphicsUnit.Pixel);\n\nTypeConverter converter = TypeDescriptor.GetConverter(typeof (Font));\n\nstring fontStr = converter.ConvertToInvariantString(font);\n\nFont font2 = (Font) converter.ConvertFromString(fontStr);\n\nConsole.WriteLine(font.Name == font2.Name); // prints True\n</code></pre>\n\n<p>If you want to use XML serialization you can create Font class wrapper which will store some subset of Font properties.</p>\n\n<p><em>Note(Gishu) - Never access a type converter directly. Instead, access the appropriate converter by using TypeDescriptor. Very important :)</em></p>\n"
},
{
"answer_id": 118769,
"author": "Dr8k",
"author_id": 6014,
"author_profile": "https://Stackoverflow.com/users/6014",
"pm_score": 0,
"selected": false,
"text": "<p>What type of datastore do you need to persist this in? If it is just user settings that can be persisted in a file you could serialise the font object to a settings file in either binary or xml (if you want to be able to edit the config file directly). The serialisation namespaces (System.Xml.Serialization and System.Runtime.Serialization) provide all the tools to do this without writing custom code.</p>\n\n<p>MSDN Site on XML Serialisation: <a href=\"http://msdn.microsoft.com/en-us/library/ms950721.aspx\" rel=\"nofollow noreferrer\">XML Serialization in the .Net Framework</a></p>\n\n<p>[EDIT]So aparrently the font object isn't serialisable. oops :( Sorry.</p>\n"
},
{
"answer_id": 118860,
"author": "absfabs",
"author_id": 20085,
"author_profile": "https://Stackoverflow.com/users/20085",
"pm_score": 0,
"selected": false,
"text": "<p>In the project I'm working on, I went with the multiple properties. </p>\n\n<p>I save the font to a database table by breaking out its name, size, style and unit and then persist those values.</p>\n\n<p>Recreating the font on demand once these values are retrived is a snap.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
]
| Usecase: The user makes font customizations to an object on the design surface, that I need to load/save to my datastore. I.e. settings like Bold, Italics, Size, Font Name need to persisted.
Is there some easy (and reliable) mechanism to convert/read back from a string representation of the font object (in which case I would need just one attribute)? Or is multiple properties combined with custom logic the right option? | Use [TypeConverter](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx):
```
Font font = new Font("Arial", 12, GraphicsUnit.Pixel);
TypeConverter converter = TypeDescriptor.GetConverter(typeof (Font));
string fontStr = converter.ConvertToInvariantString(font);
Font font2 = (Font) converter.ConvertFromString(fontStr);
Console.WriteLine(font.Name == font2.Name); // prints True
```
If you want to use XML serialization you can create Font class wrapper which will store some subset of Font properties.
*Note(Gishu) - Never access a type converter directly. Instead, access the appropriate converter by using TypeDescriptor. Very important :)* |
118,727 | <p>I'm in the process of moving one of our projects from VS6 to VS2008 and I've hit the following compile error with mshtml.h:</p>
<pre><code>1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5272) : error C2143: syntax error : missing '}' before 'constant'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C2143: syntax error : missing ';' before '}'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2143: syntax error : missing ';' before '}'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}'
</code></pre>
<p>Following the first error statement drops into this part of the mshtml.h code, pointing at the "True = 1" line:</p>
<pre><code>EXTERN_C const GUID CLSID_CDocument;
EXTERN_C const GUID CLSID_CScriptlet;
typedef
enum _BoolValue
{ True = 1,
False = 0,
BoolValue_Max = 2147483647L
} BoolValue;
EXTERN_C const GUID CLSID_CPluginSite;
</code></pre>
<p>It looks like someone on expert-sexchange also came across this error but I'd rather not dignify that site with a "7 day free trial".</p>
<p>Any suggestions would be most welcome.</p>
| [
{
"answer_id": 118734,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": true,
"text": "<p>There is probably a #define changing something. Try running just the preprocessor on your .cpp and generating a .i file. The setting is in the project property pages.</p>\n\n<p>EDIT: Also, you can get the answer from that other expert site by scrolling to the bottom of the page. They have to do that or Google will take them out of their indexes.</p>\n"
},
{
"answer_id": 118739,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 1,
"selected": false,
"text": "<p>What other incodes do ou have in the currently compiling file? It may be that <code>True</code> has been defined by a macro already as <code>1</code>. That would explain the error.</p>\n"
},
{
"answer_id": 118745,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 2,
"selected": false,
"text": "<p>you might already have the symbols True & False defined, try</p>\n\n<pre><code>#undef True \n#undef False \n</code></pre>\n\n<p>before including that file.</p>\n"
},
{
"answer_id": 119020,
"author": "Lou",
"author_id": 4341,
"author_profile": "https://Stackoverflow.com/users/4341",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks Guys. I found the right spot for those #undef's. I dropped them into the classes header file just before a <code>#include <atlctl.h></code> that seemed to do the trick.</p>\n\n<p>And thanks for the tip about that other expert site, I'll have to keep that in mind.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4341/"
]
| I'm in the process of moving one of our projects from VS6 to VS2008 and I've hit the following compile error with mshtml.h:
```
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5272) : error C2143: syntax error : missing '}' before 'constant'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C2143: syntax error : missing ';' before '}'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2143: syntax error : missing ';' before '}'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}'
```
Following the first error statement drops into this part of the mshtml.h code, pointing at the "True = 1" line:
```
EXTERN_C const GUID CLSID_CDocument;
EXTERN_C const GUID CLSID_CScriptlet;
typedef
enum _BoolValue
{ True = 1,
False = 0,
BoolValue_Max = 2147483647L
} BoolValue;
EXTERN_C const GUID CLSID_CPluginSite;
```
It looks like someone on expert-sexchange also came across this error but I'd rather not dignify that site with a "7 day free trial".
Any suggestions would be most welcome. | There is probably a #define changing something. Try running just the preprocessor on your .cpp and generating a .i file. The setting is in the project property pages.
EDIT: Also, you can get the answer from that other expert site by scrolling to the bottom of the page. They have to do that or Google will take them out of their indexes. |
118,730 | <p>Does anyone know how I can get rid of the following assembler warning?</p>
<p>Code is x86, 32 bit:</p>
<pre><code>int test (int x)
{
int y;
// do a bit-rotate by 8 on the lower word. leave upper word intact.
asm ("rorw $8, %0\n\t": "=q"(y) :"0"(x));
return y;
}
</code></pre>
<p>If I compile it I get the following (very valid) warning:</p>
<pre><code>Warning: using `%ax' instead of `%eax' due to `w' suffix
</code></pre>
<p>What I'm looking for is a way to tell the compiler/assembler that I want to access the lower 16 bit sub-register of %0. Accessing the byte sub-registers (in this case AL and AH) would be nice to know as well. </p>
<p>I've already chosen the "q" modifier, so the compiler is forced to use EAX, EBX, ECX or EDX. I've made sure the compiler has to pick a register that has sub-registers.</p>
<p>I know that I can force the asm-code to use a specific register (and its sub-registers), but I want to leave the register-allocation job up to the compiler.</p>
| [
{
"answer_id": 118737,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "<p>You can use <code>%w0</code> if I remember right. I just tested it, too. :-)</p>\n<pre><code>int\ntest(int x)\n{\n int y;\n asm ("rorw $8, %w0" : "=q" (y) : "0" (x));\n return y;\n}\n</code></pre>\n<p>Edit: In response to the OP, yes, you can do the following too:</p>\n<pre><code>int\ntest(int x)\n{\n int y;\n asm ("xchg %b0, %h0" : "=Q" (y) : "0" (x));\n return y;\n}\n</code></pre>\n<p>For x86 it's documented in the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#x86-Operand-Modifiers\" rel=\"nofollow noreferrer\">x86 Operand Modifiers section</a> of the Extended Asm part of the manual.</p>\n<p>For non-x86 instruction sets, you may have to dig through their <code>.md</code> files in the GCC source. For example, <code>gcc/config/i386/i386.md</code> was the only place to find this before it was officially documented.</p>\n<p>(Related: <a href=\"https://stackoverflow.com/questions/34459803/in-gnu-c-inline-asm-what-are-the-size-override-modifiers-for-xmm-ymm-zmm-for-a\">In GNU C inline asm, what are the size-override modifiers for xmm/ymm/zmm for a single operand?</a> for vector registers.)</p>\n"
},
{
"answer_id": 119365,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 0,
"selected": false,
"text": "<p>So apparently there are tricks to do this... but it may not be so efficient. 32-bit x86 processors are generally <b>slow</b> at manipulating 16-bit data in general purpose registers. You ought to benchmark it if performance is important.</p>\n\n<p>Unless this is (a) performance critical and (b) proves to be much faster, I would save myself some maintenance hassle and just do it in C:</p>\n\n<pre><code>uint32_t y, hi=(x&~0xffff), lo=(x&0xffff);\ny = hi + (((lo >> 8) + (lo << 8))&0xffff);\n</code></pre>\n\n<p>With GCC 4.2 and -O2 this gets optimized down to six instructions...</p>\n"
},
{
"answer_id": 122375,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 2,
"selected": false,
"text": "<p>While I'm thinking about it ... you should replace the \"q\" constraint with a capital \"Q\" constraint in Chris's second solution:</p>\n\n<pre><code>int\ntest(int x)\n{\n int y;\n asm (\"xchg %b0, %h0\" : \"=Q\" (y) : \"0\" (x));\n return y;\n}\n</code></pre>\n\n<p>\"q\" and \"Q\" are slightly different in 64-bit mode, where you can get the lowest byte for all of the integer registers (ax, bx, cx, dx, si, di, sp, bp, r8-r15). But you can only get the second-lowest byte (e.g. ah) for the four original 386 registers (ax, bx, cx, dx).</p>\n"
},
{
"answer_id": 17825185,
"author": "Nathan Kurz",
"author_id": 49301,
"author_profile": "https://Stackoverflow.com/users/49301",
"pm_score": 3,
"selected": false,
"text": "<p>Long ago, but I'll likely need this for my own future reference...</p>\n\n<p>Adding on to Chris's fine answer says, the key is using a modifier between the '%' and the number of the output operand. For example, <code>\"MOV %1, %0\"</code> might become <code>\"MOV %q1, %w0\"</code>. </p>\n\n<p>I couldn't find anything in constraints.md, but <a href=\"https://raw.github.com/mirrors/gcc/trunk/gcc/config/i386/i386.c\" rel=\"noreferrer\">/gcc/config/i386/i386.c</a> had this potentially useful comment in the source for <code>print_reg()</code>:</p>\n\n<pre><code>/* Print the name of register X to FILE based on its machine mode and number.\n If CODE is 'w', pretend the mode is HImode.\n If CODE is 'b', pretend the mode is QImode.\n If CODE is 'k', pretend the mode is SImode.\n If CODE is 'q', pretend the mode is DImode.\n If CODE is 'x', pretend the mode is V4SFmode.\n If CODE is 't', pretend the mode is V8SFmode.\n If CODE is 'h', pretend the reg is the 'high' byte register.\n If CODE is 'y', print \"st(0)\" instead of \"st\", if the reg is stack op.\n If CODE is 'd', duplicate the operand for AVX instruction.\n */\n</code></pre>\n\n<p>A comment below for <code>ix86_print_operand()</code> offer an example: </p>\n\n<blockquote>\n <p>b -- print the QImode name of the register for the indicated operand. </p>\n \n <p>%b0 would print %al if operands[0] is reg 0.</p>\n</blockquote>\n\n<p>A few more useful options are listed under <a href=\"http://gcc.gnu.org/onlinedocs/gccint/Output-Template.html\" rel=\"noreferrer\">Output Template</a> of the <a href=\"http://gcc.gnu.org/onlinedocs/gccint/\" rel=\"noreferrer\">GCC Internals</a> documentation:</p>\n\n<blockquote>\n <p>‘%cdigit’ can be used to substitute an operand that is a constant\n value without the syntax that normally indicates an immediate operand.</p>\n \n <p>‘%ndigit’ is like ‘%cdigit’ except that the value of the constant is\n negated before printing.</p>\n \n <p>‘%adigit’ can be used to substitute an operand as if it were a memory\n reference, with the actual operand treated as the address. This may be\n useful when outputting a “load address” instruction, because often the\n assembler syntax for such an instruction requires you to write the\n operand as if it were a memory reference.</p>\n \n <p>‘%ldigit’ is used to substitute a label_ref into a jump instruction.</p>\n \n <p>‘%=’ outputs a number which is unique to each instruction in the\n entire compilation. This is useful for making local labels to be\n referred to more than once in a single template that generates\n multiple assembler instructions.</p>\n</blockquote>\n\n<p>The '<code>%c2</code>' construct allows one to properly format an LEA instruction using an offset: </p>\n\n<pre><code>#define ASM_LEA_ADD_BYTES(ptr, bytes) \\\n __asm volatile(\"lea %c1(%0), %0\" : \\\n /* reads/writes %0 */ \"+r\" (ptr) : \\\n /* reads */ \"i\" (bytes));\n</code></pre>\n\n<p>Note the crucial but sparsely documented 'c' in '<code>%c1</code>'. This macro is equivalent to </p>\n\n<pre><code>ptr = (char *)ptr + bytes\n</code></pre>\n\n<p>but without making use of the usual integer arithmetic execution ports. </p>\n\n<p>Edit to add:</p>\n\n<p>Making direct calls in x64 can be difficult, as it requires yet another undocumented modifier: '<code>%P0</code>' (which seems to be for PIC)</p>\n\n<pre><code>#define ASM_CALL_FUNC(func) \\\n __asm volatile(\"call %P0\") : \\\n /* no writes */ : \\\n /* reads %0 */ \"i\" (func)) \n</code></pre>\n\n<p>A lower case 'p' modifier also seems to function the same in GCC, although only the capital 'P' is recognized by ICC. More details are probably available at <a href=\"https://raw.github.com/mirrors/gcc/trunk/gcc/config/i386/i386.c\" rel=\"noreferrer\">/gcc/config/i386/i386.c</a>. Search for \"'p'\".</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15955/"
]
| Does anyone know how I can get rid of the following assembler warning?
Code is x86, 32 bit:
```
int test (int x)
{
int y;
// do a bit-rotate by 8 on the lower word. leave upper word intact.
asm ("rorw $8, %0\n\t": "=q"(y) :"0"(x));
return y;
}
```
If I compile it I get the following (very valid) warning:
```
Warning: using `%ax' instead of `%eax' due to `w' suffix
```
What I'm looking for is a way to tell the compiler/assembler that I want to access the lower 16 bit sub-register of %0. Accessing the byte sub-registers (in this case AL and AH) would be nice to know as well.
I've already chosen the "q" modifier, so the compiler is forced to use EAX, EBX, ECX or EDX. I've made sure the compiler has to pick a register that has sub-registers.
I know that I can force the asm-code to use a specific register (and its sub-registers), but I want to leave the register-allocation job up to the compiler. | You can use `%w0` if I remember right. I just tested it, too. :-)
```
int
test(int x)
{
int y;
asm ("rorw $8, %w0" : "=q" (y) : "0" (x));
return y;
}
```
Edit: In response to the OP, yes, you can do the following too:
```
int
test(int x)
{
int y;
asm ("xchg %b0, %h0" : "=Q" (y) : "0" (x));
return y;
}
```
For x86 it's documented in the [x86 Operand Modifiers section](https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#x86-Operand-Modifiers) of the Extended Asm part of the manual.
For non-x86 instruction sets, you may have to dig through their `.md` files in the GCC source. For example, `gcc/config/i386/i386.md` was the only place to find this before it was officially documented.
(Related: [In GNU C inline asm, what are the size-override modifiers for xmm/ymm/zmm for a single operand?](https://stackoverflow.com/questions/34459803/in-gnu-c-inline-asm-what-are-the-size-override-modifiers-for-xmm-ymm-zmm-for-a) for vector registers.) |
118,748 | <p>How do I open multiple pages in Internet Explorer 7 with a single DOS command? Is a batch file the only way to do this?</p>
<p>Thanks!</p>
| [
{
"answer_id": 118763,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately, there is no way to include multiple URLs as command-line parameters. Here is a a <a href=\"http://blogs.msdn.com/tonyschr/archive/2007/01/19/ie-automation-amp-tabs.aspx\" rel=\"nofollow noreferrer\">blog post</a> which details another (fairly convoluted) way to do it via Javascript.</p>\n"
},
{
"answer_id": 118796,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 4,
"selected": true,
"text": "<p>A batch file will work as a quick and dirty solution.</p>\n\n<pre><code>@echo off\n@setlocal\n\n:openurl\nset url=%~1\n\nif \"%url:~0,4%\" == \"http\" (\n start \"%ProgramFiles%\\Internet Explorer\\iexplore.exe\" \"%url%\"\n)\nif NOT \"%url:~0,4%\" == \"http\" (\n start \"%ProgramFiles%\\Internet Explorer\\iexplore.exe\" \"http://%url%\"\n)\n\nshift\nif \"%~1\" == \"\" goto :end\ngoto :openurl\n\n:end\n</code></pre>\n\n<p>Edit: added support for domain names without http handler prefix.</p>\n"
},
{
"answer_id": 6067360,
"author": "mohammed",
"author_id": 762115,
"author_profile": "https://Stackoverflow.com/users/762115",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>open a txt file with .txt extension</li>\n<li><p>Add the below lines</p>\n\n<ul>\n<li>start www.google.com</li>\n<li>start www.yahoo.com</li>\n<li>start www.microsoft.com</li>\n</ul></li>\n<li><p>save the file, select rename on the file and change the extension from .txt to .cmd </p></li>\n<li>double click the .cmd file to execute</li>\n</ol>\n"
},
{
"answer_id": 8347500,
"author": "voducdien",
"author_id": 1076212,
"author_profile": "https://Stackoverflow.com/users/1076212",
"pm_score": 1,
"selected": false,
"text": "<p>I’ve downloaded the software that does exactly this. From a command line open several websites without having to copy, paste VB scripts or batch files, etc… It’s available at <a href=\"http://www.multiwebpageopener.com\" rel=\"nofollow\">http://www.multiwebpageopener.com</a>.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How do I open multiple pages in Internet Explorer 7 with a single DOS command? Is a batch file the only way to do this?
Thanks! | A batch file will work as a quick and dirty solution.
```
@echo off
@setlocal
:openurl
set url=%~1
if "%url:~0,4%" == "http" (
start "%ProgramFiles%\Internet Explorer\iexplore.exe" "%url%"
)
if NOT "%url:~0,4%" == "http" (
start "%ProgramFiles%\Internet Explorer\iexplore.exe" "http://%url%"
)
shift
if "%~1" == "" goto :end
goto :openurl
:end
```
Edit: added support for domain names without http handler prefix. |
118,774 | <p>Deep down in WinDef.h there's this relic from the segmented memory era:</p>
<pre><code>#define far
#define near
</code></pre>
<p>This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?</p>
| [
{
"answer_id": 118779,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 2,
"selected": false,
"text": "<p>maybe:</p>\n\n<pre><code>#undef near\n#undef far\n</code></pre>\n\n<p>could be dangerous though...</p>\n"
},
{
"answer_id": 118780,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": -1,
"selected": false,
"text": "<p>Best not to. They are defined for backwards compatibility with older code - if you got rid of them somehow and then later needed to use some of that old code you'd be broken.</p>\n"
},
{
"answer_id": 118782,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>Undefine any macros you don't want after including <code>windows.h</code>:</p>\n\n<pre><code>#include <windows.h>\n#undef near\n#undef far\n</code></pre>\n"
},
{
"answer_id": 118873,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 1,
"selected": false,
"text": "<p>You probably don't want to undefined near and far everywhere. But when you need to use the variable names, you can use the following to undefine the macro locally and add it back when you are done.</p>\n\n<pre><code>#pragma push_macro(\"near\")\n#undef near\n//your code here.\n#pragma pop_macro (\"near\")\n</code></pre>\n"
},
{
"answer_id": 119553,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 6,
"selected": true,
"text": "<p>You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended. </p>\n\n<p>The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
]
| Deep down in WinDef.h there's this relic from the segmented memory era:
```
#define far
#define near
```
This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables? | You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended.
The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone. |
118,813 | <p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
| [
{
"answer_id": 118820,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "<p>I have both installed:</p>\n\n<pre><code>$ which python\n/usr/bin/python\n$ which python2.5\n/opt/local/bin/python2.5\n</code></pre>\n\n<p>I also added the following line to my <code>.profile</code>:</p>\n\n<pre><code>export PATH=/opt/local/bin:/opt/local/sbin:$PATH\n</code></pre>\n"
},
{
"answer_id": 118821,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of uninstalling the built-in Python, install the MacPorts version and then modify your <code>$PATH</code> to have the MacPorts version first.</p>\n\n<p>For example, if MacPorts installs <code>/usr/local/bin/python</code>, then modify your <code>.bashrc</code> to include <code>PATH=/usr/local/bin:$PATH</code> at the end.</p>\n"
},
{
"answer_id": 118823,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 2,
"selected": false,
"text": "<p>I wouldn't uninstall it since many scripts will expect python to be in the usual places when they do not follow convention and use <code>#!/usr/bin/env python</code>. You should simply edit your <code>.profile</code> or <code>.bash_profile</code> so the macports binaries are the first in your path.</p>\n\n<p>Your <code>.profile</code> should have this line: </p>\n\n<pre><code>export PATH=/opt/local/bin:/opt/local/sbin:$PATH\n</code></pre>\n\n<p>If not, add it in, and now your shell will search macport's <code>bin/</code> first, and should find macports python before system python.</p>\n"
},
{
"answer_id": 118824,
"author": "jacobian",
"author_id": 18184,
"author_profile": "https://Stackoverflow.com/users/18184",
"pm_score": 5,
"selected": false,
"text": "<p>Don't. Apple ships various system utilities that rely on the system Python (and particularly the Python \"framework\" build); removing it will cause you problems.</p>\n\n<p>Instead, modify your PATH environ variable in your <code>~/.bash_profile</code> to put <code>/opt/local/bin</code> first.</p>\n"
},
{
"answer_id": 604946,
"author": "bryan",
"author_id": 73049,
"author_profile": "https://Stackoverflow.com/users/73049",
"pm_score": 4,
"selected": false,
"text": "<p>Use the <a href=\"http://www.macports.org/ports.php?by=name&substr=python_select\" rel=\"noreferrer\">python_select</a> port to switch python interpreters.</p>\n\n<pre><code>sudo port install python25\nsudo port install python_select\nsudo python_select python25\n</code></pre>\n\n<p>This will symlink <code>/opt/local/bin/python</code> to the selected version. Then export <code>PATH</code> as described above.</p>\n"
},
{
"answer_id": 2621262,
"author": "Simo Salminen",
"author_id": 72544,
"author_profile": "https://Stackoverflow.com/users/72544",
"pm_score": 2,
"selected": false,
"text": "<p>The current Macports installer does the .profile PATH modification automatically.</p>\n"
},
{
"answer_id": 6166416,
"author": "chipiik",
"author_id": 774930,
"author_profile": "https://Stackoverflow.com/users/774930",
"pm_score": 4,
"selected": false,
"text": "<p><code>python_select</code> is now deprecated, use this instead:</p>\n\n<pre><code>sudo port select python python26\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013/"
]
| I want to use the macports version of python instead of the one that comes with Leopard. | I have both installed:
```
$ which python
/usr/bin/python
$ which python2.5
/opt/local/bin/python2.5
```
I also added the following line to my `.profile`:
```
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
``` |
118,839 | <p>I would like to replace only the group in parenthesis in this expression :</p>
<pre><code>my_string.gsub(/<--MARKER_START-->(.)*<--MARKER_END-->/, 'replace_text')
</code></pre>
<p>so that I get : <code><--MARKER_START-->replace_text<--MARKER_END--></code></p>
<p>I know I could repeat the whole <code>MARKER_START</code> and <code>MARKER_END</code> blocks in the substitution expression but I thought there should be a more simple way to do this.</p>
| [
{
"answer_id": 118852,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": true,
"text": "<p>You could do something like this:</p>\n\n<pre><code>my_string.gsub(/(<--MARKER_START-->)(.*)(<--MARKER_END-->)/, '\\1replace_text\\3')\n</code></pre>\n"
},
{
"answer_id": 118958,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it with <a href=\"http://www.perlmonks.org/?node_id=518444\" rel=\"nofollow noreferrer\">zero width look-ahead and look-behind assertions</a>.</p>\n\n<p>This regex should work in ruby 1.9 and in perl and many other places:</p>\n\n<p><em>Note: ruby 1.8 only supports look-ahead assertions. You need both look-ahead and look-behind to do this properly.</em></p>\n\n<pre><code> s.gsub( /(?<=<--MARKER START-->).*?(?=<--MARKER END-->)/, 'replacement text' )\n</code></pre>\n\n<p>What happens in ruby 1.8 is the <code>?<=</code> causes it to crash because it doesn't understand the look-behind assertion. For that part, you then have to fall back to using a backreference - like <a href=\"https://stackoverflow.com/questions/118839/gsub-partial-replace#118852\">Greig Hewgill mentions</a></p>\n\n<p>so what you get is</p>\n\n<pre><code> s.gsub( /(<--MARKER START-->).*?(?=<--MARKER END-->)/, '\\1replacement text' )\n</code></pre>\n\n<h3>EXPLANATION THE FIRST:</h3>\n\n<p>I've replaced the <code>(.)*</code> in the middle of your regex with <code>.*?</code> - this is non-greedy.\nIf you don't have non-greedy, then your regex will try and match as much as it can - if you have 2 markers on one line, it goes wrong. This is best illustrated by example:</p>\n\n<pre><code>\"<b>One</b> Two <b>Three</b>\".gsub( /<b>.*<\\/b>/, 'BOLD' )\n=> \"BOLD\"\n</code></pre>\n\n<p>What we actually want:</p>\n\n<pre><code>\"<b>One</b> Two <b>Three</b>\".gsub( /<b>.*?<\\/b>/, 'BOLD' )\n=> \"BOLD Two BOLD\"\n</code></pre>\n\n<h3>EXPLANATION THE SECOND:</h3>\n\n<p>zero-width-look-ahead-assertion sounds like a giant pile of nerdly confusion.</p>\n\n<p>What \"look-ahead-assertion\" actually means is \"Only match, if the thing we are looking for, is followed by this other stuff.</p>\n\n<p>For example, only match a digit, if it is followed by an F.</p>\n\n<pre><code>\"123F\" =~ /\\d(?=F)/ # will match the 3, but not the 1 or the 2\n</code></pre>\n\n<p>What \"zero width\" actually means is \"consider the 'followed by' in our search, but don't count it as part of the match when doing replacement or grouping or things like that.\nUsing the same example of 123F, If we didn't use the lookahead assertion, and instead just do this:</p>\n\n<pre><code>\"123F\" =~ /\\dF/ # will match 3F, because F is considered part of the match\n</code></pre>\n\n<p>As you can see, this is ideal for checking for our <code><--MARKER END--></code>, but what we need for the <code><--MARKER START--></code> is the ability to say \"Only match, if the thing we are looking for FOLLOWS this other stuff\". That's called a look-behind assertion, which ruby 1.8 doesn't have for some strange reason..</p>\n\n<p>Hope that makes sense :-)</p>\n\n<p>PS: Why use lookahead assertions instead of just backreferences? If you use lookahead, you're not actually replacing the <code><--MARKER--></code> bits, only the contents. If you use backreferences, you are replacing the whole lot. I don't know if this incurs much of a performance hit, but from a programming point of view it seems like the right thing to do, as we don't actually want to be replacing the markers at all.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20871/"
]
| I would like to replace only the group in parenthesis in this expression :
```
my_string.gsub(/<--MARKER_START-->(.)*<--MARKER_END-->/, 'replace_text')
```
so that I get : `<--MARKER_START-->replace_text<--MARKER_END-->`
I know I could repeat the whole `MARKER_START` and `MARKER_END` blocks in the substitution expression but I thought there should be a more simple way to do this. | You could do something like this:
```
my_string.gsub(/(<--MARKER_START-->)(.*)(<--MARKER_END-->)/, '\1replace_text\3')
``` |
118,851 | <p>Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work.</p>
<p>A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here?</p>
<pre><code>routes.MapRoute("UserItems", "User/{UserID}/Items",
new {controller = "User", action = "Items"});
</code></pre>
<p>And on my aspx page</p>
<pre><code>Html.ActionLink("Items", "UserItems", new { UserID = 1 })
</code></pre>
| [
{
"answer_id": 118996,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 1,
"selected": false,
"text": "<p>Can you post more information? What URL is the aspx page generating in the link? It could be because of the order of your routes definition. I think you need your route to be declared before the default route.</p>\n"
},
{
"answer_id": 119040,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 2,
"selected": false,
"text": "<p>Going by the MVC Preview 4 code I have in front of me the overload for Html.ActionLink() you are using is this one:</p>\n\n<pre><code>public string ActionLink(string linkText, string actionName, object values);\n</code></pre>\n\n<p>Note how the second parameter is the <em>actionName</em> not the <em>routeName</em>.</p>\n\n<p>As such, try:</p>\n\n<pre><code>Html.ActionLink(\"Items\", \"Items\", new { UserID = 1 })\n</code></pre>\n\n<p>Alternatively, try:</p>\n\n<pre><code><a href=\"<%=Url.RouteUrl(\"UserItems\", new { UserId = 1 })%>\">Items</a>\n</code></pre>\n"
},
{
"answer_id": 712857,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": 0,
"selected": false,
"text": "<p>Firstly start with looking at what URL it generates and checking it with <a href=\"http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx\" rel=\"nofollow noreferrer\">Phil Haack</a>'s route debug library. It will clear lots of things up.</p>\n\n<p>If you're having a bunch of routes you might want to consider naming your routes and using named routing. It will make your intent more clear when you re-visit your code and it can potentially improve parsing speed.</p>\n\n<p>Furthermore (and this is purely a personal opinion) I like to generate my links somewhere at the start of the page in strings and then put those strings in my HTML. It's a tiny overhead but makes the code much more readable in my opinion. Furthermore if you have or repeated links, you have to generate them only once.</p>\n\n<p>I prefer to put</p>\n\n<pre><code><% string action = Url.RouteUrl(\"NamedRoute\", new \n { controller=\"User\",\n action=\"Items\",\n UserID=1});%>\n</code></pre>\n\n<p>and later on write</p>\n\n<pre><code><a href=\"<%=action%>\">link</a>\n</code></pre>\n"
},
{
"answer_id": 4840673,
"author": "Dayi Chen",
"author_id": 595443,
"author_profile": "https://Stackoverflow.com/users/595443",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Html.ActionLink(\"Items\", \"User\", new { UserID = 1 })\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
]
| Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work.
A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here?
```
routes.MapRoute("UserItems", "User/{UserID}/Items",
new {controller = "User", action = "Items"});
```
And on my aspx page
```
Html.ActionLink("Items", "UserItems", new { UserID = 1 })
``` | Going by the MVC Preview 4 code I have in front of me the overload for Html.ActionLink() you are using is this one:
```
public string ActionLink(string linkText, string actionName, object values);
```
Note how the second parameter is the *actionName* not the *routeName*.
As such, try:
```
Html.ActionLink("Items", "Items", new { UserID = 1 })
```
Alternatively, try:
```
<a href="<%=Url.RouteUrl("UserItems", new { UserId = 1 })%>">Items</a>
``` |
118,863 | <p>When is it appropriate to use a class in Visual Basic for Applications (VBA)?</p>
<p>I'm assuming the <a href="http://en.wikipedia.org/wiki/Class_(computer_science)#Reasons_for_using_classes" rel="noreferrer">accelerated development and reduction of introducing bugs</a> is a common benefit for most languages that support OOP. But with VBA, is there a specific criterion? </p>
| [
{
"answer_id": 118870,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": -1,
"selected": false,
"text": "<p>I don't see why the criteria for VBA would be any different from another language, particularly if you are referring to VB.NET.</p>\n"
},
{
"answer_id": 118980,
"author": "cori",
"author_id": 8151,
"author_profile": "https://Stackoverflow.com/users/8151",
"pm_score": 2,
"selected": false,
"text": "<p>I wouldn't say there's a specific criterion, but I've never really found a useful place to use Classes in VBA code. In my mind it's so tied to the existing models around the Office apps that adding additional abstraction outside of that object model just confuses things.</p>\n\n<p>That's not to say one <strong>couldn't</strong> find a useful place for a class in VBA, or do perfectly useful things using a class, just that I've never found them useful in that environment.</p>\n"
},
{
"answer_id": 126502,
"author": "JonnyGold",
"author_id": 2665,
"author_profile": "https://Stackoverflow.com/users/2665",
"pm_score": 1,
"selected": false,
"text": "<p>You can also reuse VBA code without using actual classes. For example, if you have a called, VBACode. You can access any function or sub in any module with the following syntax:</p>\n\n<pre><code>VBCode.mysub(param1, param2)\n</code></pre>\n\n<p>If you create a reference to a template/doc (as you would a dll), you can reference code from other projects in the same way.</p>\n"
},
{
"answer_id": 132678,
"author": "ajp",
"author_id": 22045,
"author_profile": "https://Stackoverflow.com/users/22045",
"pm_score": 3,
"selected": false,
"text": "<p>I think the criteria is the same as other languages</p>\n\n<p>If you need to tie together several pieces of data and some methods and also specifically handle what happens when the object is created/terminated, classes are ideal</p>\n\n<p>say if you have a few procedures which fire when you open a form and one of them is taking a long time, you might decide you want to time each stage...... </p>\n\n<p>You could create a stopwatch class with methods for the obvious functions for starting and stopping, you could then add a function to retrieve the time so far and report it in a text file, using an argument representing the name of the process being timed. You could write logic to log only the slowest performances for investigation. </p>\n\n<p>You could then add a progress bar object with methods to open and close it and to display the names of the current action, along with times in ms and probable time remaining based on previous stored reports etc</p>\n\n<p>Another example might be if you dont like Access's user group rubbish, you can create your own User class with methods for loging in and out and features for group-level user access control/auditing/logging certain actions/tracking errors etc </p>\n\n<p>Of course you could do this using a set of unrelated methods and lots of variable passing, but to have it all encapsulated in a class just seems better to me. </p>\n\n<p>You do sooner or later come near to the limits of VBA, but its quite a powerful language and if your company ties you to it you can actually get some good, complex solutions out of it. </p>\n"
},
{
"answer_id": 134707,
"author": "jinsungy",
"author_id": 1316,
"author_profile": "https://Stackoverflow.com/users/1316",
"pm_score": 1,
"selected": false,
"text": "<p>Developing software, even with Microsoft Access, using Object Oriented Programming is generally a good practice. It will allow for scalability in the future by allowing objects to be loosely coupled, along with a number of advantages. This basically means that the objects in your system will be less dependent on each other, so refactoring becomes a lot easier. You can achieve this is Access using Class Modules. The downside is that you cannot perform Class Inheritance or Polymorphism in VBA. In the end, there's no hard and fast rule about using classes, just best practices. But keep in mind that as your application grows, the easier it is to maintain using classes. </p>\n"
},
{
"answer_id": 143395,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 7,
"selected": true,
"text": "<p>It depends on who's going to develop and maintain the code. Typical \"Power User\" macro writers hacking small ad-hoc apps may well be confused by using classes. But for serious development, the reasons to use classes are the same as in other languages. You have the same restrictions as VB6 - no inheritance - but you can have polymorphism by using interfaces.</p>\n\n<p>A good use of classes is to represent entities, and collections of entities. For example, I often see VBA code that copies an Excel range into a two-dimensional array, then manipulates the two dimensional array with code like:</p>\n\n<pre><code>Total = 0\nFor i = 0 To NumRows-1\n Total = Total + (OrderArray(i,1) * OrderArray(i,3))\nNext i\n</code></pre>\n\n<p>It's more readable to copy the range into a collection of objects with appropriately-named properties, something like:</p>\n\n<pre><code>Total = 0\nFor Each objOrder in colOrders\n Total = Total + objOrder.Quantity * objOrder.Price\nNext i\n</code></pre>\n\n<p>Another example is to use classes to implement the RAII design pattern (google for it). For example, one thing I may need to do is to unprotect a worksheet, do some manipulations, then protect it again. Using a class ensures that the worksheet will always be protected again even if an error occurs in your code:</p>\n\n<pre><code>--- WorksheetProtector class module ---\n\nPrivate m_objWorksheet As Worksheet\nPrivate m_sPassword As String\n\nPublic Sub Unprotect(Worksheet As Worksheet, Password As String)\n ' Nothing to do if we didn't define a password for the worksheet\n If Len(Password) = 0 Then Exit Sub\n\n ' If the worksheet is already unprotected, nothing to do\n If Not Worksheet.ProtectContents Then Exit Sub\n\n ' Unprotect the worksheet\n Worksheet.Unprotect Password\n\n ' Remember the worksheet and password so we can protect again\n Set m_objWorksheet = Worksheet\n m_sPassword = Password\nEnd Sub\n\nPublic Sub Protect()\n ' Protects the worksheet with the same password used to unprotect it\n If m_objWorksheet Is Nothing Then Exit Sub\n If Len(m_sPassword) = 0 Then Exit Sub\n\n ' If the worksheet is already protected, nothing to do\n If m_objWorksheet.ProtectContents Then Exit Sub\n\n m_objWorksheet.Protect m_sPassword\n Set m_objWorksheet = Nothing\n m_sPassword = \"\"\nEnd Sub\n\nPrivate Sub Class_Terminate()\n ' Reprotect the worksheet when this object goes out of scope\n On Error Resume Next\n Protect\nEnd Sub\n</code></pre>\n\n<p>You can then use this to simplify your code:</p>\n\n<pre><code>Public Sub DoSomething()\n Dim objWorksheetProtector as WorksheetProtector\n Set objWorksheetProtector = New WorksheetProtector\n objWorksheetProtector.Unprotect myWorksheet, myPassword\n\n ... manipulate myWorksheet - may raise an error\n\nEnd Sub \n</code></pre>\n\n<p>When this Sub exits, objWorksheetProtector goes out of scope, and the worksheet is protected again.</p>\n"
},
{
"answer_id": 987766,
"author": "Smandoli",
"author_id": 122139,
"author_profile": "https://Stackoverflow.com/users/122139",
"pm_score": 2,
"selected": false,
"text": "<p>For data recursion (a.k.a. BOM handling), a custom class is critically helpful and I think sometimes indispensable. You can make a recursive function without a class module, but a lot of data issues can't be addressed effectively. </p>\n\n<p>(I don't know why people aren't out peddling BOM library-sets for VBA. Maybe the XML tools have made a difference.) </p>\n\n<p>Multiple form instances is the common application of a class (many automation problems are otherwise unsolvable), I assume the question is about <strong>custom</strong> classes. </p>\n"
},
{
"answer_id": 989083,
"author": "Oorang",
"author_id": 102270,
"author_profile": "https://Stackoverflow.com/users/102270",
"pm_score": 2,
"selected": false,
"text": "<p>I use classes when I need to do something and a class will do it best:) For instance if you need to respond to (or intercept) events, then you need a class. Some people hate UDTs (user defined types) but I like them, so I use them if I want plain-english self-documenting code. Pharmacy.NCPDP being a lot easier to read then strPhrmNum :) But a UDT is limited, so say I want to be able to set Pharmacy.NCPDP and have all the other properties populate. And I also want make it so you can't accidentally alter the data. Then I need a class, because you don't have readonly properties in a UDT, etc. </p>\n\n<p>Another consideration is just simple readability. If you are doing complex data structures, it's often beneficial to know you just need to call Company.Owner.Phone.AreaCode then trying to keep track of where everything is structured. Especially for people who have to maintain that codebase 2 years after you left:)</p>\n\n<p>My own two cents is \"Code With Purpose\". Don't use a class without a reason. But if you have a reason then do it:)</p>\n"
},
{
"answer_id": 9254543,
"author": "Jason TEPOORTEN",
"author_id": 1204438,
"author_profile": "https://Stackoverflow.com/users/1204438",
"pm_score": 2,
"selected": false,
"text": "<p>I use classes if I want to create an self-encapsulated package of code that I will use across many VBA projects that come across for various clients.</p>\n"
},
{
"answer_id": 9264988,
"author": "Mike",
"author_id": 1207363,
"author_profile": "https://Stackoverflow.com/users/1207363",
"pm_score": 3,
"selected": false,
"text": "<p>Classes are extremely useful when dealing with the more complex API functions, and particularly when they require a data structure.</p>\n\n<p>For example, the GetOpenFileName() and GetSaveFileName() functions take an OPENFILENAME stucture with many members. you might not need to take advantage of all of them but they are there and should be initialized.</p>\n\n<p>I like to wrap the structure (UDT) and the API function declarations into a CfileDialog class. The Class_Initialize event sets up the default values of the structure's members, so that when I use the class, I only need to set the members I want to change (through Property procedures). Flag constants are implemented as an Enum. So, for example, to choose a spreadsheet to open, my code might look like this:</p>\n\n<pre><code>Dim strFileName As String\nDim dlgXLS As New CFileDialog\n\nWith dlgXLS\n .Title = \"Choose a Spreadsheet\"\n .Filter = \"Excel (*.xls)|*.xls|All Files (*.*)|*.*\"\n .Flags = ofnFileMustExist OR ofnExplorer\n\n If OpenFileDialog() Then\n strFileName = .FileName\n End If\nEnd With\nSet dlgXLS = Nothing\n</code></pre>\n\n<p>The class sets the default directory to My Documents, though if I wanted to I could change it with the InitDir property. </p>\n\n<p>This is just one example of how a class can be hugely beneficial in a VBA application.</p>\n"
},
{
"answer_id": 45492083,
"author": "Bellow Akambi",
"author_id": 8413575,
"author_profile": "https://Stackoverflow.com/users/8413575",
"pm_score": 0,
"selected": false,
"text": "<p>You can define a sql wrapper class in access that is more convenient than the recordsets and querydefs. For example if you want to update a table based on a criteria in another related table, you cannot use joins. You could built a vba recorset and querydef to do that however i find it easier with a class. Also, your application can have some concept that need more that 2 tables, it might be better imo to use classes for that. E.g. You application track incidents. Incident have several attributes that will hold in several tables {users and their contacts or profiles, incident description; status tracking; Checklists to help the support officer to reply tonthe incident; Reply ...} . To keep track of all the queries and relationships involved, oop can be helpful. It is a relief to be able to do Incident.Update(xxx) instead of all the coding ...</p>\n"
},
{
"answer_id": 64596272,
"author": "Gener4tor",
"author_id": 9930052,
"author_profile": "https://Stackoverflow.com/users/9930052",
"pm_score": 1,
"selected": false,
"text": "<p>As there is a lot code overhead in using classes in VBA I think a class has to provide more benefit than in other languages:</p>\n<p>So this are things to consider before using a class instead of functions:</p>\n<ul>\n<li><p>There is no class-inheritance in vba. So prepare to copy some code when you do similar small things in different classes. This happens especially when you want to work with interfaces and want to implement one interfaces in different classes.</p>\n</li>\n<li><p>There are no built in constructors in vba-classes. In my case I create a extra function like below to simulate this. But of curse, this is overhead too and can be ignored by the one how uses the class. Plus: As its not possible to use different functions with the same name but different parameters, you have to use different names for your "constructor"-functions. Also the functions lead to an extra debug-step which can be quite annoying.</p>\n</li>\n</ul>\n<code>\nPublic Function MyClass(ByVal someInit As Boolean) As MyClassClass\n Set MyClass = New MyClassClass\n Call MyClass.Init(someInit)\nEnd Function\n</code>\n<ul>\n<li><p>The development environment does not provide a "goto definition" for class-names. This can be quite annoying, especially when using classes with interfaces, because you always have to use the module-explorer to jump to the class code.</p>\n</li>\n<li><p>object-variables are used different to other variable-types in different places. So you have to use a extra "Set" to assign a object</p>\n</li>\n</ul>\n<p><code>Set varName = new ClassName</code></p>\n<ul>\n<li><p>if you want to use properties with objects this is done by a different setter. You have to use "set" instead of "let"</p>\n</li>\n<li><p>If you implement an interface in vba the function-name is named "InterfaceName_functionName" and defined as private. So you can use the interface function only when you cast the Variable to the Interface. If you want to use the function with the original class, you have to create an extra "public" function which only calls the interface function (see below). This creates an extra debug-step too.</p>\n</li>\n</ul>\n<code>\n'content of class-module: MyClass\nimplements IMyInterface\nprivate sub IMyInterface_SomeFunction()\n 'This can only be called if you got an object of type \"IMyInterface\"\nend function\nprivate sub IMyInterface_SomeFunction()\n 'You need this to call the function when having an object of the type \"MyClass\"\n Call IMyInterface_SomeFunction()\nend function</code>\n<p>This means:</p>\n<ul>\n<li>I !dont! use classes when they would contain no member-variables.</li>\n<li>I am aware of the overhead and dont use classes as the default to do things. Usually functions-only is the default way to do things in VBA.</li>\n</ul>\n<p>Examples of classes I created which I found to be useful:</p>\n<ul>\n<li>Collection-Classes: e.g. StringCollection, LongCollection which provide the collection functionality vba is missing</li>\n<li>DbInserter-Class: Class to create insert-statements</li>\n</ul>\n<p>Examples of classes I created which I dont found to be useful:</p>\n<ul>\n<li>Converter-class: A class which would have provided the functionality for converting variables to other types (e.g. StringToLong, VariantToString)</li>\n<li>StringTool-class: A class which would have provided some functionality for strings. e.g. StartsWith</li>\n</ul>\n"
},
{
"answer_id": 73012015,
"author": "6diegodiego9",
"author_id": 11738627,
"author_profile": "https://Stackoverflow.com/users/11738627",
"pm_score": 0,
"selected": false,
"text": "<p>In VBA, I prefer classes to modules when:</p>\n<ul>\n<li>(frequent case) I want multiple simultaneous instances (objects) of a common structure (class) each with own independent properties.<br>\nExample:<br>Dim EdgeTabGoogle as new Selenium.EdgeDriver<br>Dim EdgeTabBing as new\nSelenium.EdgeDriver<br>'Open both, then do something and read data to and from both, then close both</li>\n<li>(sometimes) I want to take advantage of the Class_Initialize and Class_Terminate automatic functions</li>\n<li>(sometimes) I want hierarchical tree of procedures (for just variables a chain of "Type" is sufficient), for better readability and Intellisense</li>\n<li>(rarely) I want public variables or procedures to not show in Intellisense globally (unless preceded by the object name)</li>\n</ul>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3155/"
]
| When is it appropriate to use a class in Visual Basic for Applications (VBA)?
I'm assuming the [accelerated development and reduction of introducing bugs](http://en.wikipedia.org/wiki/Class_(computer_science)#Reasons_for_using_classes) is a common benefit for most languages that support OOP. But with VBA, is there a specific criterion? | It depends on who's going to develop and maintain the code. Typical "Power User" macro writers hacking small ad-hoc apps may well be confused by using classes. But for serious development, the reasons to use classes are the same as in other languages. You have the same restrictions as VB6 - no inheritance - but you can have polymorphism by using interfaces.
A good use of classes is to represent entities, and collections of entities. For example, I often see VBA code that copies an Excel range into a two-dimensional array, then manipulates the two dimensional array with code like:
```
Total = 0
For i = 0 To NumRows-1
Total = Total + (OrderArray(i,1) * OrderArray(i,3))
Next i
```
It's more readable to copy the range into a collection of objects with appropriately-named properties, something like:
```
Total = 0
For Each objOrder in colOrders
Total = Total + objOrder.Quantity * objOrder.Price
Next i
```
Another example is to use classes to implement the RAII design pattern (google for it). For example, one thing I may need to do is to unprotect a worksheet, do some manipulations, then protect it again. Using a class ensures that the worksheet will always be protected again even if an error occurs in your code:
```
--- WorksheetProtector class module ---
Private m_objWorksheet As Worksheet
Private m_sPassword As String
Public Sub Unprotect(Worksheet As Worksheet, Password As String)
' Nothing to do if we didn't define a password for the worksheet
If Len(Password) = 0 Then Exit Sub
' If the worksheet is already unprotected, nothing to do
If Not Worksheet.ProtectContents Then Exit Sub
' Unprotect the worksheet
Worksheet.Unprotect Password
' Remember the worksheet and password so we can protect again
Set m_objWorksheet = Worksheet
m_sPassword = Password
End Sub
Public Sub Protect()
' Protects the worksheet with the same password used to unprotect it
If m_objWorksheet Is Nothing Then Exit Sub
If Len(m_sPassword) = 0 Then Exit Sub
' If the worksheet is already protected, nothing to do
If m_objWorksheet.ProtectContents Then Exit Sub
m_objWorksheet.Protect m_sPassword
Set m_objWorksheet = Nothing
m_sPassword = ""
End Sub
Private Sub Class_Terminate()
' Reprotect the worksheet when this object goes out of scope
On Error Resume Next
Protect
End Sub
```
You can then use this to simplify your code:
```
Public Sub DoSomething()
Dim objWorksheetProtector as WorksheetProtector
Set objWorksheetProtector = New WorksheetProtector
objWorksheetProtector.Unprotect myWorksheet, myPassword
... manipulate myWorksheet - may raise an error
End Sub
```
When this Sub exits, objWorksheetProtector goes out of scope, and the worksheet is protected again. |
118,884 | <p>I have noticed that some browsers (in particular, Firefox and <a href="https://en.wikipedia.org/wiki/Opera_%28web_browser%29" rel="noreferrer">Opera</a>) are very zealous in using cached copies of <strong>.css</strong> and <strong>.js</strong> files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keeps on using the cached copy.</p>
<p>What is the most elegant way of forcing the user's browser to reload the file when it has changed?</p>
<p>Ideally, the solution would not force the browser to reload the file on every visit to the page.</p>
<hr/>
<p>I have found <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118921#118921">John Millikin's</a> and <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118901#118901">da5id's</a> suggestion to be useful. It turns out there is a term for this: <strong>auto-versioning</strong>.</p>
<p>I have posted a new answer below which is a combination of my original solution and John's suggestion.</p>
<p>Another idea that was suggested by <strong>SCdF</strong> would be to append a bogus query string to the file. (Some Python code, to automatically use the timestamp as a bogus query string, was <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/121143#121143">submitted by <em>pi.</em></a>.)</p>
<p>However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.)</p>
| [
{
"answer_id": 118886,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 9,
"selected": false,
"text": "<p>This solution is written in PHP, but it should be easily adapted to other languages.</p>\n<p>The original <code>.htaccess</code> regex can cause problems with files like <code>json-1.3.js</code>. The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)</p>\n<p>First, we use the following rewrite rule in .htaccess:</p>\n<pre><code>RewriteEngine on\nRewriteRule ^(.*)\\.[\\d]{10}\\.(css|js)$ $1.$2 [L]\n</code></pre>\n<p>Now, we write the following PHP function:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Given a file, i.e. /css/base.css, replaces it with a string containing the\n * file's mtime, i.e. /css/base.1221534296.css.\n *\n * @param $file The file to be loaded. Must be an absolute path (i.e.\n * starting with slash).\n */\nfunction auto_version($file)\n{\n if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))\n return $file;\n\n $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);\n return preg_replace('{\\\\.([^./]+)$}', ".$mtime.\\$1", $file);\n}\n</code></pre>\n<p>Now, wherever you include your CSS, change it from this:</p>\n<pre class=\"lang-html prettyprint-override\"><code><link rel="stylesheet" href="/css/base.css" type="text/css" />\n</code></pre>\n<p>To this:</p>\n<pre><code><link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />\n</code></pre>\n<p>This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.</p>\n<p>This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.</p>\n"
},
{
"answer_id": 118902,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 6,
"selected": false,
"text": "<p>You can just put <code>?foo=1234</code> at the end of your CSS / JavaScript import, changing 1234 to be whatever you like. Have a look at the Stack Overflow HTML source for an example.</p>\n<p>The idea there being that the <code>?</code> parameters are discarded / ignored on the request anyway and you can change that number when you roll out a new version.</p>\n<hr />\n<p><strong>Note:</strong> There is some argument with regard to exactly how this affects caching. I believe the general gist of it is that <a href=\"https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods\" rel=\"nofollow noreferrer\">GET</a> requests, with or without parameters <em>should</em> be cachable, so the above solution should work.</p>\n<p>However, it is down to both the web server to decide if it wants to adhere to that part of the spec and the browser the user uses, as it can just go right ahead and ask for a fresh version anyway.</p>\n"
},
{
"answer_id": 118921,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p>I've heard this called "auto versioning". The most common method is to include the static file's modification time somewhere in the URL, and strip it out using rewrite handlers or URL configurations:</p>\n<p>See also:</p>\n<ul>\n<li><a href=\"http://muffinresearch.co.uk/archives/2008/04/08/automatic-asset-versioning-in-django/\" rel=\"nofollow noreferrer\">Automatic asset versioning in Django</a></li>\n<li><a href=\"http://particletree.com/notebook/automatically-version-your-css-and-javascript-files/\" rel=\"nofollow noreferrer\">Automatically Version Your CSS and JavaScript Files</a></li>\n</ul>\n"
},
{
"answer_id": 118930,
"author": "helios",
"author_id": 9686,
"author_profile": "https://Stackoverflow.com/users/9686",
"pm_score": 3,
"selected": false,
"text": "<p>You can force a "session-wide caching" if you add the session-id as a spurious parameter of the JavaScript/CSS file:</p>\n<pre><code><link rel="stylesheet" src="myStyles.css?ABCDEF12345sessionID" />\n<script language="javascript" src="myCode.js?ABCDEF12345sessionID"></script>\n</code></pre>\n<p>If you want a version-wide caching, you could add some code to print the file date or similar. If you're using Java you can use a custom-tag to generate the link in an elegant way.</p>\n<pre><code><link rel="stylesheet" src="myStyles.css?20080922_1020" />\n<script language="javascript" src="myCode.js?20080922_1120"></script>\n</code></pre>\n"
},
{
"answer_id": 119056,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 8,
"selected": false,
"text": "<h3>Simple Client-side Technique</h3>\n<p>In general, caching is good... So there are a couple of techniques, depending on whether you're fixing the problem for yourself as you develop a website, or whether you're trying to control cache in a production environment.</p>\n<p>General visitors to your website won't have the same experience that you're having when you're developing the site. Since the average visitor comes to the site less frequently (maybe only a few times each month, unless you're a Google or hi5 Networks), then they are less likely to have your files in cache, and that may be enough.</p>\n<p>If you want to force a new version into the browser, you can always add a query string to the request, and bump up the version number when you make major changes:</p>\n<pre><code><script src="/myJavascript.js?version=4"></script>\n</code></pre>\n<p>This will ensure that everyone gets the new file. It works because the browser looks at the URL of the file to determine whether it has a copy in cache. If your server isn't set up to do anything with the query string, it will be ignored, but the name will look like a new file to the browser.</p>\n<p>On the other hand, if you're developing a website, you don't want to change the version number every time you save a change to your development version. That would be tedious.</p>\n<p>So while you're developing your site, a good trick would be to automatically generate a query string parameter:</p>\n<pre><code><!-- Development version: -->\n<script>document.write('<script src="/myJavascript.js?dev=' + Math.floor(Math.random() * 100) + '"\\><\\/script>');</script>\n</code></pre>\n<p>Adding a query string to the request is a good way to version a resource, but for a simple website this may be unnecessary. And remember, caching is a good thing.</p>\n<p>It's also worth noting that the browser isn't necessarily stingy about keeping files in cache. Browsers have policies for this sort of thing, and they are usually playing by the rules laid down in the HTTP specification. When a browser makes a request to a server, part of the response is an <a href=\"https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Standard_response_fields\" rel=\"noreferrer\">Expires</a> header... a date which tells the browser how long it should be kept in cache. The next time the browser comes across a request for the same file, it sees that it has a copy in cache and looks to the <em>Expires</em> date to decide whether it should be used.</p>\n<p>So believe it or not, it's actually your server that is making that browser cache so persistent. You could adjust your server settings and change the <em>Expires</em> headers, but the little technique I've written above is probably a much simpler way for you to go about it. Since caching is good, you usually want to set that date far into the future (a "Far-future Expires Header"), and use the technique described above to force a change.</p>\n<p>If you're interested in more information on HTTP or how these requests are made, a good book is "High Performance Web Sites" by Steve Souders. It's a very good introduction to the subject.</p>\n"
},
{
"answer_id": 119319,
"author": "pcorcoran",
"author_id": 15992,
"author_profile": "https://Stackoverflow.com/users/15992",
"pm_score": -1,
"selected": false,
"text": "<p>Changing the filename will work. But that's not usually the simplest solution.</p>\n\n<p>An HTTP cache-control header of 'no-cache' doesn't always work, as you've noticed. The HTTP 1.1 spec allows wiggle-room for user-agents to decide whether or not to request a new copy. (It's non-intuitive if you just look at the names of the directives. Go read the actual <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9\" rel=\"nofollow noreferrer\">HTTP 1.1 spec for cache</a>... it makes a little more sense in context.)</p>\n\n<p>In a nutshell, if you want iron-tight cache-control use</p>\n\n<pre><code>Cache-Control: no-cache, no-store, must-revalidate\n</code></pre>\n\n<p>in your response headers.</p>\n"
},
{
"answer_id": 119326,
"author": "airrob",
"author_id": 1513,
"author_profile": "https://Stackoverflow.com/users/1513",
"pm_score": 4,
"selected": false,
"text": "<p>Don’t use <code>foo.css?version=1</code>!</p>\n<p>Browsers aren't supposed to cache URLs with GET variables. According to <a href=\"http://www.thinkvitamin.com/features/webapps/serving-javascript-fast\" rel=\"nofollow noreferrer\">http://www.thinkvitamin.com/features/webapps/serving-javascript-fast</a>, though Internet Explorer and Firefox ignore this, <a href=\"https://en.wikipedia.org/wiki/Opera_%28web_browser%29\" rel=\"nofollow noreferrer\">Opera</a> and <a href=\"https://en.wikipedia.org/wiki/Safari_%28web_browser%29\" rel=\"nofollow noreferrer\">Safari</a> don't! Instead, use <em>foo.v1234.css</em>, and use rewrite rules to strip out the version number.</p>\n"
},
{
"answer_id": 120960,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 7,
"selected": false,
"text": "<p>Instead of changing the version manually, I would recommend you use an MD5 hash of the actual CSS file.</p>\n\n<p>So your URL would be something like</p>\n\n<pre><code>http://mysite.com/css/[md5_hash_here]/style.css\n</code></pre>\n\n<p>You could still use the rewrite rule to strip out the hash, but the advantage is that now you can set your cache policy to \"cache forever\", since if the URL is the same, that means that the file is unchanged.</p>\n\n<p>You can then write a simple shell script that would compute the hash of the file and update your tag (you'd probably want to move it to a separate file for inclusion).</p>\n\n<p>Simply run that script every time CSS changes and you're good. The browser will ONLY reload your files when they are altered. If you make an edit and then undo it, there's no pain in figuring out which version you need to return to in order for your visitors not to re-download.</p>\n"
},
{
"answer_id": 121143,
"author": "pi.",
"author_id": 15274,
"author_profile": "https://Stackoverflow.com/users/15274",
"pm_score": 3,
"selected": false,
"text": "<p>I recently solved this using Python. Here is the code (it should be easy to adopt to other languages):</p>\n<pre class=\"lang-python prettyprint-override\"><code>def import_tag(pattern, name, **kw):\n if name[0] == "/":\n name = name[1:]\n # Additional HTML attributes\n attrs = ' '.join(['%s="%s"' % item for item in kw.items()])\n try:\n # Get the files modification time\n mtime = os.stat(os.path.join('/documentroot', name)).st_mtime\n include = "%s?%d" % (name, mtime)\n # This is the same as sprintf(pattern, attrs, include) in other\n # languages\n return pattern % (attrs, include)\n except:\n # In case of error return the include without the added query\n # parameter.\n return pattern % (attrs, name)\n\ndef script(name, **kw):\n return import_tag('<script %s src="/%s"></script>', name, **kw)\n\ndef stylesheet(name, **kw):\n return import_tag('<link rel="stylesheet" type="text/css" %s href="/%s">', name, **kw)\n</code></pre>\n<p>This code basically appends the files time-stamp as a query parameter to the URL. The call of the following function</p>\n<pre><code>script("/main.css")\n</code></pre>\n<p>will result in</p>\n<pre><code><link rel="stylesheet" type="text/css" href="/main.css?1221842734">\n</code></pre>\n<p>The advantage of course is that you do never have to change your HTML content again, touching the CSS file will automatically trigger a cache invalidation. It works very well and the overhead is not noticeable.</p>\n"
},
{
"answer_id": 126086,
"author": "Walter Rumsby",
"author_id": 1654,
"author_profile": "https://Stackoverflow.com/users/1654",
"pm_score": 3,
"selected": false,
"text": "<p>Say you have a file available at:</p>\n<pre><code>/styles/screen.css\n</code></pre>\n<p>You can either append a query parameter with version information onto the URI, e.g.:</p>\n<pre><code>/styles/screen.css?v=1234\n</code></pre>\n<p>Or you can prepend version information, e.g.:</p>\n<pre><code>/v/1234/styles/screen.css\n</code></pre>\n<p>IMHO, the second method is better for CSS files, because they can refer to images using relative URLs which means that if you specify a <code>background-image</code> like so:</p>\n<pre><code>body {\n background-image: url('images/happy.gif');\n}\n</code></pre>\n<p>Its URL will effectively be:</p>\n<pre><code>/v/1234/styles/images/happy.gif\n</code></pre>\n<p>This means that if you update the version number used, the server will treat this as a new resource and not use a cached version. If you base your version number on the <a href=\"https://en.wikipedia.org/wiki/Apache_Subversion\" rel=\"nofollow noreferrer\">Subversion</a>, <a href=\"https://en.wikipedia.org/wiki/Concurrent_Versions_System\" rel=\"nofollow noreferrer\">CVS</a>, etc. revision this means that changes to images referenced in CSS files will be noticed. That isn't guaranteed with the first scheme, i.e. the URL <code>images/happy.gif</code> relative to <code>/styles/screen.css?v=1235</code> is <code>/styles/images/happy.gif</code> which doesn't contain any version information.</p>\n<p>I have implemented a caching solution using this technique with Java servlets and simply handle requests to <code>/v/*</code> with a servlet that delegates to the underlying resource (i.e. <code>/styles/screen.css</code>). In development mode I set caching headers that tell the client to always check the freshness of the resource with the server (this typically results in a 304 if you delegate to Tomcat's <code>DefaultServlet</code> and the <code>.css</code>, <code>.js</code>, etc. file hasn't changed) while in deployment mode I set headers that say "cache forever".</p>\n"
},
{
"answer_id": 126632,
"author": "Dan Burzo",
"author_id": 21613,
"author_profile": "https://Stackoverflow.com/users/21613",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest implementing the following process:</p>\n<ul>\n<li><p>version your CSS and JavaScript files whenever you deploy. Something like: screen.1233.css (the number can be your SVN revision if you use a versioning system)</p>\n</li>\n<li><p>minify them to optimize loading times</p>\n</li>\n</ul>\n"
},
{
"answer_id": 129545,
"author": "roundcrisis",
"author_id": 162325,
"author_profile": "https://Stackoverflow.com/users/162325",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using <a href=\"https://en.wikipedia.org/wiki/JQuery\" rel=\"nofollow noreferrer\">jQuery</a>, there is an option called cache that will append a random number.</p>\n<p>This is not a complete answer I know, but it might save you some time.</p>\n"
},
{
"answer_id": 131037,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 0,
"selected": false,
"text": "<p>My method to do this is simply to have the link element into a server-side include:</p>\n\n<pre><code><!--#include virtual=\"/includes/css-element.txt\"-->\n</code></pre>\n\n<p>where the contents of css-element.txt is</p>\n\n<pre><code><link rel=\"stylesheet\" href=\"mycss.css\"/>\n</code></pre>\n\n<p>so the day you want to link to my-new-css.css or whatever, you just change the include.</p>\n"
},
{
"answer_id": 1041463,
"author": "Michiel",
"author_id": 125699,
"author_profile": "https://Stackoverflow.com/users/125699",
"pm_score": 4,
"selected": false,
"text": "<p>Interesting post. Having read all the answers here combined with the fact that I have never had any problems with "bogus" query strings (which I am unsure why everyone is so reluctant to use this) I guess the solution (which removes the need for Apache rewrite rules as in the accepted answer) is to compute a short <em>hash</em> of the CSS file contents (instead of the file datetime) as a bogus querystring.</p>\n<p>This would result in the following:</p>\n<pre><code><link rel="stylesheet" href="/css/base.css?[hash-here]" type="text/css" />\n</code></pre>\n<p>Of course, the datetime solutions also get the job done in the case of editing a CSS file, but I think it is about the CSS file content and not about the file datetime, so why get these mixed up?</p>\n"
},
{
"answer_id": 3417141,
"author": "Nick Johnson",
"author_id": 227569,
"author_profile": "https://Stackoverflow.com/users/227569",
"pm_score": 4,
"selected": false,
"text": "<p>The RewriteRule needs a small update for JavaScript or CSS files that contain a dot notation versioning at the end. E.g., <em>json-1.3.js</em>.</p>\n<p>I added a dot negation class [^.] to the regex, so .number. is ignored.</p>\n<pre><code>RewriteRule ^(.*)\\.[^.][\\d]+\\.(css|js)$ $1.$2 [L]\n</code></pre>\n"
},
{
"answer_id": 4622905,
"author": "lony",
"author_id": 227821,
"author_profile": "https://Stackoverflow.com/users/227821",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks to <a href=\"https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-js-files/118886#118886\">Kip for his perfect solution</a>!</p>\n<p>I extended it to use it as an Zend_view_Helper. Because my client run his page on a virtual host I also extended it for that.</p>\n<pre><code>/**\n * Extend filepath with timestamp to force browser to\n * automatically refresh them if they are updated\n *\n * This is based on Kip's version, but now\n * also works on virtual hosts\n * @link http://stackoverflow.com/questions/118884/what-is-an-elegant-way-to-force-browsers-to-reload-cached-css-js-files\n *\n * Usage:\n * - extend your .htaccess file with\n * # Route for My_View_Helper_AutoRefreshRewriter\n * # which extends files with there timestamp so if these\n * # are updated a automatic refresh should occur\n * # RewriteRule ^(.*)\\.[^.][\\d]+\\.(css|js)$ $1.$2 [L]\n * - then use it in your view script like\n * $this->headLink()->appendStylesheet( $this->autoRefreshRewriter($this->cssPath . 'default.css'));\n *\n */\nclass My_View_Helper_AutoRefreshRewriter extends Zend_View_Helper_Abstract {\n\n public function autoRefreshRewriter($filePath) {\n\n if (strpos($filePath, '/') !== 0) {\n\n // Path has no leading '/'\n return $filePath;\n } elseif (file_exists($_SERVER['DOCUMENT_ROOT'] . $filePath)) {\n\n // File exists under normal path\n // so build path based on this\n $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $filePath);\n return preg_replace('{\\\\.([^./]+)$}', ".$mtime.\\$1", $filePath);\n } else {\n\n // Fetch directory of index.php file (file from all others are included)\n // and get only the directory\n $indexFilePath = dirname(current(get_included_files()));\n\n // Check if file exist relativ to index file\n if (file_exists($indexFilePath . $filePath)) {\n\n // Get timestamp based on this relativ path\n $mtime = filemtime($indexFilePath . $filePath);\n\n // Write generated timestamp to path\n // but use old path not the relativ one\n return preg_replace('{\\\\.([^./]+)$}', ".$mtime.\\$1", $filePath);\n } else {\n return $filePath;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5588394,
"author": "Leopd",
"author_id": 303056,
"author_profile": "https://Stackoverflow.com/users/303056",
"pm_score": 7,
"selected": false,
"text": "<p>Google's <a href=\"http://code.google.com/p/modpagespeed/\" rel=\"nofollow noreferrer\">mod_pagespeed</a> plugin for <a href=\"https://en.wikipedia.org/wiki/Apache_HTTP_Server\" rel=\"nofollow noreferrer\">Apache</a> will do auto-versioning for you. It's really slick.</p>\n<p>It parses HTML on its way out of the webserver (works with PHP, <a href=\"https://en.wikipedia.org/wiki/Ruby_on_Rails\" rel=\"nofollow noreferrer\">Ruby on Rails</a>, Python, static HTML -- anything) and rewrites links to CSS, JavaScript, image files so they include an id code. It serves up the files at the modified URLs with a very long cache control on them. When the files change, it automatically changes the URLs so the browser has to re-fetch them. It basically just works, without any changes to your code. It'll even minify your code on the way out too.</p>\n"
},
{
"answer_id": 6440080,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "<p>I put an MD5 hash of the file's contents in its URL. That way I can set a very long expiration date, and don't have to worry about users having old JS or CSS.</p>\n<p>I also calculate this once per file at runtime (or on file system changes) so there's nothing funny to do at design time or during the build process.</p>\n<p>If you're using ASP.NET MVC then you can check out the code <a href=\"https://stackoverflow.com/questions/936626/how-can-i-force-a-hard-refresh-ctrlf5/6439351#6439351\">in my other answer here</a>.</p>\n"
},
{
"answer_id": 7999354,
"author": "A Programmer",
"author_id": 1028240,
"author_profile": "https://Stackoverflow.com/users/1028240",
"pm_score": -1,
"selected": false,
"text": "<p>The simplest method is to take advantage of the PHP file read functionality. Just have the PHP echo the contents of the file into tags.</p>\n\n<pre><code><?php\n//Replace the 'style.css' with the link to the stylesheet.\necho \"<style type='text/css'>\".file_get_contents('style.css').\"</style>\";\n?>\n</code></pre>\n\n<p>If you're using something besides PHP, there are some variations depending on the language, but almost all languages have a way to print the contents of a file. Put it in the right location (in the section), and that way, you don't have to rely on the browser.</p>\n"
},
{
"answer_id": 11355226,
"author": "Tai Li",
"author_id": 774863,
"author_profile": "https://Stackoverflow.com/users/774863",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/35440/toma\">TomA's answer</a> is right.</p>\n<p>Using the "querystring" method will not be cached as quoted by <a href=\"http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/\" rel=\"nofollow noreferrer\">Steve Souders</a> below:</p>\n<blockquote>\n<p>...that Squid, a popular proxy, doesn’t cache resources with a\nquerystring.</p>\n</blockquote>\n<p><a href=\"https://stackoverflow.com/users/35440/toma\">TomA's suggestion</a> of using style.TIMESTAMP.css is good, but MD5 would be much better as only when the contents were genuinely changed, the MD5 changes as well.</p>\n"
},
{
"answer_id": 14383167,
"author": "ThomasH",
"author_id": 127465,
"author_profile": "https://Stackoverflow.com/users/127465",
"pm_score": 2,
"selected": false,
"text": "<p>I see a problem with the approach of using a timestamp- or hash-based differentiator in the resource URL which gets stripped out on request at the server. The page that contains the link to e.g. the style sheet <em>might get cached as well</em>. So the cached page might request an older version of the style sheet, but it will be served the latest version, which might or might not work with the requesting page.</p>\n<p>To fix this, you either have to guard the requesting page with a <code>no-cache</code> header or meta, to make sure it gets refreshed on every load. Or you have to maintain <em>all versions</em> of the style file that you ever deployed on the server, each as an individual file and with their differentiator intact so that the requesting page can get at the version of the style file it was designed for. In the latter case, you basically tie the versions of the HTML page and the style sheet together, which can be done statically and doesn't require any server logic.</p>\n"
},
{
"answer_id": 14536240,
"author": "Phantom007",
"author_id": 468975,
"author_profile": "https://Stackoverflow.com/users/468975",
"pm_score": 7,
"selected": false,
"text": "<p>I am not sure why you guys/gals are taking so much pain to implement this solution.</p>\n<p>All you need to do if get the file's modified timestamp and append it as a querystring to the file.</p>\n<p>In PHP I would do it as:</p>\n<pre><code><link href="mycss.css?v=<?= filemtime('mycss.css') ?>" rel="stylesheet">\n</code></pre>\n<p><em>filemtime()</em> is a PHP function that returns the file modified timestamp.</p>\n"
},
{
"answer_id": 15704646,
"author": "Scott Arciszewski",
"author_id": 2224584,
"author_profile": "https://Stackoverflow.com/users/2224584",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<p>"Another idea which was suggested by SCdF would be to append a bogus query string to the file. (Some Python code to automatically use the timestamp as a bogus query string was submitted by pi.) However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.) Since it is not clear what happens with a bogus query string, I am not accepting that answer."</p>\n</blockquote>\n<pre><code><link rel="stylesheet" href="file.css?<?=hash_hmac('sha1', session_id(), md5_file("file.css")); ?>" />\n</code></pre>\n<p>Hashing the file means when it has changed, the query string will have changed. If it hasn't, it will remain the same. Each session forces a reload too.</p>\n<p>Optionally, you can also use rewrites to cause the browser to think it's a new <a href=\"https://en.wikipedia.org/wiki/Uniform_Resource_Identifier\" rel=\"nofollow noreferrer\">URI</a>.</p>\n"
},
{
"answer_id": 17043892,
"author": "holmis83",
"author_id": 1463522,
"author_profile": "https://Stackoverflow.com/users/1463522",
"pm_score": 2,
"selected": false,
"text": "<p>For a <a href=\"https://en.wikipedia.org/wiki/Jakarta_Servlet\" rel=\"nofollow noreferrer\">Java Servlet</a> environment, you can look at the <a href=\"https://jawr.java.net/\" rel=\"nofollow noreferrer\">Jawr library</a>. The features page explains how it handles caching:</p>\n<blockquote>\n<p>Jawr will try its best to force your clients to cache the resources. If a browser asks if a file changed, a 304 (not modified) header is sent back with no content. On the other hand, with Jawr you will be 100% sure that new versions of your bundles are downloaded by all clients. Every URL to your resources will include an automatically generated, content-based prefix that changes automatically whenever a resource is updated. Once you deploy a new version, the URL to the bundle will change as well so it will be impossible that a client uses an older, cached version.</p>\n</blockquote>\n<p>The library also does JavaScript and CSS minification, but you can turn that off if you don't want it.</p>\n"
},
{
"answer_id": 17467422,
"author": "Ponmudi VN",
"author_id": 2186642,
"author_profile": "https://Stackoverflow.com/users/2186642",
"pm_score": 3,
"selected": false,
"text": "<p>You could simply add some random number with the CSS and JavaScript URL like</p>\n<pre><code>example.css?randomNo = Math.random()\n</code></pre>\n"
},
{
"answer_id": 18033374,
"author": "Ivan Kochurkin",
"author_id": 1046374,
"author_profile": "https://Stackoverflow.com/users/1046374",
"pm_score": 3,
"selected": false,
"text": "<p>For ASP.NET I propose the following solution with advanced options (debug/release mode, versions):</p>\n<p>Include JavaScript or CSS files this way:</p>\n<pre><code><script type="text/javascript" src="Scripts/exampleScript<%=Global.JsPostfix%>" />\n<link rel="stylesheet" type="text/css" href="Css/exampleCss<%=Global.CssPostfix%>" />\n</code></pre>\n<p><em>Global.JsPostfix</em> and <em>Global.CssPostfix</em> are calculated by the following way in <em>Global.asax</em>:</p>\n<pre><code>protected void Application_Start(object sender, EventArgs e)\n{\n ...\n string jsVersion = ConfigurationManager.AppSettings["JsVersion"];\n bool updateEveryAppStart = Convert.ToBoolean(ConfigurationManager.AppSettings["UpdateJsEveryAppStart"]);\n int buildNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Revision;\n JsPostfix = "";\n#if !DEBUG\n JsPostfix += ".min";\n#endif\n JsPostfix += ".js?" + jsVersion + "_" + buildNumber;\n if (updateEveryAppStart)\n {\n Random rand = new Random();\n JsPosfix += "_" + rand.Next();\n }\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 21614688,
"author": "Alex White",
"author_id": 1721440,
"author_profile": "https://Stackoverflow.com/users/1721440",
"pm_score": -1,
"selected": false,
"text": "<p>Another way for JavaScript files would be to use the jQuery <code>$.getScript</code> in conjunction with <code>$.ajaxSetup</code> option <code>cache: false</code>.</p>\n<p>Instead of:</p>\n<pre><code><script src="scripts/app.js"></script>\n</code></pre>\n<p>You can use:</p>\n<pre><code>$.ajaxSetup({\n cache: false\n});\n\n$.getScript('scripts/app.js'); // GET scripts/app.js?_1391722802668\n</code></pre>\n"
},
{
"answer_id": 25265359,
"author": "Amarnath Bakthavathsalam",
"author_id": 2008645,
"author_profile": "https://Stackoverflow.com/users/2008645",
"pm_score": 1,
"selected": false,
"text": "<p>Another suggestion for ASP.NET websites,</p>\n<ol>\n<li><p>Set different <code>cache-control:max-age</code> values, for different static files.</p>\n</li>\n<li><p>For CSS and JavaScript files, the chances of modifying these files on server is high, so set a minimal <em>cache-control:max-age</em> value of 1 or 2 minutes or something that meets your need.</p>\n</li>\n<li><p>For images, set a far date as the <em>cache-control:max-age</em> value, say 360 days.</p>\n</li>\n<li><p>By doing so, when we make the first request, all static contents are downloaded to client machine with a <em>200-OK</em> response.</p>\n</li>\n<li><p>On subsequent requests and after two minutes, we see <em>304-Not Modified</em> requests on CSS and JavaScript files which avoids us from CSS and JavaScript versioning.</p>\n</li>\n<li><p>Image files will not be requested as they will be used from cached memory till the cache expires.</p>\n</li>\n<li><p>By using the below <em>web.config</em> configurations, we can achieve the above described behavior,</p>\n<pre class=\"lang-xml prettyprint-override\"><code><system.webServer>\n <modules runAllManagedModulesForAllRequests="true"/>\n <staticContent>\n <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00.00:01:00"/>\n </staticContent>\n <httpProtocol>\n <customHeaders>\n <add name="ETAG" value=""/>\n </customHeaders>\n </httpProtocol>\n</system.webServer>\n\n<location path="Images">\n <system.webServer>\n <staticContent>\n <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="180.00:00:00" />\n </staticContent>\n </system.webServer>\n</location>\n</code></pre>\n</li>\n</ol>\n"
},
{
"answer_id": 25872382,
"author": "Jos",
"author_id": 1138266,
"author_profile": "https://Stackoverflow.com/users/1138266",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using a modern browser, you could use a manifest file to inform the browsers which files need to be updated. This requires no headers, no versions in URLs, etc.</p>\n<p>For more details, see:\n<em><a href=\"https://developer.mozilla.org/nl/docs/Web/HTML/Applicatie_cache_gebruiken#Introduction\" rel=\"nofollow noreferrer\">Using the application cache</a></em></p>\n"
},
{
"answer_id": 26129241,
"author": "user3738893",
"author_id": 3738893,
"author_profile": "https://Stackoverflow.com/users/3738893",
"pm_score": 4,
"selected": false,
"text": "<p>For ASP.NET 4.5 and greater you can use <a href=\"http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification\" rel=\"nofollow noreferrer\">script bundling</a>.</p>\n<blockquote>\n<p>The request <code>http://localhost/MvcBM_time/bundles/AllMyScripts?v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81</code> is for the bundle AllMyScripts and contains a query string pair v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81. The query string <code>v</code> has a value token that is a unique identifier used for caching. As long as the bundle doesn't change, the ASP.NET application will request the AllMyScripts bundle using this token. If any file in the bundle changes, the ASP.NET optimization framework will generate a new token, guaranteeing that browser requests for the bundle will get the latest bundle.</p>\n</blockquote>\n<p>There are other benefits to bundling, including increased performance on first-time page loads with minification.</p>\n"
},
{
"answer_id": 27451135,
"author": "undefined",
"author_id": 610585,
"author_profile": "https://Stackoverflow.com/users/610585",
"pm_score": 1,
"selected": false,
"text": "<p>Many answers here advocate adding a timestamp to the URL. Unless you are modifying your production files directly, the file's timestamp is not likely to reflect the time when a file was changed. In most cases this will cause the URL to change more frequently than the file itself. This is why you should use a fast hash of the file's contents such as <a href=\"https://en.wikipedia.org/wiki/MD5\" rel=\"nofollow noreferrer\">MD5</a> as <a href=\"https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/120960#120960\">levik and others</a> have suggested.</p>\n<p>Keep in mind that the value should be calculated once at build or run, rather than each time the file is requested.</p>\n<p>As an example, here's a simple bash script that reads a list of filenames from <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)\" rel=\"nofollow noreferrer\">standard input</a> and writes a JSON file containing hashes to standard output:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>#!/bin/bash\n# Create a JSON map from filenames to MD5 hashes\n# Run as hashes.sh < inputfile.list > outputfile.json\n\necho "{"\ndelim=""\nwhile read l; do\n echo "$delim\\"$l\\": \\"`md5 -q $l`\\""\n delim=","\ndone\necho "}"\n</code></pre>\n<p>This file could then be loaded at server startup and referenced instead of reading the file system.</p>\n"
},
{
"answer_id": 27924764,
"author": "Lloyd Banks",
"author_id": 1423787,
"author_profile": "https://Stackoverflow.com/users/1423787",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a pure JavaScript solution</p>\n<pre><code>(function(){\n\n // Match this timestamp with the release of your code\n var lastVersioning = Date.UTC(2014, 11, 20, 2, 15, 10);\n \n var lastCacheDateTime = localStorage.getItem('lastCacheDatetime');\n\n if(lastCacheDateTime){\n if(lastVersioning > lastCacheDateTime){\n var reload = true;\n }\n }\n\n localStorage.setItem('lastCacheDatetime', Date.now());\n\n if(reload){\n location.reload(true);\n }\n\n})();\n</code></pre>\n<p>The above will look for the last time the user visited your site. If the last visit was before you released new code, it uses <code>location.reload(true)</code> to force page refresh from server.</p>\n<p>I usually have this as the very first script within the <code><head></code> so it's evaluated before any other content loads. If a reload needs to occurs, it's hardly noticeable to the user.</p>\n<p>I am using local storage to store the last visit timestamp on the browser, but you can add cookies to the mix if you're looking to support older versions of IE.</p>\n"
},
{
"answer_id": 31525382,
"author": "pinkp",
"author_id": 2409791,
"author_profile": "https://Stackoverflow.com/users/2409791",
"pm_score": 2,
"selected": false,
"text": "<p>A <a href=\"http://www.silverstripe.org\" rel=\"nofollow noreferrer\">SilverStripe</a>-specific answer worked out from reading: <a href=\"http://api.silverstripe.org/3.0/source-class-SS_Datetime.html#98-110\" rel=\"nofollow noreferrer\">http://api.silverstripe.org/3.0/source-class-SS_Datetime.html#98-110</a>:</p>\n<p>Hopefully this will help someone using a SilverStripe template and trying to force reload a cached image on each page visit / refresh. In my case it is a GIF animation which only plays once and therefore did not replay after it was cached. In my template I simply added:</p>\n<pre><code>?$Now.Format(dmYHis)\n</code></pre>\n<p>to the end of the file path to create a unique time stamp and to force the browser to treat it as a new file.</p>\n"
},
{
"answer_id": 31618120,
"author": "Frank Bryce",
"author_id": 3960399,
"author_profile": "https://Stackoverflow.com/users/3960399",
"pm_score": 3,
"selected": false,
"text": "<p>For my development, I find that Chrome has a great solution.</p>\n<p><a href=\"https://superuser.com/a/512833\">https://superuser.com/a/512833</a></p>\n<p>With developer tools open, simply long click the refresh button and let go once you hover over "Empty Cache and Hard Reload".</p>\n<p>This is my best friend, and is a super lightweight way to get what you want!</p>\n"
},
{
"answer_id": 31795900,
"author": "Michael Kropat",
"author_id": 27581,
"author_profile": "https://Stackoverflow.com/users/27581",
"pm_score": 5,
"selected": false,
"text": "<p>The 30 or so existing answers are great advice for a circa 2008 website. However, when it comes to a modern, <strong><a href=\"https://en.wikipedia.org/wiki/Single-page_application\" rel=\"noreferrer\">single-page application</a></strong> (SPA), it might be time to rethink some fundamental assumptions… specifically the idea that it is desirable for the web server to serve only the single, most recent version of a file.</p>\n<p>Imagine you're a user that has version <em>M</em> of a SPA loaded into your browser:</p>\n<ol>\n<li>Your <a href=\"https://en.wikipedia.org/wiki/Continuous_delivery\" rel=\"noreferrer\">CD</a> pipeline deploys the new version <em>N</em> of the application onto the server</li>\n<li>You navigate within the SPA, which sends an <a href=\"https://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"noreferrer\">XMLHttpRequest</a> (XHR) to the server to get <code>/some.template</code></li>\n</ol>\n<ul>\n<li>(Your browser hasn't refreshed the page, so you're still running version <em>M</em>)</li>\n</ul>\n<ol>\n<li>The server responds with the contents of <code>/some.template</code> — do you want it to return version <em>M</em> or <em>N</em> of the template?</li>\n</ol>\n<p>If the format of <code>/some.template</code> changed between versions <em>M</em> and <em>N</em> (or the file was renamed or whatever) <strong>you probably don't want version <em>N</em> of the template sent to the browser that's running the old version <em>M</em> of the parser</strong>.†</p>\n<p>Web applications run into this issue when two conditions are met:</p>\n<ul>\n<li>Resources are requested asynchronously some time after the initial page load</li>\n<li>The application logic assumes things (that may change in future versions) about resource content</li>\n</ul>\n<p>Once your application needs to serve up multiple versions in parallel, <strong>solving caching and "reloading" becomes trivial:</strong></p>\n<ol>\n<li>Install all site files into versioned directories: <code>/v<release_tag_1>/…files…</code>, <code>/v<release_tag_2>/…files…</code></li>\n<li>Set HTTP headers to let browsers cache files forever</li>\n</ol>\n<ul>\n<li>(Or better yet, put everything in a CDN)</li>\n</ul>\n<ol>\n<li>Update all <code><script></code> and <code><link></code> tags, etc. to point to that file in one of the versioned directories</li>\n</ol>\n<p>That last step sounds tricky, as it could require calling a URL builder for every URL in your server-side or client-side code. Or you could just make clever use of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base\" rel=\"noreferrer\"><code><base></code> tag</a> and change the current version in one place.</p>\n<p>† One way around this is to be aggressive about forcing the browser to reload everything when a new version is released. But for the sake of letting any in-progress operations to complete, it may still be easiest to support at least two versions in parallel: v-current and v-previous.</p>\n"
},
{
"answer_id": 37181172,
"author": "statler",
"author_id": 618660,
"author_profile": "https://Stackoverflow.com/users/618660",
"pm_score": 1,
"selected": false,
"text": "<p>I came to this question when looking for a solution for my SPA, which only has a single <em>index.html</em> file listing all the necessary files. While I got some leads that helped me, I could not find a quick-and-easy solution.</p>\n<p>In the end, I wrote a quick page (including all of the code) necessary to autoversion an HTML/JavaScript <em>index.html</em> file as part of the publishing process. It works perfectly and only updates new files based on date last modified.</p>\n<p>You can see my post at <em><a href=\"http://blueskycont.com/wp/2016/05/12/autoversion-your-spa-index-html/\" rel=\"nofollow noreferrer\">Autoversion your SPA index.html</a></em>. There is a stand-alone Windows application there too.</p>\n<p>The guts of the code is:</p>\n<pre><code>private void ParseIndex(string inFile, string addPath, string outFile)\n{\n string path = Path.GetDirectoryName(inFile);\n HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();\n document.Load(inFile);\n\n foreach (HtmlNode link in document.DocumentNode.Descendants("script"))\n {\n if (link.Attributes["src"]!=null)\n {\n resetQueryString(path, addPath, link, "src");\n }\n }\n\n foreach (HtmlNode link in document.DocumentNode.Descendants("link"))\n {\n if (link.Attributes["href"] != null && link.Attributes["type"] != null)\n {\n if (link.Attributes["type"].Value == "text/css" || link.Attributes["type"].Value == "text/html")\n {\n resetQueryString(path, addPath, link, "href");\n }\n }\n }\n\n document.Save(outFile);\n MessageBox.Show("Your file has been processed.", "Autoversion complete");\n}\n\nprivate void resetQueryString(string path, string addPath, HtmlNode link, string attrType)\n{\n string currFileName = link.Attributes[attrType].Value;\n\n string uripath = currFileName;\n if (currFileName.Contains('?'))\n uripath = currFileName.Substring(0, currFileName.IndexOf('?'));\n string baseFile = Path.Combine(path, uripath);\n if (!File.Exists(baseFile))\n baseFile = Path.Combine(addPath, uripath);\n if (!File.Exists(baseFile))\n return;\n DateTime lastModified = System.IO.File.GetLastWriteTime(baseFile);\n link.Attributes[attrType].Value = uripath + "?v=" + lastModified.ToString("yyyyMMddhhmm");\n}\n</code></pre>\n"
},
{
"answer_id": 37538586,
"author": "GreQ",
"author_id": 6331590,
"author_profile": "https://Stackoverflow.com/users/6331590",
"pm_score": 3,
"selected": false,
"text": "<p>I have not found the client-side DOM approach creating the script node (or CSS) element dynamically:</p>\n<pre><code><script>\n var node = document.createElement("script");\n node.type = "text/javascript";\n node.src = 'test.js?' + Math.floor(Math.random()*999999999);\n document.getElementsByTagName("head")[0].appendChild(node);\n</script>\n</code></pre>\n"
},
{
"answer_id": 38251122,
"author": "commonpike",
"author_id": 95733,
"author_profile": "https://Stackoverflow.com/users/95733",
"pm_score": 2,
"selected": false,
"text": "<p>It seems all answers here suggest some sort of versioning in the naming scheme, which has its downsides.</p>\n<p>Browsers should be well aware of what to cache and what not to cache by reading the web server's response, in particular the HTTP headers - for how long is this resource valid? Was this resource updated since I last retrieved it? etc.</p>\n<p>If things are configured 'correctly', just updating the files of your application should (at some point) refresh the browser's caches. You can for example configure your web server to tell the browser to never cache files (which is a bad idea).</p>\n<p>A more in-depth explanation of how that works is in <em><a href=\"https://www.mnot.net/cache_docs/#WORK\" rel=\"nofollow noreferrer\">How Web Caches Work</a></em>.</p>\n"
},
{
"answer_id": 39060477,
"author": "Mizo Games",
"author_id": 1482251,
"author_profile": "https://Stackoverflow.com/users/1482251",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I have made it work my way by changing the JavaScript file version each time the page loads by adding a random number to JavaScript file version as follows:</p>\n<pre><code>// Add it to the top of the page\n<?php\n srand();\n $random_number = rand();\n?>\n</code></pre>\n<p>Then apply the random number to the JavaScript version as follow:</p>\n<pre><code><script src="file.js?version=<?php echo $random_number;?>"></script>\n</code></pre>\n"
},
{
"answer_id": 41304784,
"author": "readikus",
"author_id": 1010468,
"author_profile": "https://Stackoverflow.com/users/1010468",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using <a href=\"https://en.wikipedia.org/wiki/Git\" rel=\"nofollow noreferrer\">Git</a> and PHP, you can reload the script from the cache each time there is a change in the Git repository, using the following code:</p>\n<pre><code>exec('git rev-parse --verify HEAD 2> /dev/null', $gitLog);\necho ' <script src="/path/to/script.js"?v='.$gitLog[0].'></script>'.PHP_EOL;\n</code></pre>\n"
},
{
"answer_id": 42576123,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "<p>In <a href=\"https://en.wikipedia.org/wiki/Laravel\" rel=\"nofollow noreferrer\">Laravel</a> (PHP) we can do it in the following clear and elegant way (using file modification timestamp):</p>\n<pre><code><script src="{{ asset('/js/your.js?v='.filemtime('js/your.js')) }}"></script>\n</code></pre>\n<p>And similar for CSS</p>\n<pre><code><link rel="stylesheet" href="{{asset('css/your.css?v='.filemtime('css/your.css'))}}">\n</code></pre>\n<p>Example HTML output (<code>filemtime</code> return time as as a <a href=\"https://www.unixtimestamp.com/index.php\" rel=\"nofollow noreferrer\">Unix timestamp</a>)</p>\n<pre><code><link rel="stylesheet" href="assets/css/your.css?v=1577772366">\n</code></pre>\n"
},
{
"answer_id": 46169589,
"author": "Karan Shaw",
"author_id": 6905379,
"author_profile": "https://Stackoverflow.com/users/6905379",
"pm_score": 3,
"selected": false,
"text": "<p>Simply add this code where you want to do a hard reload (force the browser to reload cached CSS and JavaScript files):</p>\n<pre><code>$(window).load(function() {\n location.reload(true);\n});\n</code></pre>\n<p>Do this inside the <code>.load</code>, so it does not refresh like a loop.</p>\n"
},
{
"answer_id": 46972723,
"author": "unknown123",
"author_id": 8590807,
"author_profile": "https://Stackoverflow.com/users/8590807",
"pm_score": 3,
"selected": false,
"text": "<p>Google Chrome has the <strong>Hard Reload</strong> as well as the <strong>Empty Cache and Hard Reload</strong> option. You can click and hold the reload button (in <em>Inspect Mode</em>) to select one.</p>\n"
},
{
"answer_id": 48727671,
"author": "Pawel",
"author_id": 696535,
"author_profile": "https://Stackoverflow.com/users/696535",
"pm_score": 2,
"selected": false,
"text": "<p>Disable caching of <em>script.js</em> <strong>only for local development</strong> in pure JavaScript.</p>\n<p>It injects a random <em>script.js?wizardry=1231234</em> and blocks regular <em>script.js</em>:</p>\n<pre><code><script type="text/javascript">\n if(document.location.href.indexOf('localhost') !== -1) {\n const scr = document.createElement('script');\n document.setAttribute('type', 'text/javascript');\n document.setAttribute('src', 'scripts.js' + '?wizardry=' + Math.random());\n document.head.appendChild(scr);\n document.write('<script type="application/x-suppress">'); // prevent next script(from other SO answer)\n }\n</script>\n\n<script type="text/javascript" src="scripts.js">\n</code></pre>\n"
},
{
"answer_id": 51606421,
"author": "Luis Cambustón",
"author_id": 4023929,
"author_profile": "https://Stackoverflow.com/users/4023929",
"pm_score": 2,
"selected": false,
"text": "<p>Just use server-side code to add the date of the file... that way it <em>will</em> be cached and only reloaded when the file changes.</p>\n<p>In ASP.NET:</p>\n<pre><code><link rel="stylesheet" href="~/css/custom.css?d=@(System.Text.RegularExpressions.Regex.Replace(File.GetLastWriteTime(Server.MapPath("~/css/custom.css")).ToString(),"[^0-9]", ""))" />\n\n<script type="text/javascript" src="~/js/custom.js?d=@(System.Text.RegularExpressions.Regex.Replace(File.GetLastWriteTime(Server.MapPath("~/js/custom.js")).ToString(),"[^0-9]", ""))"></script>\n</code></pre>\n<p>This can be simplified to:</p>\n<pre><code><script src="<%= Page.ResolveClientUrlUnique("~/js/custom.js") %>" type="text/javascript"></script>\n</code></pre>\n<p>By adding an extension method to your project to extend <em>Page</em>:</p>\n<pre><code>public static class Extension_Methods\n{\n public static string ResolveClientUrlUnique(this System.Web.UI.Page oPg, string sRelPath)\n {\n string sFilePath = oPg.Server.MapPath(sRelPath);\n string sLastDate = System.IO.File.GetLastWriteTime(sFilePath).ToString();\n string sDateHashed = System.Text.RegularExpressions.Regex.Replace(sLastDate, "[^0-9]", "");\n\n return oPg.ResolveClientUrl(sRelPath) + "?d=" + sDateHashed;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 52229111,
"author": "Jajikanth pydimarla",
"author_id": 4138684,
"author_profile": "https://Stackoverflow.com/users/4138684",
"pm_score": 1,
"selected": false,
"text": "<p>Small improvement from existing answers...</p>\n<p>Using a random number or session id would cause it to reload on each request. Ideally, we may need to change only if some code changes were done in any JavaScript or CSS file.</p>\n<p>When using a common JSP file as a template to many other <a href=\"https://en.wikipedia.org/wiki/JavaServer_Pages\" rel=\"nofollow noreferrer\">JSP</a> and JavaScript files, add the below in a common JSP file</p>\n<pre><code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>\n<c:set var = "version" scope = "application" value = "1.0.0" />\n</code></pre>\n<p>Now use the above variable in all locations as below in your JavaScript file inclusions.</p>\n<pre><code><script src='<spring:url value="/js/myChangedFile.js?version=${version}"/>'></script>\n</code></pre>\n<p><strong>Advantages:</strong></p>\n<blockquote>\n<ol>\n<li>This approach will help you in changing version number at one location only.</li>\n</ol>\n</blockquote>\n<blockquote>\n<ol start=\"2\">\n<li>Maintaining a proper version number (usually build/release number) will help you to check/verify your code changes being deployed properly (from developer console of the browser).</li>\n</ol>\n</blockquote>\n<p><strong>Another useful tip:</strong></p>\n<p>If you are using the Chrome browser, you can disable caching when <em>Dev Tools</em> is open.\nIn Chrome, hit <kbd>F12</kbd> → <kbd>F1</kbd> and scroll to <em>Settings</em> → <em>Preferences</em> → <em>Network</em> → *Disable caching (while <a href=\"https://developers.google.com/web/tools/chrome-devtools/\" rel=\"nofollow noreferrer\">DevTools</a> is open)</p>\n<p><a href=\"https://i.stack.imgur.com/S3Ojy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/S3Ojy.png\" alt=\"Chrome DevTools\" /></a></p>\n"
},
{
"answer_id": 52671176,
"author": "Bangash",
"author_id": 6213405,
"author_profile": "https://Stackoverflow.com/users/6213405",
"pm_score": 2,
"selected": false,
"text": "<p>One of the best and quickest approaches I know is to change the name of the folder where you have CSS or JavaScript files.</p>\n<p>Or for developers: Change the name of your CSS and JavaScript files something like versions.</p>\n<pre><code><link rel="stylesheet" href="cssfolder/somecssfile-ver-1.css"/>\n</code></pre>\n<p>Do the same for your JavaScript files.</p>\n"
},
{
"answer_id": 56141208,
"author": "Jessie Lesbian",
"author_id": 10831193,
"author_profile": "https://Stackoverflow.com/users/10831193",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"https://en.wikipedia.org/wiki/Subresource_Integrity\" rel=\"nofollow noreferrer\">SRI</a> to break the browser cache. You only have to update your <em>index.html</em> file with the new SRI hash every time. When the browser loads the HTML and finds out the SRI hash on the HTML page didn't match that of the cached version of the resource, it will reload your resource from your servers. It also comes with a good side effect of bypassing cross-origin read blocking.</p>\n<pre><code><script src="https://jessietessie.github.io/google-translate-token-generator/google_translate_token_generator.js" integrity="sha384-muTMBCWlaLhgTXLmflAEQVaaGwxYe1DYIf2fGdRkaAQeb4Usma/kqRWFWErr2BSi" crossorigin="anonymous"></script>\n</code></pre>\n"
},
{
"answer_id": 56636730,
"author": "patrick",
"author_id": 73804,
"author_profile": "https://Stackoverflow.com/users/73804",
"pm_score": 3,
"selected": false,
"text": "<p>For development: use a browser setting: for example, <code>Chrome</code> <code>network tab</code> has a <code>disable cache</code> option.</p>\n<p>For production: append a unique query parameter to the request (<em>for example</em>, <code>q?Date.now()</code>) with a server-side rendering framework or pure JavaScript code.</p>\n<pre><code>// Pure JavaScript unique query parameter generation\n//\n//=== myfile.js\n\nfunction hello() { console.log('hello') };\n\n//=== end of file\n\n<script type="text/javascript">\n document.write('<script type="text/javascript" src="myfile.js?q=' + Date.now() + '">\n // document.write is considered bad practice!\n // We can't use hello() yet\n</script>')\n\n<script type="text/javascript">\n hello();\n</script>\n</code></pre>\n"
},
{
"answer_id": 58640532,
"author": "AIon",
"author_id": 5904566,
"author_profile": "https://Stackoverflow.com/users/5904566",
"pm_score": 3,
"selected": false,
"text": "<p>For developers with this problem while developing and testing:</p>\n<p>Remove caching briefly.</p>\n<p><code>"keep caching consistent with the file"</code> .. it's way too much hassle ..</p>\n<p>Generally speaking, I don't mind loading more - even loading again files which did not change - on most projects - is practically irrelevant. While developing an application - we are mostly loading from disk, on <code>localhost:port</code> - so this <code>increase in network traffic</code> issue is <strong>not a deal breaking issue</strong>.</p>\n<p>Most small projects are just playing around - they never end-up in production. So for them you don't need anything more...</p>\n<p>As such if you use <strong>Chrome DevTools</strong>, you can follow this disable-caching approach like in the image below:</p>\n<p><a href=\"https://i.stack.imgur.com/fzd7C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fzd7C.png\" alt=\"How to force chrome to reload cached files\" /></a></p>\n<p>And if you have <strong>Firefox</strong> caching issues:</p>\n<p><a href=\"https://i.stack.imgur.com/O8hno.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O8hno.png\" alt=\"How to force asset reload on Firefox\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/dFHrK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dFHrK.png\" alt=\"How to disable caching in Firefox while in development\" /></a></p>\n<p>Do this only in development. You also need a mechanism to force reload for production, since your users will use old cache invalidated modules if you update your application frequently and you don't provide a dedicated cache synchronisation mechanism like the ones described in the answers above.</p>\n<p>Yes, this information is already in previous answers, but I still needed to do a Google search to find it.</p>\n"
},
{
"answer_id": 60337162,
"author": "Nicolai VdS",
"author_id": 6714566,
"author_profile": "https://Stackoverflow.com/users/6714566",
"pm_score": 0,
"selected": false,
"text": "<p>We have one solution with some different way for implementation. We use the above solution for it.</p>\n<pre><code>datatables?v=1\n</code></pre>\n<p>We can handle the version of the file. It means that every time that we change our file, change the version of it too. But it's not a suitable way.</p>\n<p>Another way used a <a href=\"https://en.wikipedia.org/wiki/Globally_unique_identifier\" rel=\"nofollow noreferrer\">GUID</a>. It wasn't suitable either, because each time it fetches the file and doesn't use from the browser cache.</p>\n<pre><code>datatables?v=Guid.NewGuid()\n</code></pre>\n<p>The last way that is the best way is:</p>\n<p>When a file change occurs, change the version too. Check the follow code:</p>\n<pre><code><script src="~/scripts/[email protected](Server.MapPath("/scripts/main.js")).ToString("yyyyMMddHHmmss")"></script>\n</code></pre>\n<p>By this way, when you change the file, LastWriteTime change too, so the version of the file will change and in the next when you open the browser, it detects a new file and fetch it.</p>\n"
},
{
"answer_id": 60723671,
"author": "loretoparisi",
"author_id": 758836,
"author_profile": "https://Stackoverflow.com/users/758836",
"pm_score": 1,
"selected": false,
"text": "<p>A simple solution for static files (just for development purposes) that adds a random version number to the script URI, using script tag injections</p>\n<pre><code><script>\n var script = document.createElement('script');\n script.src = "js/app.js?v=" + Math.random();\n document.getElementsByTagName('head')[0].appendChild(script);\n</script>\n</code></pre>\n"
},
{
"answer_id": 60959675,
"author": "Amr Lotfy",
"author_id": 1356559,
"author_profile": "https://Stackoverflow.com/users/1356559",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my Bash script-based cache busting solution:</p>\n<ol>\n<li>I assume you have CSS and JavaScript files referenced in your <em>index.html</em> file</li>\n<li>Add a timestamp as a parameter for .js and .css in <em>index.html</em> as below (one time only)</li>\n<li>Create a <em>timestamp.txt</em> file with the above timestamp.</li>\n<li>After any update to .css or .js file, just run the below .sh script</li>\n</ol>\n<p>Sample <em>index.html</em> entries for .js and .css with a timestamp:</p>\n<pre><code><link rel="stylesheet" href="bla_bla.css?v=my_timestamp">\n<script src="scripts/bla_bla.js?v=my_timestamp"></script>\n</code></pre>\n<p>File <em>timestamp.txt</em> should only contain same timestamp 'my_timestamp' (will be searched for and replaced by script later on)</p>\n<p>Finally here is the script (let's call it cache_buster.sh :D)</p>\n<pre><code>old_timestamp=$(cat timestamp.txt)\ncurrent_timestamp=$(date +%s)\nsed -i -e "s/$old_timestamp/$current_timestamp/g" index.html\necho "$current_timestamp" >timestamp.txt\n</code></pre>\n<p>(Visual Studio Code users) you can put this script in a hook, so it gets called each time a file is saved in your workspace.</p>\n"
},
{
"answer_id": 63118075,
"author": "raul7",
"author_id": 7489103,
"author_profile": "https://Stackoverflow.com/users/7489103",
"pm_score": 0,
"selected": false,
"text": "<p>I've solved this issue by using\n<a href=\"https://en.wikipedia.org/wiki/HTTP_ETag\" rel=\"nofollow noreferrer\">ETag</a>:</p>\n<blockquote>\n<p>ETag or entity tag is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for Web cache validation, which allows a client to make conditional requests. This allows caches to be more efficient and saves bandwidth, as a Web server does not need to send a full response if the content has not changed. ETags can also be used for optimistic concurrency control,<a href=\"https://en.wikipedia.org/wiki/HTTP_ETag\" rel=\"nofollow noreferrer\">1</a> as a way to help prevent simultaneous updates of a resource from overwriting each other.</p>\n</blockquote>\n<ul>\n<li>I am running a Single-Page Application (written in Vue.JS).</li>\n<li>The output of the application is built by npm, and is stored as dist folder (the important file is: dist/static/js/app.my_rand.js)</li>\n<li>Nginx is responsible of serving the content in this dist folder, and it generates a new Etag value, which is some kind of a fingerprint, based on the modification time and the content of the dist folder. Thus when the resource changes, a new Etag value is generated.</li>\n<li>When the browser requests the resource, a comparison between the request headers and the stored Etag, can determine if the two representations of the resource are the same, and could be served from cache or a new response with a new Etag needs to be served.</li>\n</ul>\n"
},
{
"answer_id": 63932033,
"author": "Jayee",
"author_id": 899742,
"author_profile": "https://Stackoverflow.com/users/899742",
"pm_score": 1,
"selected": false,
"text": "<p>In ASP.NET Core you could achieve this by adding 'asp-append-version':</p>\n<pre><code><link rel="stylesheet" href="~/css/xxx.css" asp-append-version="true" />\n\n <script src="~/js/xxx.js" asp-append-version="true"></script>\n</code></pre>\n<p>It will generate HTML:</p>\n<pre><code><link rel="stylesheet" href="/css/xxx.css?v=rwgRWCjxemznsx7wgNx5PbMO1EictA4Dd0SjiW0S90g" />\n</code></pre>\n<p>The framework will generate a new version number every time you update the file.</p>\n"
},
{
"answer_id": 69619469,
"author": "zyrup",
"author_id": 1590519,
"author_profile": "https://Stackoverflow.com/users/1590519",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't want the client to cache the file ever, this solution seems to be quickest to implement. Adjust the part with <code>time()</code> if you e.g. load the file in footer.php:</p>\n<pre><code><script src="<?php echo get_template_directory_uri(); ?>/js/main.js?v=<?= time() ?>"></script>\n</code></pre>\n"
},
{
"answer_id": 71968270,
"author": "Wervice",
"author_id": 18889997,
"author_profile": "https://Stackoverflow.com/users/18889997",
"pm_score": 0,
"selected": false,
"text": "<pre><code>location.reload(true)\n</code></pre>\n<p>Or use "Network" from the inspector ([CTRL] + [I]), click "disable cache", click trash icon, click "load"/"get"</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
]
| I have noticed that some browsers (in particular, Firefox and [Opera](https://en.wikipedia.org/wiki/Opera_%28web_browser%29)) are very zealous in using cached copies of **.css** and **.js** files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keeps on using the cached copy.
What is the most elegant way of forcing the user's browser to reload the file when it has changed?
Ideally, the solution would not force the browser to reload the file on every visit to the page.
---
I have found [John Millikin's](https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118921#118921) and [da5id's](https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118901#118901) suggestion to be useful. It turns out there is a term for this: **auto-versioning**.
I have posted a new answer below which is a combination of my original solution and John's suggestion.
Another idea that was suggested by **SCdF** would be to append a bogus query string to the file. (Some Python code, to automatically use the timestamp as a bogus query string, was [submitted by *pi.*](https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/121143#121143).)
However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.) | This solution is written in PHP, but it should be easily adapted to other languages.
The original `.htaccess` regex can cause problems with files like `json-1.3.js`. The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)
First, we use the following rewrite rule in .htaccess:
```
RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
```
Now, we write the following PHP function:
```php
/**
* Given a file, i.e. /css/base.css, replaces it with a string containing the
* file's mtime, i.e. /css/base.1221534296.css.
*
* @param $file The file to be loaded. Must be an absolute path (i.e.
* starting with slash).
*/
function auto_version($file)
{
if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
return $file;
$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}
```
Now, wherever you include your CSS, change it from this:
```html
<link rel="stylesheet" href="/css/base.css" type="text/css" />
```
To this:
```
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />
```
This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.
This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated. |
118,905 | <p>I'm trying to write a parser to get the data out of a typical html table day/time schedule (like <a href="http://kut.org/about/schedule" rel="nofollow noreferrer">this</a>). </p>
<p>I'd like to give this parser a page and a table class/id, and have it return a list of events, along with days & times they occur. It should take into account rowspans and colspans, so for the linked example, it would return </p>
<pre><code>{:event => "Music With Paul Ray", :times => [T 12:00am - 3:00am, F 12:00am - 3:00am]}, etc.
</code></pre>
<p>I've sort of figured out a half-executed messy approach using ruby, and am wondering how you might tackle such a problem?</p>
| [
{
"answer_id": 119029,
"author": "treat your mods well",
"author_id": 20772,
"author_profile": "https://Stackoverflow.com/users/20772",
"pm_score": 0,
"selected": false,
"text": "<p>This is what the program will need to do:</p>\n\n<ol>\n<li>Read the tags in (detect attributes and open/close tags)</li>\n<li>Build an internal representation of the table (how will you handle malformed tables?)</li>\n<li>Calculate the day, start time, and end time of each event</li>\n<li>Merge repeated events into an event series</li>\n</ol>\n\n<p>That's a lot of components! You'll probably need to ask a more specific question.</p>\n"
},
{
"answer_id": 119460,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 2,
"selected": false,
"text": "<p>The best thing to do here is to use a HTML parser. With a HTML parser you can look at the table rows programmatically, without having to resort to fragile regular expressions and doing the parsing yourself.</p>\n\n<p>Then you can run some logic along the lines of (this is not runnable code, just a sketch that you should be able to see the idea from):</p>\n\n<pre><code>for row in table:\n i = 0\n for cell in row: # skipping row 1\n event = name\n starttime = row[0]\n endtime = table[ i + cell.rowspan + 1 ][0]\n\n print event, starttime, endtime\n i += 1\n</code></pre>\n"
},
{
"answer_id": 119490,
"author": "Hannes Ovrén",
"author_id": 13565,
"author_profile": "https://Stackoverflow.com/users/13565",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">http://www.crummy.com/software/BeautifulSoup/</a> and that task should be a breeze.</p>\n"
},
{
"answer_id": 140471,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>As said, using regexes on HTML is generally a bad idea, you should use a good parser.<br>\nFor validating XHTML pages, you can use a simple XML parser which is available in most languages. Alas, in your case, the given page doesn't validate (W3C's markup validation service reports 230 Errors, 7 warning(s)!)<br>\nFor generic, possibly malformed HTML, there are libraries to handle that (kigurai recommends BeautifulSoup for Python, I know also TagSoup for Java, there are others).</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/118905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm trying to write a parser to get the data out of a typical html table day/time schedule (like [this](http://kut.org/about/schedule)).
I'd like to give this parser a page and a table class/id, and have it return a list of events, along with days & times they occur. It should take into account rowspans and colspans, so for the linked example, it would return
```
{:event => "Music With Paul Ray", :times => [T 12:00am - 3:00am, F 12:00am - 3:00am]}, etc.
```
I've sort of figured out a half-executed messy approach using ruby, and am wondering how you might tackle such a problem? | The best thing to do here is to use a HTML parser. With a HTML parser you can look at the table rows programmatically, without having to resort to fragile regular expressions and doing the parsing yourself.
Then you can run some logic along the lines of (this is not runnable code, just a sketch that you should be able to see the idea from):
```
for row in table:
i = 0
for cell in row: # skipping row 1
event = name
starttime = row[0]
endtime = table[ i + cell.rowspan + 1 ][0]
print event, starttime, endtime
i += 1
``` |
119,009 | <p>In our Java applications we typically use the maven conventions (docs, src/java, test, etc.). For Perl we follow similar conventions only using a top level 'lib' which is easy to add to Perl's @INC.</p>
<p>I'm about to embark on creating a service written in Erlang, what's a good source layout for Erlang applications?</p>
| [
{
"answer_id": 119443,
"author": "Bwooce",
"author_id": 15290,
"author_profile": "https://Stackoverflow.com/users/15290",
"pm_score": 5,
"selected": true,
"text": "<p>The Erlang recommended standard directory structure can be <a href=\"http://erlang.org/doc/design_principles/applications.html#id80846\" rel=\"nofollow noreferrer\">found here</a>.</p>\n\n<p>In addition you may need a few more directories depending on your project, common ones are (credit to Vance Shipley): </p>\n\n<pre>\n lib: OS driver libraries\n bin: OS executables\n c_src: C language source files (e.g. for drivers)\n java_src: Java language source files\n examples: Example code\n mibs: SNMP MIBs\n</pre>\n\n<p>Other projects such as <a href=\"http://bob.pythonmac.org/archives/2007/12/17/using-the-mochiweb-project-skeleton/\" rel=\"nofollow noreferrer\">Mochiweb</a> have their own structures, Mochiweb even have a script to create it all for you. Other projects such as <a href=\"http://www.erlware.org\" rel=\"nofollow noreferrer\">Erlware</a> overlay on the standard structure.</p>\n"
},
{
"answer_id": 809497,
"author": "psyeugenic",
"author_id": 99013,
"author_profile": "https://Stackoverflow.com/users/99013",
"pm_score": 2,
"selected": false,
"text": "<p>Another critical directory is the priv directory. Here you can store files that can easily be found from your applications.</p>\n\n<pre><code>code:priv_dir(Name) -> string() | {error, bad_name}\n</code></pre>\n\n<p>where Name is the name of your application.</p>\n"
},
{
"answer_id": 832544,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Erlware is changing that - in a couple of days the Erlware structures will be exactly that of Erlang OTP. Actually the structure of app packages is already exactly that of OTP and as specified above. What will change is that Erlware installed directory structure will fit exactly over an existing Erlang/OTP install (of course one is not needed to install Erlware though) Erlware can now be used to add packages to an existing install very easily.</p>\n\n<p>Cheers,\nMartin</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
| In our Java applications we typically use the maven conventions (docs, src/java, test, etc.). For Perl we follow similar conventions only using a top level 'lib' which is easy to add to Perl's @INC.
I'm about to embark on creating a service written in Erlang, what's a good source layout for Erlang applications? | The Erlang recommended standard directory structure can be [found here](http://erlang.org/doc/design_principles/applications.html#id80846).
In addition you may need a few more directories depending on your project, common ones are (credit to Vance Shipley):
```
lib: OS driver libraries
bin: OS executables
c_src: C language source files (e.g. for drivers)
java_src: Java language source files
examples: Example code
mibs: SNMP MIBs
```
Other projects such as [Mochiweb](http://bob.pythonmac.org/archives/2007/12/17/using-the-mochiweb-project-skeleton/) have their own structures, Mochiweb even have a script to create it all for you. Other projects such as [Erlware](http://www.erlware.org) overlay on the standard structure. |
119,011 | <p>Can anyone suggest a good way of detecting if a database is empty from Java (needs to support at least Microsoft SQL Server, Derby and Oracle)?</p>
<p>By empty I mean in the state it would be if the database were freshly created with a new create database statement, though the check need not be 100% perfect if covers 99% of cases.</p>
<p>My first thought was to do something like this...</p>
<pre><code>tables = metadata.getTables(null, null, null, null);
Boolean isEmpty = !tables.next();
return isEmpty;
</code></pre>
<p>...but unfortunately that gives me a bunch of underlying system tables (at least in Microsoft SQL Server).</p>
| [
{
"answer_id": 119046,
"author": "Nathan Feger",
"author_id": 8563,
"author_profile": "https://Stackoverflow.com/users/8563",
"pm_score": 0,
"selected": false,
"text": "<p>Are you always checking databases created in the same way? If so you might be able to simply select from a subset of tables that you are familiar with to look for data.</p>\n\n<p>You also might need to be concerned about static data perhaps added to a lookup table that looks like 'data' from a cursory glance, but might in fact not really be 'data' in an interesting sense of the term.</p>\n\n<p>Can you provide any more information about the specific problem you are trying to tackle? I wonder if with more data a simpler and more reliable answer might be provided.</p>\n\n<p>Are you creating these databases?<br>\nAre you creating them with roughly the same constructor each time?\nWhat kind of process leaves these guys hanging around, and can that constructor destruct?</p>\n\n<p>There is certainly a meta data process to loop through tables, just through something a little more custom might exist.</p>\n"
},
{
"answer_id": 119066,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 2,
"selected": false,
"text": "<p>There are some cross-database SQL-92 schema query standards - mileage for this of course varies according to vendor</p>\n\n<pre><code>SELECT COUNT(*) FROM [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_TYPE] = <tabletype>\n</code></pre>\n\n<p>Support for these varies by vendor, as does the content of the columns for the Tables view. SQL implementation of Information Schema docs found here:</p>\n\n<blockquote>\n <p><a href=\"http://msdn.microsoft.com/en-us/library/aa933204(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa933204(SQL.80).aspx</a></p>\n</blockquote>\n\n<p>More specifically in SQL Server, sysobjects metadata predates the SQL92 standards initiative.</p>\n\n<pre><code>SELECT COUNT(*) FROM [sysobjects] WHERE [type] = 'U'\n</code></pre>\n\n<p>Query above returns the count of User tables in the database. More information about the sysobjects table here:</p>\n\n<blockquote>\n <p><a href=\"http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx</a></p>\n</blockquote>\n"
},
{
"answer_id": 119086,
"author": "user19113",
"author_id": 19113,
"author_profile": "https://Stackoverflow.com/users/19113",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know if this is a complete solution ... but you can determine if a table is a system table by reading the table_type column of the ResultSet returned by getTables:</p>\n\n<pre><code>int nonSystemTableCount = 0;\ntables = metadata.getTables(null, null, null, null);\nwhile( tables.next () ) {\n if( !\"SYSTEM TABLE\".equals( tables.getString( \"table_type\" ) ) ) {\n nonSystemTableCount++;\n }\n}\nboolean isEmpty = nonSystemTableCount == 0;\nreturn isEmpty;\n</code></pre>\n\n<p>In practice ... I think you might have to work pretty hard to get a really reliable, truly generic solution.</p>\n"
},
{
"answer_id": 119274,
"author": "Mpvvliet",
"author_id": 20783,
"author_profile": "https://Stackoverflow.com/users/20783",
"pm_score": 0,
"selected": false,
"text": "<p>In Oracle, at least, you can select from USER_TABLES to exclude any system tables.</p>\n"
},
{
"answer_id": 44615862,
"author": "Naor Bar",
"author_id": 6792588,
"author_profile": "https://Stackoverflow.com/users/6792588",
"pm_score": 0,
"selected": false,
"text": "<p><strong>I could not find a standard generic solution, so each database needs its own tests set.</strong> </p>\n\n<p>For Oracle for instance, I used to check tables, sequences and indexes:</p>\n\n<pre><code>select count(*) from user_tables\nselect count(*) from user_sequences\nselect count(*) from user_indexes\n</code></pre>\n\n<p>For SqlServer I used to check tables, views and stored procedures:</p>\n\n<pre><code>SELECT * FROM sys.all_objects where type_desc in ('USER_TABLE', 'SQL_STORED_PROCEDURE', 'VIEW')\n</code></pre>\n\n<p><strong>The best generic (and intuitive) solution I got, is by using ANT SQL task - all I needed to do is passing different parameters for each type of database.</strong> </p>\n\n<p>i.e. The ANT build file looks like this:</p>\n\n<pre><code><project name=\"run_sql_query\" basedir=\".\" default=\"main\">\n <!-- run_sql_query: --> \n <target name=\"run_sql_query\">\n <echo message=\"=== running sql query from file ${database.src.file}; check the result in ${database.out.file} ===\"/>\n <sql classpath=\"${jdbc.jar.file}\" \n driver=\"${database.driver.class}\" \n url=\"${database.url}\" \n userid=\"${database.user}\" \n password=\"${database.password}\" \n src=\"${database.src.file}\"\n output=\"${database.out.file}\"\n print=\"yes\"/>\n </target>\n\n <!-- Main: --> \n <target name=\"main\" depends=\"run_sql_query\"/> \n</project> \n</code></pre>\n\n<p>For more details, please refer to ANT: </p>\n\n<p><a href=\"https://ant.apache.org/manual/Tasks/sql.html\" rel=\"nofollow noreferrer\">https://ant.apache.org/manual/Tasks/sql.html</a></p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
| Can anyone suggest a good way of detecting if a database is empty from Java (needs to support at least Microsoft SQL Server, Derby and Oracle)?
By empty I mean in the state it would be if the database were freshly created with a new create database statement, though the check need not be 100% perfect if covers 99% of cases.
My first thought was to do something like this...
```
tables = metadata.getTables(null, null, null, null);
Boolean isEmpty = !tables.next();
return isEmpty;
```
...but unfortunately that gives me a bunch of underlying system tables (at least in Microsoft SQL Server). | There are some cross-database SQL-92 schema query standards - mileage for this of course varies according to vendor
```
SELECT COUNT(*) FROM [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_TYPE] = <tabletype>
```
Support for these varies by vendor, as does the content of the columns for the Tables view. SQL implementation of Information Schema docs found here:
>
> <http://msdn.microsoft.com/en-us/library/aa933204(SQL.80).aspx>
>
>
>
More specifically in SQL Server, sysobjects metadata predates the SQL92 standards initiative.
```
SELECT COUNT(*) FROM [sysobjects] WHERE [type] = 'U'
```
Query above returns the count of User tables in the database. More information about the sysobjects table here:
>
> <http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx>
>
>
> |
119,018 | <p>It seems that anyone can snoop on incoming/outgoing .NET web service SOAP messages just by dropping in a simple SoapExtension into the bin folder and then plumbing it in using:</p>
<pre><code><soapExtensionTypes>
<add type="MyLoggingSoapExtension, SoapLoggingTools" priority="0" group="High" />
<soapExtensionTypes>
</code></pre>
<p>Is there a way to prevent SOAP extensions from loading or to be asked in my app (through an event or some such mechanism) whether it's ok to load ?</p>
<p>@Hurst: thanks for the answer. I know about message level encryption/WS-Security and was hoping not to have to go that road. We have classic ASP clients using the service and that opens a small world of pain. There are SSL certs on the site running the web service but I was kinda hoping that I could discourage the client from tinkering with soap extensions as they have developers who have some ability to 'play'.</p>
| [
{
"answer_id": 119212,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 3,
"selected": true,
"text": "<p>I am not sure what you mean by extensions and bin folders (I would guess you are using .NET), so I can't answer about them being loaded etc.</p>\n\n<p>However, note that SOAP is designed to allow intermediaries to read the headers and even to modify them. (Do a search for \"SOAP Active Intermediaries\"). <strong>Judging by that, I expect there to be no reason for a technology to avoid snooping by preventing code from reading the SOAP</strong>.</p>\n\n<p>The proper way to protect yourself is to use \"<strong><em>message-level security</em></strong>\". (This is in contrast to <em>transport-level security</em>, such as SSL, which does not protect from intermediaries). <strong>In other words, encrypt your own messages before sending.</strong> </p>\n\n<p>One available standard used to implement message-level security mechanisms is the <strong>WS-Security</strong> protocol. This allows you to target the encryption to the payload and relevant headers regardless of transport. It is more complex, but that is how you would go about restricting access.</p>\n"
},
{
"answer_id": 119231,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 0,
"selected": false,
"text": "<p>Totally agree with @Hurst - if you want to prevent others reading your messages you need to use message-level encryption. Otherwise even simple NetMon can crack over the wire traffic. </p>\n\n<p>Of course if someone has access to the machine (given the access to /bin etc.), even cryptography may not be enough to prevent snoopers using debuggers e.g. to read in-memory representations of the message after decrypting. </p>\n\n<p>With physical access to the machine - all bets are off.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
]
| It seems that anyone can snoop on incoming/outgoing .NET web service SOAP messages just by dropping in a simple SoapExtension into the bin folder and then plumbing it in using:
```
<soapExtensionTypes>
<add type="MyLoggingSoapExtension, SoapLoggingTools" priority="0" group="High" />
<soapExtensionTypes>
```
Is there a way to prevent SOAP extensions from loading or to be asked in my app (through an event or some such mechanism) whether it's ok to load ?
@Hurst: thanks for the answer. I know about message level encryption/WS-Security and was hoping not to have to go that road. We have classic ASP clients using the service and that opens a small world of pain. There are SSL certs on the site running the web service but I was kinda hoping that I could discourage the client from tinkering with soap extensions as they have developers who have some ability to 'play'. | I am not sure what you mean by extensions and bin folders (I would guess you are using .NET), so I can't answer about them being loaded etc.
However, note that SOAP is designed to allow intermediaries to read the headers and even to modify them. (Do a search for "SOAP Active Intermediaries"). **Judging by that, I expect there to be no reason for a technology to avoid snooping by preventing code from reading the SOAP**.
The proper way to protect yourself is to use "***message-level security***". (This is in contrast to *transport-level security*, such as SSL, which does not protect from intermediaries). **In other words, encrypt your own messages before sending.**
One available standard used to implement message-level security mechanisms is the **WS-Security** protocol. This allows you to target the encryption to the payload and relevant headers regardless of transport. It is more complex, but that is how you would go about restricting access. |
119,060 | <p>The Image Web Part doesn't seem to have an href attribute that I can set. Is there something I am missing?</p>
| [
{
"answer_id": 119122,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 3,
"selected": false,
"text": "<p>Does it have to be an Image Web Part? If not I would simply use a <a href=\"http://office.microsoft.com/en-us/sharepointserver/HA100240461033.aspx\" rel=\"noreferrer\">Content Editor Web Part</a> and paste the required HTML there.</p>\n\n<pre><code><a href=\"http://www.google.com\"><img src=\"urlToImage\" /></a>\n</code></pre>\n"
},
{
"answer_id": 1078914,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>what if it have to? \nusers need to have an opportunity to change the link and the image themselves and not to disturb an administrator.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| The Image Web Part doesn't seem to have an href attribute that I can set. Is there something I am missing? | Does it have to be an Image Web Part? If not I would simply use a [Content Editor Web Part](http://office.microsoft.com/en-us/sharepointserver/HA100240461033.aspx) and paste the required HTML there.
```
<a href="http://www.google.com"><img src="urlToImage" /></a>
``` |
119,098 | <p>In new C++ code, I tend to use the C++ iostream library instead of the C stdio library.</p>
<p>I've noticed some programmers seem to stick to stdio, insisting that it's more portable.</p>
<p>Is this really the case? What is better to use?</p>
| [
{
"answer_id": 119118,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": false,
"text": "<p>If, like me, you learned C before learning C++, the stdio libraries seem more natural to use. There are pros and cons for iostream vs. stdio but I do miss printf() when using iostream.</p>\n"
},
{
"answer_id": 119126,
"author": "Colin Jensen",
"author_id": 9884,
"author_profile": "https://Stackoverflow.com/users/9884",
"pm_score": 3,
"selected": false,
"text": "<p>Back in the bad old days, the C++ Standards committee kept mucking about with the language and iostreams was a moving target. If you used iostreams, you were then given the opportunity to rewrite parts of your code every year or so. Because of this, I always used stdio which hasn't changed significantly since 1989.</p>\n\n<p>If I were doing stuff today, I would use iostreams.</p>\n"
},
{
"answer_id": 119149,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 4,
"selected": false,
"text": "<p>It's just too verbose.</p>\n\n<p>Ponder the iostream construct for doing the following (similarly for scanf):</p>\n\n<pre><code>// nonsense output, just to examplify\nfprintf(stderr, \"at %p/%s: mean value %.3f of %4d samples\\n\",\n stats, stats->name, stats->mean, stats->sample_count);\n</code></pre>\n\n<p>That would requires something like:</p>\n\n<pre><code>std::cerr << \"at \" << static_cast<void*>(stats) << \"/\" << stats->name\n << \": mean value \" << std::precision(3) << stats->mean\n << \" of \" << std::width(4) << std::fill(' ') << stats->sample_count\n << \" samples \" << std::endl;\n</code></pre>\n\n<p>String formatting is a case where object-orientedness can, and should be, sidestepped in favour of a formatting DSL embedded in strings. Consider Lisp's <code>format</code>, Python's printf-style formatting, or PHP, Bash, Perl, Ruby and their string intrapolation.</p>\n\n<p><code>iostream</code> for that use case is misguided, at best.</p>\n"
},
{
"answer_id": 119194,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 6,
"selected": true,
"text": "<p>To answer the original question:<br>\nAnything that can be done using stdio can be done using the iostream library.<br></p>\n\n<pre><code>Disadvantages of iostreams: verbose\nAdvantages of iostreams: easy to extend for new non POD types.\n</code></pre>\n\n<p>The step forward the C++ made over C was type safety.</p>\n\n<ul>\n<li><p>iostreams was designed to be explicitly type safe. Thus assignment to an object explicitly checked the type (at compiler time) of the object being assigned too (generating an compile time error if required). Thus prevent run-time memory over-runs or writing a float value to a char object etc.<br></p></li>\n<li><p>scanf()/printf() and family on the other hand rely on the programmer getting the format string correct and there was no type checking (I believe gcc has an extension that helps). As a result it was the source of many bugs (as programmers are less perfect in their analysis than compilers [not going to say compilers are perfect just better than humans]).</p></li>\n</ul>\n\n<p>Just to clarify comments from Colin Jensen.</p>\n\n<ul>\n<li>The iostream libraries have been stable since the release of the last standard (I forget the actual year but about 10 years ago).</li>\n</ul>\n\n<p>To clarify comments by Mikael Jansson.</p>\n\n<ul>\n<li>The other languages that he mentions that use the format style have explicit safeguards to prevent the dangerous side effects of the C stdio library that can (in C but not the mentioned languages) cause a run-time crash.</li>\n</ul>\n\n<p><b>N.B.</b> I agree that the iostream library is a bit on the verbose side. But I am willing to put up with the verboseness to ensure runtime safety. But we can mitigate the verbosity by using <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html\" rel=\"nofollow noreferrer\">Boost Format Library</a>.</p>\n\n<pre><code>#include <iostream>\n#include <iomanip>\n#include <boost/format.hpp>\n\nstruct X\n{ // this structure reverse engineered from\n // example provided by 'Mikael Jansson' in order to make this a running example\n\n char* name;\n double mean;\n int sample_count;\n};\nint main()\n{\n X stats[] = {{\"Plop\",5.6,2}};\n\n // nonsense output, just to exemplify\n\n // stdio version\n fprintf(stderr, \"at %p/%s: mean value %.3f of %4d samples\\n\",\n stats, stats->name, stats->mean, stats->sample_count);\n\n // iostream\n std::cerr << \"at \" << (void*)stats << \"/\" << stats->name\n << \": mean value \" << std::fixed << std::setprecision(3) << stats->mean\n << \" of \" << std::setw(4) << std::setfill(' ') << stats->sample_count\n << \" samples\\n\";\n\n // iostream with boost::format\n std::cerr << boost::format(\"at %p/%s: mean value %.3f of %4d samples\\n\")\n % stats % stats->name % stats->mean % stats->sample_count;\n}\n</code></pre>\n"
},
{
"answer_id": 119210,
"author": "Evan",
"author_id": 6277,
"author_profile": "https://Stackoverflow.com/users/6277",
"pm_score": 2,
"selected": false,
"text": "<p>For binary IO, I tend to use stdio's fread and fwrite. For formatted stuff I'll usually use IO Stream although as Mikael said, non-trival (non-default?) formatting can be a PITA.</p>\n"
},
{
"answer_id": 119325,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 1,
"selected": false,
"text": "<p>stdio is better for reading binary files (like freading blocks into a vector<unsigned char> and using .resize() etc.). See the read_rest function in file.hh in <a href=\"http://nuwen.net/libnuwen.html\" rel=\"nofollow noreferrer\">http://nuwen.net/libnuwen.html</a> for an example.</p>\n\n<p>C++ streams can choke on lots of bytes when reading binary files causing a false eof.</p>\n"
},
{
"answer_id": 119351,
"author": "KK.",
"author_id": 7438,
"author_profile": "https://Stackoverflow.com/users/7438",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html\" rel=\"noreferrer\" title=\"Boost Format Library\">Boost Format Library</a> provides a type-safe, object-oriented alternative for printf-style string formatting and is a complement to iostreams that does not suffer from the usual verbosity issues due to the clever use of operator%. I recommend considering it over using plain C printf if you dislike formatting with iostream's operator<<.</p>\n"
},
{
"answer_id": 119371,
"author": "Jan de Vos",
"author_id": 11215,
"author_profile": "https://Stackoverflow.com/users/11215",
"pm_score": 2,
"selected": false,
"text": "<p>I use iostreams, mainly because that makes it easier to fiddle with the stream later on (if I need it). For example, you could find out that you want to display the output in some trace window -- this is relatively easy to do with cout and cerr. You can, off course, fiddle with pipes and stuff on unix, but that is not as portable.</p>\n\n<p>I do love printf-like formatting, so I usually format a string first, and then send it to the buffer. With Qt, I often use <a href=\"http://doc.trolltech.com/4.4/qstring.html#sprintf\" rel=\"nofollow noreferrer\">QString::sprintf</a> (although they recommend using <a href=\"http://doc.trolltech.com/4.4/qstring.html#arg-10\" rel=\"nofollow noreferrer\">QString::arg</a> instead). I've looked at <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html\" rel=\"nofollow noreferrer\">boost.format</a> as well, but couldn't really get used to the syntax (too many %'s). I should really give it a look, though.</p>\n"
},
{
"answer_id": 119532,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 1,
"selected": false,
"text": "<p>Since iostreams have become a standard you should use them knowing that your code will work for sure with newer versions of compiler. I guess nowadays most of the compilers know very well about iostreams and there shouldn't be any problem using them.</p>\n\n<p>But if you want to stick with *printf functions there can be no problem in my opinion.</p>\n"
},
{
"answer_id": 154988,
"author": "Dan Hewett",
"author_id": 17975,
"author_profile": "https://Stackoverflow.com/users/17975",
"pm_score": 3,
"selected": false,
"text": "<p>In principle I would use iostreams, in practice I do too much formatted decimals, etc that make iostreams too unreadable, so I use stdio. Boost::format is an improvement, but not quite motivating enough for me. In practice, stdio is nearly typesafe since most modern compilers do argument checking anyway.</p>\n\n<p>It's an area where I'm still not totally happy with any of the solutions.</p>\n"
},
{
"answer_id": 365607,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>What I miss about the iolibraries is the formatted input.</p>\n\n<p>iostreams does not have a nice way to replicate scanf() and even boost does not have the required extension for input.</p>\n"
},
{
"answer_id": 1781584,
"author": "R Samuel Klatchko",
"author_id": 29809,
"author_profile": "https://Stackoverflow.com/users/29809",
"pm_score": 2,
"selected": false,
"text": "<p>While there are a lot of benefits to the C++ iostreams API, one significant problem is has is around i18n. The problem is that the order of parameter substitutions can vary based on the culture. The classic example is something like:</p>\n\n<pre><code>// i18n UNSAFE \nstd::cout << \"Dear \" << name.given << ' ' << name.family << std::endl;\n</code></pre>\n\n<p>While that works for English, in Chinese the family name is comes first.</p>\n\n<p>When it comes to translating your code for foreign markets, translating snippets is fraught with peril so new l10ns may require changes to the code and not just different strings.</p>\n\n<p>boost::format seems to combine the best of stdio (a single format string that can use the parameters in a different order then they appear) and iostreams (type-safety, extensibility).</p>\n"
},
{
"answer_id": 8256127,
"author": "Sebastian Mach",
"author_id": 76722,
"author_profile": "https://Stackoverflow.com/users/76722",
"pm_score": 2,
"selected": false,
"text": "<p>I'll be comparing the two mainstream libraries from the C++ standard library.</p>\n\n<h2>You shouldn't use C-style-format-string-based string-processing-routines in C++.</h2>\n\n<p>Several reasons exist to mit their use:</p>\n\n<ul>\n<li>Not typesafe</li>\n<li>You can't pass non-POD types to variadic argument lists (i.e., neither to scanf+co., nor to printf+co.),\nor you enter the Dark Stronghold of Undefined Behaviour </li>\n<li>Easy to get wrong: \n<ul>\n<li>You must manage to keep the format string and the \"value-argument-list\" in sync</li>\n<li>You must keep in sync <em>correctly</em></li>\n</ul></li>\n</ul>\n\n<h2>Subtle bugs introduced at remote places</h2>\n\n<p>It is not only the printf in itself that is not good. Software gets old and is refactored and modified, and errors might be introduced from remote places. Suppose you have</p>\n\n<p>.</p>\n\n<pre><code>// foo.h\n...\nfloat foo;\n...\n</code></pre>\n\n<p>and somewhere ...</p>\n\n<pre><code>// bar/frob/42/icetea.cpp\n...\nscanf (\"%f\", &foo);\n...\n</code></pre>\n\n<p>And three years later you find that foo should be of some custom type ...</p>\n\n<pre><code>// foo.h\n...\nFixedPoint foo;\n...\n</code></pre>\n\n<p>but somewhere ...</p>\n\n<pre><code>// bar/frob/42/icetea.cpp\n...\nscanf (\"%f\", &foo);\n...\n</code></pre>\n\n<p>... then your old printf/scanf will still compile, except that you now get random segfaults and you don't remember why.</p>\n\n<h2>Verbosity of iostreams</h2>\n\n<p>If you think printf() is less verbose, then there's a certain probability that you don't use their iostream's full force. Example:</p>\n\n<pre><code> printf (\"My Matrix: %f %f %f %f\\n\"\n \" %f %f %f %f\\n\"\n \" %f %f %f %f\\n\"\n \" %f %f %f %f\\n\",\n mat(0,0), mat(0,1), mat(0,2), mat(0,3), \n mat(1,0), mat(1,1), mat(1,2), mat(1,3), \n mat(2,0), mat(2,1), mat(2,2), mat(2,3), \n mat(3,0), mat(3,1), mat(3,2), mat(3,3));\n</code></pre>\n\n<p>Compare that to using iostreams right:</p>\n\n<pre><code>cout << mat << '\\n';\n</code></pre>\n\n<p>You have to define a proper overload for operator<< which has roughly the structure of the printf-thingy, but the significant difference is that you now have something re-usable and typesafe; of course you can also make something re-usable for printf-likes, but then you have printf again (what if you replace the matrix members with the new <code>FixedPoint</code>?), apart from other non-trivialities, e.g. you must pass FILE* handles around.</p>\n\n<h2>C-style format strings are not better for I18N than iostreams</h2>\n\n<p>Note that format-strings are often thought of being the rescue with internationalization, but they are not at all better than iostream in that respect:</p>\n\n<pre><code>printf (\"Guten Morgen, Sie sind %f Meter groß und haben %d Kinder\", \n someFloat, someInt);\n\nprintf (\"Good morning, you have %d children and your height is %f meters\",\n someFloat, someInt); // Note: Position changed.\n\n// ^^ not the best example, but different languages have generally different\n// order of \"variables\"\n</code></pre>\n\n<p>I.e., old style C format strings lack positional information as much as iostreams do.</p>\n\n<p>You might want to consider <a href=\"http://www.boost.org/doc/libs/1_46_1/libs/format/doc/format.html\" rel=\"nofollow\">boost::format</a>, which offers support for stating the position in the format string explicitly. From their examples section:</p>\n\n<pre><code>cout << format(\"%1% %2% %3% %2% %1% \\n\") % \"11\" % \"22\" % \"333\"; // 'simple' style.\n</code></pre>\n\n<p>Some printf-implementations provide positional arguments, but they are non-standard. </p>\n\n<h2>Should I <strong>never</strong> use C-style format strings?</h2>\n\n<p>Apart from performance (as pointed out by Jan Hudec), I don't see a reason. But keep in mind: </p>\n\n<blockquote>\n <p>“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified” - Knuth</p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n <p>“Bottlenecks occur in surprising places, so don't try to second guess and put in a speed hack until you have proven that's where the bottleneck is.” - Pike</p>\n</blockquote>\n\n<p>Yes, printf-implementations are usually faster than iostreams are usually faster than boost::format (from a small and specific benchmark I wrote, but it should largely depend on the situation in particular: if printf=100%, then iostream=160%, and boost::format=220%)</p>\n\n<p>But do not blindly omit thinking about it: How much time do you <em>really</em> spend on text-processing? How long does your program run before exiting?\nIs it relevant at all to fall back to C-style format strings, loose type safety, decrease refactorbility, \nincrease probability of very subtle bugs that may hide themselves for years and may only reveal themselves right\ninto your favourites customers face? </p>\n\n<p>Personally, I wouldn't fall back if I can not gain more than 20% speedup. But because my applications\nspend virtually all of their time on other tasks than string-processing, I never had to. Some parsers\nI wrote spend virtually all their time on string processing, but their total runtime is so small\nthat it isn't worth the testing and verification effort.</p>\n\n<h2>Some riddles</h2>\n\n<p>Finally, I'd like to preset some riddles:</p>\n\n<p>Find all errors, because the compiler won't (he can only suggest if he's nice):</p>\n\n<pre><code>shared_ptr<float> f(new float);\nfscanf (stdout, \"%u %s %f\", f)\n</code></pre>\n\n<p>If nothing else, what's wrong with this one? </p>\n\n<pre><code>const char *output = \"in total, the thing is 50%\"\n \"feature complete\";\nprintf (output);\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
]
| In new C++ code, I tend to use the C++ iostream library instead of the C stdio library.
I've noticed some programmers seem to stick to stdio, insisting that it's more portable.
Is this really the case? What is better to use? | To answer the original question:
Anything that can be done using stdio can be done using the iostream library.
```
Disadvantages of iostreams: verbose
Advantages of iostreams: easy to extend for new non POD types.
```
The step forward the C++ made over C was type safety.
* iostreams was designed to be explicitly type safe. Thus assignment to an object explicitly checked the type (at compiler time) of the object being assigned too (generating an compile time error if required). Thus prevent run-time memory over-runs or writing a float value to a char object etc.
* scanf()/printf() and family on the other hand rely on the programmer getting the format string correct and there was no type checking (I believe gcc has an extension that helps). As a result it was the source of many bugs (as programmers are less perfect in their analysis than compilers [not going to say compilers are perfect just better than humans]).
Just to clarify comments from Colin Jensen.
* The iostream libraries have been stable since the release of the last standard (I forget the actual year but about 10 years ago).
To clarify comments by Mikael Jansson.
* The other languages that he mentions that use the format style have explicit safeguards to prevent the dangerous side effects of the C stdio library that can (in C but not the mentioned languages) cause a run-time crash.
**N.B.** I agree that the iostream library is a bit on the verbose side. But I am willing to put up with the verboseness to ensure runtime safety. But we can mitigate the verbosity by using [Boost Format Library](http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html).
```
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
struct X
{ // this structure reverse engineered from
// example provided by 'Mikael Jansson' in order to make this a running example
char* name;
double mean;
int sample_count;
};
int main()
{
X stats[] = {{"Plop",5.6,2}};
// nonsense output, just to exemplify
// stdio version
fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n",
stats, stats->name, stats->mean, stats->sample_count);
// iostream
std::cerr << "at " << (void*)stats << "/" << stats->name
<< ": mean value " << std::fixed << std::setprecision(3) << stats->mean
<< " of " << std::setw(4) << std::setfill(' ') << stats->sample_count
<< " samples\n";
// iostream with boost::format
std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n")
% stats % stats->name % stats->mean % stats->sample_count;
}
``` |
119,107 | <p>This is what I have so far: </p>
<pre><code>myArray.map!{ rand(max) }
</code></pre>
<p>Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?</p>
<p><strong>Edit:</strong><br>
I'd really like to see this done w/o loop - if at all possible.</p>
| [
{
"answer_id": 119120,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 1,
"selected": false,
"text": "<p>You could use a hash to track the random numbers you've used so far:</p>\n\n<pre><code>seen = {}\nmax = 100\n(1..10).map { |n|\n x = rand(max)\n while (seen[x]) \n x = rand(max)\n end\n x\n}\n</code></pre>\n"
},
{
"answer_id": 119124,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than add the items to a list/array, add them to a Set. </p>\n"
},
{
"answer_id": 119159,
"author": "Ryan Leavengood",
"author_id": 20891,
"author_profile": "https://Stackoverflow.com/users/20891",
"pm_score": 6,
"selected": true,
"text": "<p>This uses Set:</p>\n\n<pre><code>require 'set'\n\ndef rand_n(n, max)\n randoms = Set.new\n loop do\n randoms << rand(max)\n return randoms.to_a if randoms.size >= n\n end\nend\n</code></pre>\n"
},
{
"answer_id": 119174,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 0,
"selected": false,
"text": "<p>Here is one solution:</p>\n\n<p>Suppose you want these random numbers to be between <code>r_min</code> and <code>r_max</code>. For each element in your list, generate a random number <code>r</code>, and make <code>list[i]=list[i-1]+r</code>. This would give you random numbers which are monotonically increasing, guaranteeing uniqueness provided that</p>\n\n<ul>\n<li><code>r+list[i-1]</code> does not over flow</li>\n<li><code>r</code> > 0</li>\n</ul>\n\n<p>For the first element, you would use <code>r_min</code> instead of <code>list[i-1]</code>. Once you are done, you can shuffle the list so the elements are not so obviously in order.</p>\n\n<p>The only problem with this method is when you go over <code>r_max</code> and still have more elements to generate. In this case, you can reset <code>r_min</code> and <code>r_max</code> to 2 adjacent element you have already computed, and simply repeat the process. This effectively runs the same algorithm over an interval where there are no numbers already used. You can keep doing this until you have the list populated.</p>\n"
},
{
"answer_id": 119250,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 6,
"selected": false,
"text": "<pre><code>(0..50).to_a.sort{ rand() - 0.5 }[0..x] \n</code></pre>\n\n<p><code>(0..50).to_a</code> can be replaced with any array. \n0 is \"minvalue\", 50 is \"max value\" \nx is \"how many values i want out\" </p>\n\n<p>of course, its impossible for x to be permitted to be greater than max-min :)</p>\n\n<p>In expansion of how this works </p>\n\n<pre><code>(0..5).to_a ==> [0,1,2,3,4,5]\n[0,1,2,3,4,5].sort{ -1 } ==> [0, 1, 2, 4, 3, 5] # constant\n[0,1,2,3,4,5].sort{ 1 } ==> [5, 3, 0, 4, 2, 1] # constant\n[0,1,2,3,4,5].sort{ rand() - 0.5 } ==> [1, 5, 0, 3, 4, 2 ] # random\n[1, 5, 0, 3, 4, 2 ][ 0..2 ] ==> [1, 5, 0 ]\n</code></pre>\n\n<h3>Footnotes:</h3>\n\n<p>It is worth mentioning that at the time this question was originally answered, September 2008, that <a href=\"http://www.ruby-doc.org/core-2.1.5/Array.html#method-i-shuffle\" rel=\"noreferrer\"><code>Array#shuffle</code></a> was either not available or not already known to me, hence the approximation in <a href=\"http://www.ruby-doc.org/core-2.1.5/Array.html#method-i-sort\" rel=\"noreferrer\"><code>Array#sort</code></a></p>\n\n<p>And there's a barrage of suggested edits to this as a result.</p>\n\n<p>So:</p>\n\n<pre><code>.sort{ rand() - 0.5 }\n</code></pre>\n\n<p>Can be better, and shorter expressed on modern ruby implementations using</p>\n\n<pre><code>.shuffle\n</code></pre>\n\n<p>Additionally,</p>\n\n<pre><code>[0..x]\n</code></pre>\n\n<p>Can be more obviously written with <a href=\"http://www.ruby-doc.org/core-2.1.5/Array.html#method-i-take\" rel=\"noreferrer\"><code>Array#take</code></a> as:</p>\n\n<pre><code>.take(x)\n</code></pre>\n\n<p>Thus, the easiest way to produce a sequence of random numbers on a modern ruby is:</p>\n\n<pre><code>(0..50).to_a.shuffle.take(x)\n</code></pre>\n"
},
{
"answer_id": 119429,
"author": "Ryan Leavengood",
"author_id": 20891,
"author_profile": "https://Stackoverflow.com/users/20891",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a finite list of possible random numbers (i.e. 1 to 100), then Kent's solution is good.</p>\n\n<p>Otherwise there is no other good way to do it without looping. The problem is you MUST do a loop if you get a duplicate. My solution should be efficient and the looping should not be too much more than the size of your array (i.e. if you want 20 unique random numbers, it might take 25 iterations on average.) Though the number of iterations gets worse the more numbers you need and the smaller max is. Here is my above code modified to show how many iterations are needed for the given input:</p>\n\n<pre><code>require 'set'\n\ndef rand_n(n, max)\n randoms = Set.new\n i = 0\n loop do\n randoms << rand(max)\n break if randoms.size > n\n i += 1\n end\n puts \"Took #{i} iterations for #{n} random numbers to a max of #{max}\"\n return randoms.to_a\nend\n</code></pre>\n\n<p>I could write this code to LOOK more like Array.map if you want :)</p>\n"
},
{
"answer_id": 120637,
"author": "TuxmAL",
"author_id": 11594,
"author_profile": "https://Stackoverflow.com/users/11594",
"pm_score": 0,
"selected": false,
"text": "<p>As far as it is nice to know in advance the maxium value, you can do this way:</p>\n\n<pre><code>class NoLoopRand\n def initialize(max)\n @deck = (0..max).to_a\n end\n\n def getrnd\n return @deck.delete_at(rand(@deck.length - 1))\n end\nend\n</code></pre>\n\n<p>and you can obtain random data in this way: </p>\n\n<pre><code>aRndNum = NoLoopRand.new(10)\nputs aRndNum.getrnd\n</code></pre>\n\n<p>you'll obtain <code>nil</code> when all the values will be exausted from the deck.</p>\n"
},
{
"answer_id": 122440,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 5,
"selected": false,
"text": "<p>Just to give you an idea about speed, I ran four versions of this:</p>\n\n<ol>\n<li>Using Sets, like Ryan's suggestion.</li>\n<li>Using an Array slightly larger than necessary, then doing uniq! at the end.</li>\n<li>Using a Hash, like Kyle suggested.</li>\n<li>Creating an Array of the required size, then sorting it randomly, like Kent's suggestion (but without the extraneous \"- 0.5\", which does nothing).</li>\n</ol>\n\n<p>They're all fast at small scales, so I had them each create a list of 1,000,000 numbers. Here are the times, in seconds:</p>\n\n<ol>\n<li>Sets: 628</li>\n<li>Array + uniq: 629</li>\n<li>Hash: 645</li>\n<li>fixed Array + sort: 8</li>\n</ol>\n\n<p>And no, that last one is not a typo. So if you care about speed, and it's OK for the numbers to be integers from 0 to whatever, then my exact code was:</p>\n\n<pre><code>a = (0...1000000).sort_by{rand}\n</code></pre>\n"
},
{
"answer_id": 125771,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 2,
"selected": false,
"text": "<p>How about a play on this? Unique random numbers without needing to use Set or Hash. </p>\n\n<pre><code>x = 0\n(1..100).map{|iter| x += rand(100)}.shuffle\n</code></pre>\n"
},
{
"answer_id": 4079104,
"author": "Bryan Larsen",
"author_id": 91365,
"author_profile": "https://Stackoverflow.com/users/91365",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, it's possible to do this without a loop and without keeping track of which numbers have been chosen. It's called a Linear Feedback Shift Register: <a href=\"https://stackoverflow.com/questions/693880/create-random-number-sequence-with-no-repeats\">Create Random Number Sequence with No Repeats</a></p>\n"
},
{
"answer_id": 8875944,
"author": "Doug English",
"author_id": 754936,
"author_profile": "https://Stackoverflow.com/users/754936",
"pm_score": 1,
"selected": false,
"text": "<p>Based on Kent Fredric's solution above, this is what I ended up using:</p>\n\n<pre><code>def n_unique_rand(number_to_generate, rand_upper_limit)\n return (0..rand_upper_limit - 1).sort_by{rand}[0..number_to_generate - 1]\nend\n</code></pre>\n\n<p>Thanks Kent.</p>\n"
},
{
"answer_id": 9882824,
"author": "Duncan Beevers",
"author_id": 132089,
"author_profile": "https://Stackoverflow.com/users/132089",
"pm_score": 5,
"selected": false,
"text": "<p>Ruby 1.9 offers the Array#sample method which returns an element, or elements randomly selected from an Array. The results of #sample won't include the same Array element twice.</p>\n\n<pre><code>(1..999).to_a.sample 5 # => [389, 30, 326, 946, 746]\n</code></pre>\n\n<p>When compared to the <code>to_a.sort_by</code> approach, the <code>sample</code> method appears to be significantly faster. In a simple scenario I compared <code>sort_by</code> to <code>sample</code>, and got the following results.</p>\n\n<pre><code>require 'benchmark'\nrange = 0...1000000\nhow_many = 5\n\nBenchmark.realtime do\n range.to_a.sample(how_many)\nend\n=> 0.081083\n\nBenchmark.realtime do\n (range).sort_by{rand}[0...how_many]\nend\n=> 2.907445\n</code></pre>\n"
},
{
"answer_id": 12975652,
"author": "mmdemirbas",
"author_id": 471214,
"author_profile": "https://Stackoverflow.com/users/471214",
"pm_score": 0,
"selected": false,
"text": "<h2>Method 1</h2>\n\n<p>Using Kent's approach, it is possible to generate an array of arbitrary length keeping all values in a limited range:</p>\n\n\n\n<pre><code># Generates a random array of length n.\n#\n# @param n length of the desired array\n# @param lower minimum number in the array\n# @param upper maximum number in the array\ndef ary_rand(n, lower, upper)\n values_set = (lower..upper).to_a\n repetition = n/(upper-lower+1) + 1\n (values_set*repetition).sample n\nend\n</code></pre>\n\n<h2>Method 2</h2>\n\n<p>Another, possibly <strong>more efficient</strong>, method modified from same Kent's <a href=\"https://stackoverflow.com/a/88341/471214\">another answer</a>:</p>\n\n<pre><code>def ary_rand2(n, lower, upper)\n v = (lower..upper).to_a\n (0...n).map{ v[rand(v.length)] }\nend\n</code></pre>\n\n<h2>Output</h2>\n\n<pre><code>puts (ary_rand 5, 0, 9).to_s # [0, 8, 2, 5, 6] expected\nputs (ary_rand 5, 0, 9).to_s # [7, 8, 2, 4, 3] different result for same params\nputs (ary_rand 5, 0, 1).to_s # [0, 0, 1, 0, 1] repeated values from limited range\nputs (ary_rand 5, 9, 0).to_s # [] no such range :)\n</code></pre>\n"
},
{
"answer_id": 32370822,
"author": "Andrei Madalin Butnaru",
"author_id": 2141840,
"author_profile": "https://Stackoverflow.com/users/2141840",
"pm_score": 1,
"selected": false,
"text": "<p>No loops with this method</p>\n\n<pre><code>Array.new(size) { rand(max) }\n\nrequire 'benchmark'\nmax = 1000000\nsize = 5\nBenchmark.realtime do\n Array.new(size) { rand(max) }\nend\n\n=> 1.9114e-05 \n</code></pre>\n"
},
{
"answer_id": 61862553,
"author": "Eric Mathison",
"author_id": 1133429,
"author_profile": "https://Stackoverflow.com/users/1133429",
"pm_score": 2,
"selected": false,
"text": "<pre><code>[*1..99].sample(4) #=> [64, 99, 29, 49]\n</code></pre>\n\n<p>According to <code>Array#sample</code> docs, </p>\n\n<blockquote>\n <p>The elements are chosen by using random and <strong>unique</strong> indices</p>\n</blockquote>\n\n<p>If you need <code>SecureRandom</code> (which uses computer noise instead of pseudorandom numbers):</p>\n\n<pre><code>require 'securerandom'\n\n[*1..99].sample(4, random: SecureRandom) #=> [2, 75, 95, 37]\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
]
| This is what I have so far:
```
myArray.map!{ rand(max) }
```
Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?
**Edit:**
I'd really like to see this done w/o loop - if at all possible. | This uses Set:
```
require 'set'
def rand_n(n, max)
randoms = Set.new
loop do
randoms << rand(max)
return randoms.to_a if randoms.size >= n
end
end
``` |
119,114 | <p>I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in.</p>
<p>Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling on my home box or not ?</p>
<p>What I am after is a way of defining a symbol, let's call it _ATHOME, automatically so I can do this:</p>
<pre><code>#ifdef _ATHOME
# define TEST_FILES "E:\\Test"
# define TEST_SERVER "192.168.0.1"
#else
# define TEST_FILE "Z:\\Project\\Blah\\Test"
# define TEST_SERVER "212.45.68.43"
#endif
</code></pre>
<p><em>NB: This is for development and debugging purposes of course, I would never release software with hard coded constants like this.</em></p>
| [
{
"answer_id": 119121,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 2,
"selected": false,
"text": "<p>You can set preproccesor variables in the properties->c++->preprocessor<br>\nin visual studio settings you can use $(enviromentvariable)</p>\n"
},
{
"answer_id": 119127,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 1,
"selected": false,
"text": "<p>I generally use config files, then just create a symlink to the appropriate configuration.</p>\n"
},
{
"answer_id": 119148,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 4,
"selected": true,
"text": "<p>On your home and work machines, set an environment variable <code>LOCATION</code> that is either \"1\" for home or \"2\" for work.</p>\n\n<p>Then in the preprocessor options, add a preprocessor define /DLOCATION=$(LOCATION). This will evaluate to either the \"home\" or \"work\" string that you set in the environment variable.</p>\n\n<p>Then in your code:</p>\n\n<pre><code>#if LOCATION==1\n // home\n#else\n // work\n#endif\n</code></pre>\n"
},
{
"answer_id": 121330,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 2,
"selected": false,
"text": "<p>If the only difference between work and home is where the test files are located... then (IMHO) you shouldn't pollute your build files with a bunch of static paths & IPs.</p>\n\n<p>For the example you showed, I would simply map drives on both work and home. I.e. at work map a drive T: that points to \\\\212.45.68.43\\Project\\Blah\\Test, at home map a drive T: that points to \\\\192.168.0.1\\Test. </p>\n\n<p>Then your build process uses the path \"T:\\\" to refer to where tests reside. </p>\n\n<p>Of course, if you need to change something more drastic, setting environment variables is probably the best way to go. </p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
]
| I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in.
Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling on my home box or not ?
What I am after is a way of defining a symbol, let's call it \_ATHOME, automatically so I can do this:
```
#ifdef _ATHOME
# define TEST_FILES "E:\\Test"
# define TEST_SERVER "192.168.0.1"
#else
# define TEST_FILE "Z:\\Project\\Blah\\Test"
# define TEST_SERVER "212.45.68.43"
#endif
```
*NB: This is for development and debugging purposes of course, I would never release software with hard coded constants like this.* | On your home and work machines, set an environment variable `LOCATION` that is either "1" for home or "2" for work.
Then in the preprocessor options, add a preprocessor define /DLOCATION=$(LOCATION). This will evaluate to either the "home" or "work" string that you set in the environment variable.
Then in your code:
```
#if LOCATION==1
// home
#else
// work
#endif
``` |
119,123 | <p>Why does the <code>sizeof</code> operator return a size larger for a structure than the total sizes of the structure's members?</p>
| [
{
"answer_id": 119128,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 11,
"selected": true,
"text": "<p>This is because of padding added to satisfy alignment constraints. <a href=\"http://en.wikipedia.org/wiki/Data_structure_alignment\" rel=\"noreferrer\">Data structure alignment</a> impacts both performance and correctness of programs:</p>\n\n<ul>\n<li>Mis-aligned access might be a hard error (often <code>SIGBUS</code>).</li>\n<li>Mis-aligned access might be a soft error.\n\n<ul>\n<li>Either corrected in hardware, for a modest performance-degradation.</li>\n<li>Or corrected by emulation in software, for a severe performance-degradation.</li>\n<li>In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors.</li>\n</ul></li>\n</ul>\n\n<p>Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):</p>\n\n<pre><code>struct X\n{\n short s; /* 2 bytes */\n /* 2 padding bytes */\n int i; /* 4 bytes */\n char c; /* 1 byte */\n /* 3 padding bytes */\n};\n\nstruct Y\n{\n int i; /* 4 bytes */\n char c; /* 1 byte */\n /* 1 padding byte */\n short s; /* 2 bytes */\n};\n\nstruct Z\n{\n int i; /* 4 bytes */\n short s; /* 2 bytes */\n char c; /* 1 byte */\n /* 1 padding byte */\n};\n\nconst int sizeX = sizeof(struct X); /* = 12 */\nconst int sizeY = sizeof(struct Y); /* = 8 */\nconst int sizeZ = sizeof(struct Z); /* = 8 */\n</code></pre>\n\n<p>One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure <code>Z</code> in the example above).</p>\n\n<p>IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special <code>#pragma</code> statements to change the structure alignment settings.</p>\n"
},
{
"answer_id": 119132,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 3,
"selected": false,
"text": "<p>It can do so if you have implicitly or explicitly set the alignment of the struct. A struct that is aligned 4 will always be a multiple of 4 bytes even if the size of its members would be something that's not a multiple of 4 bytes.</p>\n\n<p>Also a library may be compiled under x86 with 32-bit ints and you may be comparing its components on a 64-bit process would would give you a different result if you were doing this by hand.</p>\n"
},
{
"answer_id": 119134,
"author": "EmmEff",
"author_id": 9188,
"author_profile": "https://Stackoverflow.com/users/9188",
"pm_score": 8,
"selected": false,
"text": "<p>Packing and byte alignment, as described in the C FAQ <a href=\"http://www.c-faq.com/struct/align.html\" rel=\"noreferrer\">here</a>:</p>\n\n<blockquote>\n <p>It's for alignment. Many processors can't access 2- and 4-byte\n quantities (e.g. ints and long ints) if they're crammed in\n every-which-way.</p>\n \n <p>Suppose you have this structure:</p>\n\n<pre><code>struct {\n char a[3];\n short int b;\n long int c;\n char d[3];\n};\n</code></pre>\n \n <p>Now, you might think that it ought to be possible to pack this\n structure into memory like this:</p>\n\n<pre><code>+-------+-------+-------+-------+\n| a | b |\n+-------+-------+-------+-------+\n| b | c |\n+-------+-------+-------+-------+\n| c | d |\n+-------+-------+-------+-------+\n</code></pre>\n \n <p>But it's much, much easier on the processor if the compiler arranges\n it like this:</p>\n\n<pre><code>+-------+-------+-------+\n| a |\n+-------+-------+-------+\n| b |\n+-------+-------+-------+-------+\n| c |\n+-------+-------+-------+-------+\n| d |\n+-------+-------+-------+\n</code></pre>\n \n <p>In the packed version, notice how it's at least a little bit hard for\n you and me to see how the b and c fields wrap around? In a nutshell,\n it's hard for the processor, too. Therefore, most compilers will pad\n the structure (as if with extra, invisible fields) like this:</p>\n\n<pre><code>+-------+-------+-------+-------+\n| a | pad1 |\n+-------+-------+-------+-------+\n| b | pad2 |\n+-------+-------+-------+-------+\n| c |\n+-------+-------+-------+-------+\n| d | pad3 |\n+-------+-------+-------+-------+\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 119144,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 4,
"selected": false,
"text": "<p>This can be due to byte alignment and padding so that the structure comes out to an even number of bytes (or words) on your platform. For example in C on Linux, the following 3 structures:</p>\n\n<pre><code>#include \"stdio.h\"\n\n\nstruct oneInt {\n int x;\n};\n\nstruct twoInts {\n int x;\n int y;\n};\n\nstruct someBits {\n int x:2;\n int y:6;\n};\n\n\nint main (int argc, char** argv) {\n printf(\"oneInt=%zu\\n\",sizeof(struct oneInt));\n printf(\"twoInts=%zu\\n\",sizeof(struct twoInts));\n printf(\"someBits=%zu\\n\",sizeof(struct someBits));\n return 0;\n}\n</code></pre>\n\n<p>Have members who's sizes (in bytes) are 4 bytes (32 bits), 8 bytes (2x 32 bits) and 1 byte (2+6 bits) respectively. The above program (on Linux using gcc) prints the sizes as 4, 8, and 4 - where the last structure is padded so that it is a single word (4 x 8 bit bytes on my 32bit platform).</p>\n\n<pre><code>oneInt=4\ntwoInts=8\nsomeBits=4\n</code></pre>\n"
},
{
"answer_id": 119491,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 5,
"selected": false,
"text": "<p>If you want the structure to have a certain size with GCC for example use <a href=\"http://digitalvampire.org/blog/index.php/2006/07/31/why-you-shouldnt-use-__attribute__packed/\" rel=\"noreferrer\"><code>__attribute__((packed))</code></a>.</p>\n\n<p>On Windows you can set the alignment to one byte when using the cl.exe compier with the <a href=\"http://msdn.microsoft.com/en-us/library/xh3e3fd0(VS.80).aspx\" rel=\"noreferrer\">/Zp option</a>.</p>\n\n<p>Usually it is easier for the CPU to access data that is a multiple of 4 (or 8), depending platform and also on the compiler.</p>\n\n<p>So it is a matter of alignment basically.</p>\n\n<p><strong>You need to have good reasons to change it.</strong></p>\n"
},
{
"answer_id": 121049,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to the other answers, a struct can (but usually doesn't) have virtual functions, in which case the size of the struct will also include the space for the vtbl.</p>\n"
},
{
"answer_id": 6185547,
"author": "lkanab",
"author_id": 724291,
"author_profile": "https://Stackoverflow.com/users/724291",
"pm_score": 4,
"selected": false,
"text": "<p>See also:</p>\n<p>for Microsoft Visual C:</p>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.80%29.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.80%29.aspx</a></p>\n<p>and GCC claim compatibility with Microsoft's compiler.:</p>\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Structure_002dPacking-Pragmas.html\" rel=\"nofollow noreferrer\">https://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Structure_002dPacking-Pragmas.html</a></p>\n<p>In addition to the previous answers, please note that regardless the packaging, <strong>there is no members-order-guarantee in C++</strong>. Compilers may (and certainly do) add virtual table pointer and base structures' members to the structure. Even the existence of virtual table is not ensured by the standard (virtual mechanism implementation is not specified) and therefore one can conclude that such guarantee is just impossible.</p>\n<p>I'm quite sure <strong>member-order <em>is</em> guaranteed in C</strong>, but I wouldn't count on it, when writing a cross-platform or cross-compiler program.</p>\n"
},
{
"answer_id": 30760303,
"author": "sid1138",
"author_id": 4995406,
"author_profile": "https://Stackoverflow.com/users/4995406",
"pm_score": 3,
"selected": false,
"text": "<p>The size of a structure is greater than the sum of its parts because of what is called packing. A particular processor has a preferred data size that it works with. Most modern processors' preferred size if 32-bits (4 bytes). Accessing the memory when data is on this kind of boundary is more efficient than things that straddle that size boundary.</p>\n\n<p>For example. Consider the simple structure:</p>\n\n<pre><code>struct myStruct\n{\n int a;\n char b;\n int c;\n} data;\n</code></pre>\n\n<p>If the machine is a 32-bit machine and data is aligned on a 32-bit boundary, we see an immediate problem (assuming no structure alignment). In this example, let us assume that the structure data starts at address 1024 (0x400 - note that the lowest 2 bits are zero, so the data is aligned to a 32-bit boundary). The access to data.a will work fine because it starts on a boundary - 0x400. The access to data.b will also work fine, because it is at address 0x404 - another 32-bit boundary. But an unaligned structure would put data.c at address 0x405. The 4 bytes of data.c are at 0x405, 0x406, 0x407, 0x408. On a 32-bit machine, the system would read data.c during one memory cycle, but would only get 3 of the 4 bytes (the 4th byte is on the next boundary). So, the system would have to do a second memory access to get the 4th byte,</p>\n\n<p>Now, if instead of putting data.c at address 0x405, the compiler padded the structure by 3 bytes and put data.c at address 0x408, then the system would only need 1 cycle to read the data, cutting access time to that data element by 50%. Padding swaps memory efficiency for processing efficiency. Given that computers can have huge amounts of memory (many gigabytes), the compilers feel that the swap (speed over size) is a reasonable one.</p>\n\n<p>Unfortunately, this problem becomes a killer when you attempt to send structures over a network or even write the binary data to a binary file. The padding inserted between elements of a structure or class can disrupt the data sent to the file or network. In order to write portable code (one that will go to several different compilers), you will probably have to access each element of the structure separately to ensure the proper \"packing\".</p>\n\n<p>On the other hand, different compilers have different abilities to manage data structure packing. For example, in Visual C/C++ the compiler supports the #pragma pack command. This will allow you to adjust data packing and alignment.</p>\n\n<p>For example:</p>\n\n<pre><code>#pragma pack 1\nstruct MyStruct\n{\n int a;\n char b;\n int c;\n short d;\n} myData;\n\nI = sizeof(myData);\n</code></pre>\n\n<p>I should now have the length of 11. Without the pragma, I could be anything from 11 to 14 (and for some systems, as much as 32), depending on the default packing of the compiler.</p>\n"
},
{
"answer_id": 31687400,
"author": "Konstantin Burlachenko",
"author_id": 1154447,
"author_profile": "https://Stackoverflow.com/users/1154447",
"pm_score": 3,
"selected": false,
"text": "<p><strong>C language leaves compiler some freedom about the location of the structural elements in the memory:</strong></p>\n\n<ul>\n<li>memory holes may appear between any two components, and after the last component. It was due to the fact that certain types of objects on the target computer may be limited by the boundaries of addressing</li>\n<li>\"memory holes\" size included in the result of sizeof operator. The sizeof only doesn't include size of the flexible array, which is available in C/C++</li>\n<li>Some implementations of the language allow you to control the memory layout of structures through the pragma and compiler options</li>\n</ul>\n\n<p><strong>The C language provides some assurance to the programmer of the elements layout in the structure:</strong></p>\n\n<ul>\n<li>compilers required to assign a sequence of components increasing memory addresses</li>\n<li>Address of the first component coincides with the start address of the structure</li>\n<li>unnamed bit fields may be included in the structure to the required address alignments of adjacent elements</li>\n</ul>\n\n<p><strong>Problems related to the elements alignment:</strong></p>\n\n<ul>\n<li>Different computers line the edges of objects in different ways</li>\n<li>Different restrictions on the width of the bit field</li>\n<li>Computers differ on how to store the bytes in a word (Intel 80x86 and Motorola 68000)</li>\n</ul>\n\n<p><strong>How alignment works:</strong></p>\n\n<ul>\n<li>The volume occupied by the structure is calculated as the size of the aligned single element of an array of such structures. The structure should\nend so that the first element of the next following structure does not the violate requirements of alignment</li>\n</ul>\n\n<p>p.s More detailed info are available here: \"Samuel P.Harbison, Guy L.Steele C A Reference, (5.6.2 - 5.6.7)\"</p>\n"
},
{
"answer_id": 35595109,
"author": "DigitalRoss",
"author_id": 140740,
"author_profile": "https://Stackoverflow.com/users/140740",
"pm_score": 3,
"selected": false,
"text": "<p>The idea is that for speed and cache considerations, operands should be read from addresses aligned to their natural size. To make this happen, the compiler pads structure members so the following member or following struct will be aligned.</p>\n\n<pre><code>struct pixel {\n unsigned char red; // 0\n unsigned char green; // 1\n unsigned int alpha; // 4 (gotta skip to an aligned offset)\n unsigned char blue; // 8 (then skip 9 10 11)\n};\n\n// next offset: 12\n</code></pre>\n\n<p>The x86 architecture has always been able to fetch misaligned addresses. However, it's slower and when the misalignment overlaps two different cache lines, then it evicts two cache lines when an aligned access would only evict one.</p>\n\n<p>Some architectures actually have to trap on misaligned reads and writes, and early versions of the ARM architecture (the one that evolved into all of today's mobile CPUs) ... well, they actually just returned bad data on for those. (They ignored the low-order bits.)</p>\n\n<p>Finally, note that cache lines can be arbitrarily large, and the compiler doesn't attempt to guess at those or make a space-vs-speed tradeoff. Instead, the alignment decisions are part of the ABI and represent the minimum alignment that will eventually evenly fill up a cache line. </p>\n\n<p><em>TL;DR:</em> alignment is important.</p>\n"
},
{
"answer_id": 37032302,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 3,
"selected": false,
"text": "<p><strong>C99 N1256 standard draft</strong></p>\n<p><a href=\"http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf\" rel=\"nofollow noreferrer\">http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf</a></p>\n<p><em>6.5.3.4 The sizeof operator</em>:</p>\n<blockquote>\n<p>3 When applied to an operand that has structure or union type,\nthe result is the total number of bytes in such an object,\nincluding internal and trailing padding.</p>\n</blockquote>\n<p><em>6.7.2.1 Structure and union specifiers</em>:</p>\n<blockquote>\n<p>13 ... There may be unnamed\npadding within a structure object, but not at its beginning.</p>\n</blockquote>\n<p>and:</p>\n<blockquote>\n<p>15 There may be unnamed padding at the end of a structure or union.</p>\n</blockquote>\n<p>The new C99 <a href=\"https://en.wikipedia.org/wiki/Flexible_array_member\" rel=\"nofollow noreferrer\">flexible array member feature</a> (<code>struct S {int is[];};</code>) may also affect padding:</p>\n<blockquote>\n<p>16 As a special case, the last element of a structure with more than one named member may\nhave an incomplete array type; this is called a flexible array member. In most situations,\nthe flexible array member is ignored. In particular, the size of the structure is as if the\nflexible array member were omitted except that it may have more trailing padding than\nthe omission would imply.</p>\n</blockquote>\n<p><em>Annex J Portability Issues</em> reiterates:</p>\n<blockquote>\n<p>The following are unspecified: ...</p>\n<ul>\n<li>The value of padding bytes when storing values in structures or unions (6.2.6.1)</li>\n</ul>\n</blockquote>\n<p><strong>C++11 N3337 standard draft</strong></p>\n<p><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf\" rel=\"nofollow noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf</a></p>\n<p><em>5.3.3 Sizeof</em>:</p>\n<blockquote>\n<p>2 When applied\nto a class, the result is the number of bytes in an object of that class including any padding required for\nplacing objects of that type in an array.</p>\n</blockquote>\n<p><em>9.2 Class members</em>:</p>\n<blockquote>\n<p>A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its\ninitial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note:\nThere might therefore be unnamed padding within a standard-layout struct object, but not at its beginning,\nas necessary to achieve appropriate alignment. — end note ]</p>\n</blockquote>\n<p>I only know enough C++ to understand the note :-)</p>\n"
},
{
"answer_id": 62640093,
"author": "RobertS supports Monica Cellio",
"author_id": 12139179,
"author_profile": "https://Stackoverflow.com/users/12139179",
"pm_score": 2,
"selected": false,
"text": "<p>Among the other well-explained answers about memory alignment and structure padding/packing, there is something which I have discovered in the question itself by reading it carefully.</p>\n<blockquote>\n<p>"<em>Why isn't <code>sizeof</code> for a struct equal to the sum of <code>sizeof</code> of each member?</em>"</p>\n<p>"<em>Why does the <code>sizeof</code> operator return a size larger for a structure than the total sizes of the structure's members</em>"?</p>\n</blockquote>\n<p>Both questions suggest something what is plain wrong. At least in a generic, non-example focused view, which is the case here.</p>\n<p>The result of the <code>sizeof</code> operand applied to a structure object <strong>can</strong> be equal to the sum of <code>sizeof</code> applied to each member separately. It doesn't <strong>have to</strong> be larger/different.</p>\n<p>If there is no reason for padding, no memory will be padded.</p>\n<hr />\n<p>One most implementations, if the structure contains only members of the same type:</p>\n<pre><code>struct foo {\n int a; \n int b;\n int c; \n} bar;\n</code></pre>\n<p>Assuming <code>sizeof(int) == 4</code>, the size of the structure <code>bar</code> will be equal to the sum of the sizes of all members together, <code>sizeof(bar) == 12</code>. No padding done here.</p>\n<p>Same goes for example here:</p>\n<pre><code>struct foo {\n short int a; \n short int b;\n int c; \n} bar;\n</code></pre>\n<p>Assuming <code>sizeof(short int) == 2</code> and <code>sizeof(int) == 4</code>. The sum of allocated bytes for <code>a</code> and <code>b</code> is equal to the allocated bytes for <code>c</code>, the largest member and with that everything is perfectly aligned. Thus, <code>sizeof(bar) == 8</code>.</p>\n<p>This is also object of the second most popular question regarding structure padding, here:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5435841/memory-alignment-in-c-structs\">Memory alignment in C-structs</a></li>\n</ul>\n"
},
{
"answer_id": 72010091,
"author": "Zrn-dev",
"author_id": 14265581,
"author_profile": "https://Stackoverflow.com/users/14265581",
"pm_score": 0,
"selected": false,
"text": "<p>given a lot information(explanation) above.</p>\n<p>And, I just would like to share some method in order to solve this issue.</p>\n<p>You can avoid it by adding pragma pack</p>\n<pre><code>#pragma pack(push, 1)\n\n// your structure\n\n#pragma pack(pop) \n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6386/"
]
| Why does the `sizeof` operator return a size larger for a structure than the total sizes of the structure's members? | This is because of padding added to satisfy alignment constraints. [Data structure alignment](http://en.wikipedia.org/wiki/Data_structure_alignment) impacts both performance and correctness of programs:
* Mis-aligned access might be a hard error (often `SIGBUS`).
* Mis-aligned access might be a soft error.
+ Either corrected in hardware, for a modest performance-degradation.
+ Or corrected by emulation in software, for a severe performance-degradation.
+ In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors.
Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):
```
struct X
{
short s; /* 2 bytes */
/* 2 padding bytes */
int i; /* 4 bytes */
char c; /* 1 byte */
/* 3 padding bytes */
};
struct Y
{
int i; /* 4 bytes */
char c; /* 1 byte */
/* 1 padding byte */
short s; /* 2 bytes */
};
struct Z
{
int i; /* 4 bytes */
short s; /* 2 bytes */
char c; /* 1 byte */
/* 1 padding byte */
};
const int sizeX = sizeof(struct X); /* = 12 */
const int sizeY = sizeof(struct Y); /* = 8 */
const int sizeZ = sizeof(struct Z); /* = 8 */
```
One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure `Z` in the example above).
IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special `#pragma` statements to change the structure alignment settings. |
119,160 | <p>What is the difference between this:</p>
<pre><code>this.btnOk.Click += new System.EventHandler(this.btnOK_Click);
</code></pre>
<p>and this?</p>
<pre><code>this.btnOk.Click += this.btnOK_Click;
</code></pre>
<p>They both work. The former is what Visual Studio defaults to when you use the snippets. But it seems like it only ads extra verbiage, or am I missing something?</p>
| [
{
"answer_id": 119162,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 1,
"selected": false,
"text": "<p>I believe that C# since 3.0 has implicitly added the delegate handler. However, it can help to be more explicit, especially when there are multiple possible delegate types.</p>\n"
},
{
"answer_id": 119164,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>\"+= Delegate_Name\" is a syntax sugar. Compiler will create new wrapper for you. </p>\n"
},
{
"answer_id": 119169,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 4,
"selected": true,
"text": "<p>No difference. Omitting the delegate instantiation is just syntax candy; the C# compiler will generate the delegate instantiation for you under the hood.</p>\n"
},
{
"answer_id": 119170,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 2,
"selected": false,
"text": "<p>In C# 3.0 and later this is no difference. Before C# 3.0 EventHandlers were required due to compiler limitations, but with the advent of C# 3.0, the second form is preferred unless you want to be very explicit.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
]
| What is the difference between this:
```
this.btnOk.Click += new System.EventHandler(this.btnOK_Click);
```
and this?
```
this.btnOk.Click += this.btnOK_Click;
```
They both work. The former is what Visual Studio defaults to when you use the snippets. But it seems like it only ads extra verbiage, or am I missing something? | No difference. Omitting the delegate instantiation is just syntax candy; the C# compiler will generate the delegate instantiation for you under the hood. |
119,167 | <p>I'm taking a look at how the model system in django works and I noticed something that I don't understand.</p>
<p>I know that you create an empty <code>__init__.py</code> file to specify that the current directory is a package. And that you can set some variable in <code>__init__.py</code> so that import * works properly.</p>
<p>But django adds a bunch of from ... import ... statements and defines a bunch of classes in <code>__init__.py</code>. Why? Doesn't this just make things look messy? Is there a reason that requires this code in <code>__init__.py</code>?</p>
| [
{
"answer_id": 119178,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 7,
"selected": true,
"text": "<p>All imports in <code>__init__.py</code> are made available when you import the package (directory) that contains it.</p>\n\n<p>Example:</p>\n\n<p><code>./dir/__init__.py</code>:</p>\n\n<pre><code>import something\n</code></pre>\n\n<p><code>./test.py</code>:</p>\n\n<pre><code>import dir\n# can now use dir.something\n</code></pre>\n\n<p>EDIT: forgot to mention, the code in <code>__init__.py</code> runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code.</p>\n\n<p>EDIT2: dgrant pointed out to a possible confusion in my example. In <code>__init__.py</code> <code>import something</code> can import any module, not necessary from the package. For example, we can replace it with <code>import datetime</code>, then in our top level <code>test.py</code> both of these snippets will work:</p>\n\n<pre><code>import dir\nprint dir.datetime.datetime.now()\n</code></pre>\n\n<p>and</p>\n\n<pre><code>import dir.some_module_in_dir\nprint dir.datetime.datetime.now()\n</code></pre>\n\n<p>The bottom line is: all names assigned in <code>__init__.py</code>, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.</p>\n"
},
{
"answer_id": 119346,
"author": "dgrant",
"author_id": 9484,
"author_profile": "https://Stackoverflow.com/users/9484",
"pm_score": 5,
"selected": false,
"text": "<p>It's just personal preference really, and has to do with the layout of your python modules.</p>\n\n<p>Let's say you have a module called <code>erikutils</code>. There are two ways that it can be a module, either you have a file called <em>erikutils.py</em> on your <code>sys.path</code> or you have a directory called <em>erikutils</em> on your <code>sys.path</code> with an empty <em><code>__init__.py</code></em> file inside it. Then let's say you have a bunch of modules called <code>fileutils</code>, <code>procutils</code>, <code>parseutils</code> and you want those to be sub-modules under <code>erikutils</code>. So you make some .py files called <em>fileutils.py</em>, <em>procutils.py</em>, and <em>parseutils.py</em>:</p>\n\n<pre><code>erikutils\n __init__.py\n fileutils.py\n procutils.py\n parseutils.py\n</code></pre>\n\n<p>Maybe you have a few functions that just don't belong in the <code>fileutils</code>, <code>procutils</code>, or <code>parseutils</code> modules. And let's say you don't feel like creating a new module called <code>miscutils</code>. AND, you'd like to be able to call the function like so:</p>\n\n<pre><code>erikutils.foo()\nerikutils.bar()\n</code></pre>\n\n<p>rather than doing</p>\n\n<pre><code>erikutils.miscutils.foo()\nerikutils.miscutils.bar()\n</code></pre>\n\n<p>So because the <code>erikutils</code> module is a directory, not a file, we have to define it's functions inside the <em><code>__init__.py</code></em> file.</p>\n\n<p>In django, the best example I can think of is <code>django.db.models.fields</code>. ALL the django *Field classes are defined in the <em><code>__init__.py</code></em> file in the <em>django/db/models/fields</em> directory. I guess they did this because they didn't want to cram everything into a hypothetical <em>django/db/models/fields.py</em> model, so they split it out into a few submodules (<em>related.py</em>, <em>files.py</em>, for example) and they stuck the made *Field definitions in the fields module itself (hence, <em><code>__init__.py</code></em>).</p>\n"
},
{
"answer_id": 126499,
"author": "nikow",
"author_id": 11992,
"author_profile": "https://Stackoverflow.com/users/11992",
"pm_score": 5,
"selected": false,
"text": "<p>Using the <code>__init__.py</code> file allows you to make the internal package structure invisible from the outside. If the internal structure changes (e.g. because you split one fat module into two) you only have to adjust the <code>__init__.py</code> file, but not the code that depends on the package. You can also make parts of your package invisible, e.g. if they are not ready for general usage.</p>\n\n<p>Note that you can use the <code>del</code> command, so a typical <code>__init__.py</code> may look like this:</p>\n\n<pre><code>from somemodule import some_function1, some_function2, SomeObject\n\ndel somemodule\n</code></pre>\n\n<p>Now if you decide to split <code>somemodule</code> the new <code>__init__.py</code> might be:</p>\n\n<pre><code>from somemodule1 import some_function1, some_function2\nfrom somemodule2 import SomeObject\n\ndel somemodule1\ndel somemodule2\n</code></pre>\n\n<p>From the outside the package still looks exactly as before.</p>\n"
},
{
"answer_id": 73379400,
"author": "joepitz1",
"author_id": 4495533,
"author_profile": "https://Stackoverflow.com/users/4495533",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<p>"We recommend not putting much code in an <code>__init__.py</code> file, though. Programmers do not expect actual logic to happen in this file, and much like with <code>from x import *</code>, it can trip them up if they are looking for the declaration of a particular piece of code and can't find it until they check <code>__init__.py</code>. "</p>\n<p>-- Python Object-Oriented Programming Fourth Edition Steven F. Lott Dusty Phillips</p>\n</blockquote>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3935/"
]
| I'm taking a look at how the model system in django works and I noticed something that I don't understand.
I know that you create an empty `__init__.py` file to specify that the current directory is a package. And that you can set some variable in `__init__.py` so that import \* works properly.
But django adds a bunch of from ... import ... statements and defines a bunch of classes in `__init__.py`. Why? Doesn't this just make things look messy? Is there a reason that requires this code in `__init__.py`? | All imports in `__init__.py` are made available when you import the package (directory) that contains it.
Example:
`./dir/__init__.py`:
```
import something
```
`./test.py`:
```
import dir
# can now use dir.something
```
EDIT: forgot to mention, the code in `__init__.py` runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code.
EDIT2: dgrant pointed out to a possible confusion in my example. In `__init__.py` `import something` can import any module, not necessary from the package. For example, we can replace it with `import datetime`, then in our top level `test.py` both of these snippets will work:
```
import dir
print dir.datetime.datetime.now()
```
and
```
import dir.some_module_in_dir
print dir.datetime.datetime.now()
```
The bottom line is: all names assigned in `__init__.py`, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package. |
119,168 | <p>I have a datagridview assigned a datasource to it. now how to add a new row to that grid and remove a row from it?</p>
| [
{
"answer_id": 119175,
"author": "Joe Phillips",
"author_id": 20471,
"author_profile": "https://Stackoverflow.com/users/20471",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you'll have to get the Table collection item and retrieve the Row collection item from that. Then you can loop through the rows or however you want to remove the row.</p>\n\n<p>You do this after binding it, of course.</p>\n"
},
{
"answer_id": 119337,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 3,
"selected": false,
"text": "<p>One way to do this is as follows:</p>\n\n<p><strong>Step #1</strong> Setup the Data Adapter, Data Grid etc:</p>\n\n<pre><code>// the data grid\nDataGridView dataGrid;\n\n// create a new data table\nDataTable table = new DataTable();\n\n// create the data adapter\nSqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strDSN);\n\n// populate the table using the SQL adapter\ndataAdapter.Fill(table);\n\n// bind the table to a data source\nBindingSource dbSource = new BindingSource();\ndbSource.DataSource = table;\n\n// finally bind the data source to the grid\ndataGrid.DataSource = dbSource;\n</code></pre>\n\n<p><strong>Step #2</strong> Setup the Data Adapter SQL Commands:</p>\n\n<p>These SQL commands define how to move the data between the grid and the database via the adapter.</p>\n\n<pre><code>dataAdapter.DeleteCommand = new SqlCommand(...);\n\ndataAdapter.InsertCommand = new SqlCommand(...);\n\ndataAdapter.UpdateCommand = new SqlCommand(...);\n</code></pre>\n\n<p><strong>Step #3</strong> Code to Remove Select lines from the Data Grid:</p>\n\n<pre><code>public int DeleteSelectedItems()\n{\n int itemsDeleted = 0;\n\n int count = dataGrid.RowCount;\n\n for (int i = count - 1; i >=0; --i)\n {\n DataGridViewRow row = dataGrid.Rows[i];\n\n if (row.Selected == true)\n {\n dataGrid.Rows.Remove(row);\n\n // count the item deleted\n ++itemsDeleted;\n }\n }\n\n // commit the deletes made\n if (itemsDeleted > 0) Commit();\n}\n</code></pre>\n\n<p><strong>Step #4</strong> Handling Row Inserts and Row Changes:</p>\n\n<p>These types of changes are relatively easy to implement as you can let the grid manage the cell changes and new row inserts. </p>\n\n<p>The only thing you will have to decide is when do you commit these changes. </p>\n\n<p>I would recomment putting the commit in the <strong>RowValidated</strong> event handler of the DataGridView as at that point you should have a full row of data.</p>\n\n<p><strong>Step #5</strong> Commit Method to Save the Changes back to the Database:</p>\n\n<p>This function will handle all the pending updates, insert and deletes and move these changes from the grid back into the database.</p>\n\n<pre><code>public void Commit()\n{\n SqlConnection cn = new SqlConnection();\n\n cn.ConnectionString = \"Do the connection using a DSN\";\n\n // open the connection\n cn.Open();\n\n // commit any data changes\n dataAdapter.DeleteCommand.Connection = cn;\n dataAdapter.InsertCommand.Connection = cn;\n dataAdapter.UpdateCommand.Connection = cn;\n dataAdapter.Update(table);\n dataAdapter.DeleteCommand.Connection = null;\n dataAdapter.InsertCommand.Connection = null;\n dataAdapter.UpdateCommand.Connection = null;\n\n // clean up\n cn.Close();\n}\n</code></pre>\n"
},
{
"answer_id": 119378,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 0,
"selected": false,
"text": "<p>Property \"Rows\" in GridView has not a Delete method, than you can't delete a row directly. You must delete item from your datasource, than remake DataBind. You can also set Visibile = false to that row, so it will appear \"deleted\" to the user.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a datagridview assigned a datasource to it. now how to add a new row to that grid and remove a row from it? | One way to do this is as follows:
**Step #1** Setup the Data Adapter, Data Grid etc:
```
// the data grid
DataGridView dataGrid;
// create a new data table
DataTable table = new DataTable();
// create the data adapter
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strDSN);
// populate the table using the SQL adapter
dataAdapter.Fill(table);
// bind the table to a data source
BindingSource dbSource = new BindingSource();
dbSource.DataSource = table;
// finally bind the data source to the grid
dataGrid.DataSource = dbSource;
```
**Step #2** Setup the Data Adapter SQL Commands:
These SQL commands define how to move the data between the grid and the database via the adapter.
```
dataAdapter.DeleteCommand = new SqlCommand(...);
dataAdapter.InsertCommand = new SqlCommand(...);
dataAdapter.UpdateCommand = new SqlCommand(...);
```
**Step #3** Code to Remove Select lines from the Data Grid:
```
public int DeleteSelectedItems()
{
int itemsDeleted = 0;
int count = dataGrid.RowCount;
for (int i = count - 1; i >=0; --i)
{
DataGridViewRow row = dataGrid.Rows[i];
if (row.Selected == true)
{
dataGrid.Rows.Remove(row);
// count the item deleted
++itemsDeleted;
}
}
// commit the deletes made
if (itemsDeleted > 0) Commit();
}
```
**Step #4** Handling Row Inserts and Row Changes:
These types of changes are relatively easy to implement as you can let the grid manage the cell changes and new row inserts.
The only thing you will have to decide is when do you commit these changes.
I would recomment putting the commit in the **RowValidated** event handler of the DataGridView as at that point you should have a full row of data.
**Step #5** Commit Method to Save the Changes back to the Database:
This function will handle all the pending updates, insert and deletes and move these changes from the grid back into the database.
```
public void Commit()
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Do the connection using a DSN";
// open the connection
cn.Open();
// commit any data changes
dataAdapter.DeleteCommand.Connection = cn;
dataAdapter.InsertCommand.Connection = cn;
dataAdapter.UpdateCommand.Connection = cn;
dataAdapter.Update(table);
dataAdapter.DeleteCommand.Connection = null;
dataAdapter.InsertCommand.Connection = null;
dataAdapter.UpdateCommand.Connection = null;
// clean up
cn.Close();
}
``` |
119,197 | <p>I have a question about how to do something "The Rails Way". With an application that has a public facing side and an admin interface what is the general consensus in the Rails community on how to do it?</p>
<p>Namespaces, subdomains or forego them altogether?</p>
| [
{
"answer_id": 119301,
"author": "psst",
"author_id": 6392,
"author_profile": "https://Stackoverflow.com/users/6392",
"pm_score": 3,
"selected": false,
"text": "<p>In some smaller applications I don't think you need to separate the admin interface. Just use the regular interface and add admin functionality for logged in users.</p>\n\n<p>In bigger projects, I would go with a namespace. Using a subdomain doesn't feel right to me for some reason.</p>\n"
},
{
"answer_id": 120168,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 6,
"selected": true,
"text": "<p>There's no real \"Rails way\" for admin interfaces, actually - you can find every possible solution in a number of applications. DHH has implied that he prefers namespaces (with HTTP Basic authentication), but that has remained a simple implication and not one of the official Rails Opinions.</p>\n\n<p>That said, I've found good success with that approach lately (namespacing + HTTP Basic). It looks like this:</p>\n\n<p>routes.rb:</p>\n\n<pre><code>map.namespace :admin do |admin|\n admin.resources :users\n admin.resources :posts\nend\n</code></pre>\n\n<p>admin/users_controller.rb:</p>\n\n<pre><code>class Admin::UsersController < ApplicationController\n before_filter :admin_required\n # ...\nend\n</code></pre>\n\n<p>application.rb</p>\n\n<pre><code>class ApplicationController < ActionController::Base\n # ...\n\n protected\n def admin_required\n authenticate_or_request_with_http_basic do |user_name, password|\n user_name == 'admin' && password == 's3cr3t'\n end if RAILS_ENV == 'production' || params[:admin_http]\n end\nend\n</code></pre>\n\n<p>The conditional on <code>authenticate_or_request_with_http_basic</code> triggers the HTTP Basic auth in production mode or when you append <code>?admin_http=true</code> to any URL, so you can test it in your functional tests and by manually updating the URL as you browse your development site.</p>\n"
},
{
"answer_id": 121870,
"author": "Carlos ",
"author_id": 20899,
"author_profile": "https://Stackoverflow.com/users/20899",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to everyone that answered my question. Looks like the consensus is to use namespaces if you want to as there is no DHH sponsored Rails Way approach. :)</p>\n\n<p>Again, thanks all!</p>\n"
},
{
"answer_id": 7678441,
"author": "Adit Saxena",
"author_id": 906787,
"author_profile": "https://Stackoverflow.com/users/906787",
"pm_score": 0,
"selected": false,
"text": "<p>Its surely late for a reply, but i really needed an answer to this question: how to easily do admin areas?</p>\n\n<p>Here is what can be used these days: <a href=\"http://activeadmin.info/\" rel=\"nofollow\">Active Admin</a>, with <a href=\"http://railscasts.com/episodes/284-active-admin\" rel=\"nofollow\">Ryan Bates's great intro</a>.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20899/"
]
| I have a question about how to do something "The Rails Way". With an application that has a public facing side and an admin interface what is the general consensus in the Rails community on how to do it?
Namespaces, subdomains or forego them altogether? | There's no real "Rails way" for admin interfaces, actually - you can find every possible solution in a number of applications. DHH has implied that he prefers namespaces (with HTTP Basic authentication), but that has remained a simple implication and not one of the official Rails Opinions.
That said, I've found good success with that approach lately (namespacing + HTTP Basic). It looks like this:
routes.rb:
```
map.namespace :admin do |admin|
admin.resources :users
admin.resources :posts
end
```
admin/users\_controller.rb:
```
class Admin::UsersController < ApplicationController
before_filter :admin_required
# ...
end
```
application.rb
```
class ApplicationController < ActionController::Base
# ...
protected
def admin_required
authenticate_or_request_with_http_basic do |user_name, password|
user_name == 'admin' && password == 's3cr3t'
end if RAILS_ENV == 'production' || params[:admin_http]
end
end
```
The conditional on `authenticate_or_request_with_http_basic` triggers the HTTP Basic auth in production mode or when you append `?admin_http=true` to any URL, so you can test it in your functional tests and by manually updating the URL as you browse your development site. |
119,207 | <p>I'm new to Ruby, and I'm trying the following: </p>
<pre><code>mySet = numOfCuts.times.map{ rand(seqLength) }
</code></pre>
<p>but I get the 'yield called out of block' error. I'm not sure what his means. BTW, this question is part of a more general question I asked <a href="https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby"><strong>here</strong></a>.</p>
| [
{
"answer_id": 119226,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "<p>if \"numOfCuts\" is an integer, </p>\n\n<pre><code>5.times.foo \n</code></pre>\n\n<p>is invalid </p>\n\n<p>\"times\" expects a block. </p>\n\n<pre><code>5.times{ code here } \n</code></pre>\n"
},
{
"answer_id": 119236,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 4,
"selected": true,
"text": "<p>The problem is that the times method expects to get a block that it will yield control to. However you haven't passed a block to it. There are two ways to solve this. The first is to not use times:</p>\n\n<pre><code>mySet = (1..numOfCuts).map{ rand(seqLength) }\n</code></pre>\n\n<p>or else pass a block to it:</p>\n\n<pre><code>mySet = []\nnumOfCuts.times {mySet.push( rand(seqLength) )}\n</code></pre>\n"
},
{
"answer_id": 119249,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 1,
"selected": false,
"text": "<p>You're combining functions that don't seem to make sense -- if numOfCuts is an integer, then just using times and a block will run the block that many times (though it only returns the original integer:</p>\n\n<pre><code>irb(main):089:0> 2.times {|x| puts x}\n0\n1\n2\n</code></pre>\n\n<p>map is a function that works on ranges and arrays and returns an array:</p>\n\n<pre><code>irb(main):092:0> (1..3).map { |x| puts x; x+1 }\n1\n2\n3\n[2, 3, 4]\n</code></pre>\n\n<p>I'm not sure what you're trying to achieve with the code - what are you trying to do? (as opposed to asking specifically about what appears to be invalid syntax)</p>\n"
},
{
"answer_id": 119255,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 0,
"selected": false,
"text": "<p>Integer.times expects a block. The error message means the <code>yield</code> statement inside the <code>times</code> method can not be called because you did not give it a block.</p>\n\n<p>As for your code, I think what you are looking for is a range: </p>\n\n<pre><code>(1..5).map{ do something }\n</code></pre>\n\n<p>Here is thy rubydoc for the <a href=\"http://www.ruby-doc.org/core/classes/Integer.html#M001160\" rel=\"nofollow noreferrer\">Integer.times</a> and <a href=\"http://www.ruby-doc.org/core-1.8.7/classes/Range.html\" rel=\"nofollow noreferrer\">Range</a>.</p>\n"
},
{
"answer_id": 120832,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 1,
"selected": false,
"text": "<p>Bingo, I just found out what this is. Its a JRuby bug. </p>\n\n<p>Under MRI </p>\n\n<pre><code>>> 3.times.map\n=> [0, 1, 2]\n>> \n</code></pre>\n\n<p>Under JRuby</p>\n\n<pre><code>irb(main):001:0> 3.times.map\nLocalJumpError: yield called out of block\n from (irb):2:in `times'\n from (irb):2:in `signal_status'\nirb(main):002:0> \n</code></pre>\n\n<p>Now, I don't know if MRI (the standard Ruby implementation) is doing the right thing here. It probably should complain that this does not make sense, but when n.times is called in MRI it returns an Enumerator, whereas Jruby complains that it needs a block. </p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
]
| I'm new to Ruby, and I'm trying the following:
```
mySet = numOfCuts.times.map{ rand(seqLength) }
```
but I get the 'yield called out of block' error. I'm not sure what his means. BTW, this question is part of a more general question I asked [**here**](https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby). | The problem is that the times method expects to get a block that it will yield control to. However you haven't passed a block to it. There are two ways to solve this. The first is to not use times:
```
mySet = (1..numOfCuts).map{ rand(seqLength) }
```
or else pass a block to it:
```
mySet = []
numOfCuts.times {mySet.push( rand(seqLength) )}
``` |
119,271 | <p>Just wondering if someone could help me with some msbuild scripts that I am trying to write. What I would like to do is copy all the files and sub folders from a folder to another folder using msbuild.</p>
<pre><code>{ProjectName}
|----->Source
|----->Tools
|----->Viewer
|-----{about 5 sub dirs}
</code></pre>
<p>What I need to be able to do is copy all the files and sub folders from the tools folder into the debug folder for the application. This is the code that I have so far.</p>
<pre><code><ItemGroup>
<Viewer Include="..\$(ApplicationDirectory)\Tools\viewer\**\*.*" />
</ItemGroup>
<Target Name="BeforeBuild">
<Copy SourceFiles="@(Viewer)" DestinationFolder="@(Viewer->'$(OutputPath)\\Tools')" />
</Target>
</code></pre>
<p>The build script runs but doesn't copy any of the files or folders.</p>
<p>Thanks</p>
| [
{
"answer_id": 119288,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>Did you try to specify concrete destination directory instead of</p>\n<pre><code>DestinationFolder="@(Viewer->'$(OutputPath)\\\\Tools')" ? \n</code></pre>\n<p>I'm not very proficient with advanced MSBuild syntax, but</p>\n<pre><code>@(Viewer->'$(OutputPath)\\\\Tools') \n</code></pre>\n<p>looks weird to me. Script looks good, so the problem might be in values of <code>$(ApplicationDirectory)</code> and <code>$(OutputPath)</code></p>\n<p>Here is a blog post that might be useful:</p>\n<p><a href=\"https://learn.microsoft.com/en-us/archive/blogs/msbuild/how-to-recursively-copy-files-using-the-copy-task\" rel=\"nofollow noreferrer\">How To: Recursively Copy Files Using the <Copy> Task</a></p>\n"
},
{
"answer_id": 120700,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 6,
"selected": false,
"text": "<p>I think the problem might be in how you're creating your ItemGroup and calling the Copy task. See if this makes sense:</p>\n\n<pre><code><Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n <PropertyGroup>\n <YourDestinationDirectory>..\\SomeDestinationDirectory</YourDestinationDirectory>\n <YourSourceDirectory>..\\SomeSourceDirectory</YourSourceDirectory>\n </PropertyGroup>\n\n <Target Name=\"BeforeBuild\">\n <CreateItem Include=\"$(YourSourceDirectory)\\**\\*.*\">\n <Output TaskParameter=\"Include\" ItemName=\"YourFilesToCopy\" />\n </CreateItem>\n\n <Copy SourceFiles=\"@(YourFilesToCopy)\"\n DestinationFiles=\"@(YourFilesToCopy->'$(YourDestinationDirectory)\\%(RecursiveDir)%(Filename)%(Extension)')\" />\n </Target>\n</Project>\n</code></pre>\n"
},
{
"answer_id": 1993557,
"author": "Denzil Brown",
"author_id": 242509,
"author_profile": "https://Stackoverflow.com/users/242509",
"pm_score": 5,
"selected": false,
"text": "<p>I'm kinda new to MSBuild but I find the EXEC Task handy for situation like these. I came across the same challenge in my project and this worked for me and was much simpler. Someone please let me know if it's not a good practice.</p>\n\n<pre><code><Target Name=\"CopyToDeployFolder\" DependsOnTargets=\"CompileWebSite\">\n <Exec Command=\"xcopy.exe $(OutputDirectory) $(DeploymentDirectory) /e\" WorkingDirectory=\"C:\\Windows\\\" />\n</Target>\n</code></pre>\n"
},
{
"answer_id": 2714234,
"author": "Johan",
"author_id": 4804,
"author_profile": "https://Stackoverflow.com/users/4804",
"pm_score": 1,
"selected": false,
"text": "<p>Personally I have made use of CopyFolder which is part of the SDC Tasks Library.</p>\n\n<p><a href=\"http://sdctasks.codeplex.com/\" rel=\"nofollow noreferrer\">http://sdctasks.codeplex.com/</a></p>\n"
},
{
"answer_id": 13136116,
"author": "amit thakur",
"author_id": 1785119,
"author_profile": "https://Stackoverflow.com/users/1785119",
"pm_score": 4,
"selected": false,
"text": "<pre><code><Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n <PropertyGroup>\n <YourDestinationDirectory>..\\SomeDestinationDirectory</YourDestinationDirectory>\n <YourSourceDirectory>..\\SomeSourceDirectory</YourSourceDirectory>\n </PropertyGroup>\n\n <Target Name=\"BeforeBuild\">\n <CreateItem Include=\"$(YourSourceDirectory)\\**\\*.*\">\n <Output TaskParameter=\"Include\" ItemName=\"YourFilesToCopy\" />\n </CreateItem>\n\n <Copy SourceFiles=\"@(YourFilesToCopy)\"\n DestinationFiles=\"$(YourFilesToCopy)\\%(RecursiveDir)\" />\n </Target>\n</Project>\n</code></pre>\n\n<p><code>\\**\\*.*</code> help to get files from all the folder.\nRecursiveDir help to put all the file in the respective folder...</p>\n"
},
{
"answer_id": 15720600,
"author": "Rodolfo Neuber",
"author_id": 561894,
"author_profile": "https://Stackoverflow.com/users/561894",
"pm_score": 7,
"selected": false,
"text": "<p>I was searching help on this too. It took me a while, but here is what I did that worked really well.</p>\n\n<pre><code><Target Name=\"AfterBuild\">\n <ItemGroup>\n <ANTLR Include=\"..\\Data\\antlrcs\\**\\*.*\" />\n </ItemGroup>\n <Copy SourceFiles=\"@(ANTLR)\" DestinationFolder=\"$(TargetDir)\\%(RecursiveDir)\" SkipUnchangedFiles=\"true\" />\n</Target>\n</code></pre>\n\n<p>This recursively copied the contents of the folder named <code>antlrcs</code> to the <code>$(TargetDir)</code>.</p>\n"
},
{
"answer_id": 33407475,
"author": "PBo",
"author_id": 5262306,
"author_profile": "https://Stackoverflow.com/users/5262306",
"pm_score": 2,
"selected": false,
"text": "<p>This is the example that worked:</p>\n\n<pre><code><Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\n <ItemGroup>\n <MySourceFiles Include=\"c:\\MySourceTree\\**\\*.*\"/>\n </ItemGroup>\n\n <Target Name=\"CopyFiles\">\n <Copy\n SourceFiles=\"@(MySourceFiles)\"\n DestinationFiles=\"@(MySourceFiles->'c:\\MyDestinationTree\\%(RecursiveDir)%(Filename)%(Extension)')\"\n />\n </Target>\n\n</Project>\n</code></pre>\n\n<p>source: <a href=\"https://msdn.microsoft.com/en-us/library/3e54c37h.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/3e54c37h.aspx</a></p>\n"
},
{
"answer_id": 40157299,
"author": "nzrytmn",
"author_id": 3193030,
"author_profile": "https://Stackoverflow.com/users/3193030",
"pm_score": 2,
"selected": false,
"text": "<p>This is copy task i used in my own project, it was working perfectly for me that copies folder with sub folders to destination successfully:</p>\n\n<pre><code><ItemGroup >\n<MyProjectSource Include=\"$(OutputRoot)/MySource/**/*.*\" />\n</ItemGroup>\n\n<Target Name=\"AfterCopy\" AfterTargets=\"WebPublish\">\n<Copy SourceFiles=\"@(MyProjectSource)\" \n OverwriteReadOnlyFiles=\"true\" DestinationFolder=\"$(PublishFolder)api/% (RecursiveDir)\"/>\n</code></pre>\n\n<p></p>\n\n<p>In my case i copied a project's publish folder to another destination folder, i think it is similiar with your case.</p>\n"
},
{
"answer_id": 55887267,
"author": "Shivinder Singh",
"author_id": 11204896,
"author_profile": "https://Stackoverflow.com/users/11204896",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to recursively copy files from one directory to another using MSBuild is using Copy task with SourceFiles and DestinationFiles as parameters. For example - To copy all files from build directory to back up directory will be</p>\n\n<pre><code><PropertyGroup>\n<BuildDirectory Condition=\"'$(BuildDirectory)' == ''\">Build</BuildDirectory>\n<BackupDirectory Condition=\"'$(BackupDiretory)' == ''\">Backup</BackupDirectory>\n</PropertyGroup>\n\n<ItemGroup>\n<AllFiles Include=\"$(MSBuildProjectDirectory)/$(BuildDirectory)/**/*.*\" />\n</ItemGroup>\n\n<Target Name=\"Backup\">\n<Exec Command=\"if not exist $(BackupDirectory) md $(BackupDirectory)\" />\n<Copy SourceFiles=\"@(AllFiles)\" DestinationFiles=\"@(AllFiles-> \n'$(MSBuildProjectDirectory)/$(BackupDirectory)/%(RecursiveDir)/%(Filename)% \n(Extension)')\" />\n</Target>\n</code></pre>\n\n<p>Now in above Copy command all source directories are traversed and files are copied to destination directory.</p>\n"
},
{
"answer_id": 58138939,
"author": "Sergei Ozerov",
"author_id": 7666352,
"author_profile": "https://Stackoverflow.com/users/7666352",
"pm_score": 0,
"selected": false,
"text": "<p>If you are working with typical C++ toolchain, another way to go is to add your files into standard CopyFileToFolders list</p>\n\n<pre><code><ItemGroup>\n <CopyFileToFolders Include=\"materials\\**\\*\">\n <DestinationFolders>$(MainOutputDirectory)\\Resources\\materials\\%(RecursiveDir)</DestinationFolders>\n </CopyFileToFolders>\n</ItemGroup>\n</code></pre>\n\n<p>Besides being simple, this is a nice way to go because CopyFilesToFolders task will generate appropriate inputs, outputs and even <a href=\"https://learn.microsoft.com/en-us/visualstudio/extensibility/visual-cpp-project-extensibility?view=vs-2017#tlog-files\" rel=\"nofollow noreferrer\">TLog files</a> therefore making sure that copy operations will run only when one of the input files has changed or one of the output files is missing. With TLog, Visual Studio will also properly recognize project as \"up to date\" or not (it uses a separate U2DCheck mechanism for that).</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
]
| Just wondering if someone could help me with some msbuild scripts that I am trying to write. What I would like to do is copy all the files and sub folders from a folder to another folder using msbuild.
```
{ProjectName}
|----->Source
|----->Tools
|----->Viewer
|-----{about 5 sub dirs}
```
What I need to be able to do is copy all the files and sub folders from the tools folder into the debug folder for the application. This is the code that I have so far.
```
<ItemGroup>
<Viewer Include="..\$(ApplicationDirectory)\Tools\viewer\**\*.*" />
</ItemGroup>
<Target Name="BeforeBuild">
<Copy SourceFiles="@(Viewer)" DestinationFolder="@(Viewer->'$(OutputPath)\\Tools')" />
</Target>
```
The build script runs but doesn't copy any of the files or folders.
Thanks | I was searching help on this too. It took me a while, but here is what I did that worked really well.
```
<Target Name="AfterBuild">
<ItemGroup>
<ANTLR Include="..\Data\antlrcs\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(ANTLR)" DestinationFolder="$(TargetDir)\%(RecursiveDir)" SkipUnchangedFiles="true" />
</Target>
```
This recursively copied the contents of the folder named `antlrcs` to the `$(TargetDir)`. |
119,278 | <p>I am using informix database, I want a query which you could also generate a row number along with the query</p>
<p>Like</p>
<pre><code>select row_number(),firstName,lastName
from students;
row_number() firstName lastName
1 john mathew
2 ricky pointing
3 sachin tendulkar
</code></pre>
<p>Here firstName, lastName are from Database, where as row number is generated in a query.</p>
| [
{
"answer_id": 120767,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 1,
"selected": false,
"text": "<p>I think the easiest way would be to use the following code and adjust its return accordingly.\n SELECT rowid, * FROM table</p>\n\n<p>It works for me but please note that it will return the row number in the database, not the row number in the query.</p>\n\n<p>P.S. it's an accepted answer from <a href=\"http://www.experts-exchange.com/Database/Informix/Q_23360872.html\" rel=\"nofollow noreferrer\">Experts Exchange</a>.</p>\n"
},
{
"answer_id": 124822,
"author": "RET",
"author_id": 14750,
"author_profile": "https://Stackoverflow.com/users/14750",
"pm_score": 2,
"selected": false,
"text": "<p>You may not be able to use ROWID in a table that's fragmented across multiple DBSpaces, so any solution that uses ROWID is not particularly portable. It's also strongly discouraged.</p>\n\n<p>If you don't have a SERIAL column in your source table (which is a better way of implementing this as a general concept), have a look at \n<a href=\"http://publib.boulder.ibm.com/infocenter/idshelp/v10/topic/com.ibm.sqls.doc/sqls264.htm#sii-02crprc-59441\" rel=\"nofollow noreferrer\">CREATE SEQUENCE</a>, which is more or less the equivalent of an Orrible function that generates unique numbers when SELECTed from (as opposed to SERIAL, which generates the unique number when the row is INSERTed).</p>\n"
},
{
"answer_id": 163014,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 3,
"selected": false,
"text": "<p>The best way is to use a (newly initialized) sequence.</p>\n\n<pre><code>begin work;\ncreate sequence myseq;\nselect myseq.nextval,s.firstName,s.lastName from students s;\ndrop sequence myseq;\ncommit work;\n</code></pre>\n"
},
{
"answer_id": 176873,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Given a table called Table3 with 3 columns:</p>\n\n<pre><code>colnum name datatype\n======= ===== ===\n1 no text;\n2 seq number;\n3 nm text;\n</code></pre>\n\n<p>NOTE:\nseq is a field within the Table that has unique values in ascending order. The numbers do not have to be contiguous.</p>\n\n<p>Here is query to return a rownumber (RowNum) along with query result </p>\n\n<pre><code>SELECT table3.no, table3.seq, Table3.nm,\n (SELECT COUNT(*) FROM Table3 AS Temp\n WHERE Temp.seq < Table3.seq) + 1 AS RowNum\n FROM Table3;\n</code></pre>\n"
},
{
"answer_id": 51661361,
"author": "Jhollman",
"author_id": 2000656,
"author_profile": "https://Stackoverflow.com/users/2000656",
"pm_score": 0,
"selected": false,
"text": "<p>I know its an old question, but since i just faced this problem and got a soultion not mentioned here, i tough i could share it, so here it is:</p>\n\n<p>1- You need to create a FUNCTION that return numbers in a given range:</p>\n\n<pre><code>CREATE FUNCTION fnc_numbers_in_range (pMinNumber INT, pMaxNumber INT)\nRETURNING INT as NUMERO;\nDEFINE numero INT;\nLET numero = 0;\nFOR numero = pMinNumber TO pMaxNumber \n RETURN numero WITH RESUME; \nEND FOR; \nEND FUNCTION; \n</code></pre>\n\n<p>2- You Cross the results of this Function with the table you want:</p>\n\n<pre><code>SELECT * FROM TABLE (fnc_numbers_in_range(0,10000)), my_table;\n</code></pre>\n\n<p>The only thing is that you must know before-hand the number of rows you want, you may get this with the COUNT(*) Function.</p>\n\n<p>This works with my Informix Database, other implementations may need some tweaking.</p>\n"
},
{
"answer_id": 52672192,
"author": "Mike Twc",
"author_id": 7775187,
"author_profile": "https://Stackoverflow.com/users/7775187",
"pm_score": 1,
"selected": false,
"text": "<p>select sum(1) over (order by rowid) as row_number, M.* from systables M</p>\n"
},
{
"answer_id": 67332358,
"author": "Guasqueño",
"author_id": 1137223,
"author_profile": "https://Stackoverflow.com/users/1137223",
"pm_score": 0,
"selected": false,
"text": "<p>Using OLAP expressions you need the OVER() with something in it, since you don't want partitions include a SORT clause, like this:</p>\n<pre><code>SELECT ROW_NUMBER() OVER(ORDER BY lastName, firstName) AS rn, firstName, lastName \n</code></pre>\n<p>FROM students;</p>\n<p>and if you don't want to order by name, you could use the way records were entered in the system by ordering by ROWID.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am using informix database, I want a query which you could also generate a row number along with the query
Like
```
select row_number(),firstName,lastName
from students;
row_number() firstName lastName
1 john mathew
2 ricky pointing
3 sachin tendulkar
```
Here firstName, lastName are from Database, where as row number is generated in a query. | The best way is to use a (newly initialized) sequence.
```
begin work;
create sequence myseq;
select myseq.nextval,s.firstName,s.lastName from students s;
drop sequence myseq;
commit work;
``` |
119,281 | <ol>
<li><p>New class is a subclass of the original object</p></li>
<li><p>It needs to be php4 compatible</p></li>
</ol>
| [
{
"answer_id": 119287,
"author": "Joe Phillips",
"author_id": 20471,
"author_profile": "https://Stackoverflow.com/users/20471",
"pm_score": 1,
"selected": false,
"text": "<p>I would imagine you would have to invent some sort of a \"copy constructor\". Then you would just create a new subclass object whilst passing in the original object.</p>\n"
},
{
"answer_id": 119293,
"author": "Geoff",
"author_id": 10427,
"author_profile": "https://Stackoverflow.com/users/10427",
"pm_score": 2,
"selected": false,
"text": "<p>The best method would be to create a clone method on the Subclass so that you could do:</p>\n\n<pre><code>$myvar = $subclass->clone($originalObject)\n</code></pre>\n\n<p>Alternatively it sounds like you could look into the decorator pattern <a href=\"http://www.devshed.com/c/a/PHP/An-Introduction-to-Using-the-Decorator-Pattern-with-PHP/\" rel=\"nofollow noreferrer\">php example</a></p>\n"
},
{
"answer_id": 119344,
"author": "Jurassic_C",
"author_id": 20572,
"author_profile": "https://Stackoverflow.com/users/20572",
"pm_score": 4,
"selected": true,
"text": "<p>You could have your classes instantiated empty and then loaded by any number of methods. One of these methods could accept an instance of the parent class as an argument, and then copy its data from there</p>\n\n<pre><code>class childClass extends parentClass\n{\n function childClass()\n {\n //do nothing\n }\n\n function loadFromParentObj( $parentObj )\n {\n $this->a = $parentObj->a;\n $this->b = $parentObj->b;\n $this->c = $parentObj->c;\n }\n};\n\n$myParent = new parentClass();\n$myChild = new childClass();\n$myChild->loadFromParentObj( $myParent );\n</code></pre>\n"
},
{
"answer_id": 120758,
"author": "Marc Gear",
"author_id": 6563,
"author_profile": "https://Stackoverflow.com/users/6563",
"pm_score": 2,
"selected": false,
"text": "<p>A php object isn't a whole lot different to an array, and since all PHP 4 object variables are public, you can do some messy stuff like this:</p>\n\n<pre><code>function clone($object, $class)\n{\n $new = new $class();\n foreach ($object as $key => $value)\n {\n $new->$key = $value;\n }\n return $new;\n}\n$mySubclassObject = clone($myObject, 'mySubclass');\n</code></pre>\n\n<p>Its not pretty, and its certianly not what I'd consider to be good practice, but it <em>is</em> reusable, and it is pretty neat.</p>\n"
},
{
"answer_id": 121366,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": false,
"text": "<p>You can do it with some black magic, although I would seriously question <strong>why</strong> you have this requirement in the first place. It suggests that there is something severely wrong with your design.</p>\n\n<p>Nonetheless:</p>\n\n<pre><code>function change_class($object, $new_class) {\n preg_match('~^O:[0-9]+:\"[^\"]+\":(.+)$~', serialize($object), $matches);\n return unserialize(sprintf('O:%s:\"%s\":%s', strlen($new_class), $new_class, $matches[1]));\n}\n</code></pre>\n\n<p>This is subject to the same limitations as serialize in general, which means that references to other objects or resources are lost.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20907/"
]
| 1. New class is a subclass of the original object
2. It needs to be php4 compatible | You could have your classes instantiated empty and then loaded by any number of methods. One of these methods could accept an instance of the parent class as an argument, and then copy its data from there
```
class childClass extends parentClass
{
function childClass()
{
//do nothing
}
function loadFromParentObj( $parentObj )
{
$this->a = $parentObj->a;
$this->b = $parentObj->b;
$this->c = $parentObj->c;
}
};
$myParent = new parentClass();
$myChild = new childClass();
$myChild->loadFromParentObj( $myParent );
``` |
119,284 | <p>I would like to be able to override the default behaviour for positioning the caret in a masked textbox.</p>
<p>The default is to place the caret where the mouse was clicked, the masked textbox already contains characters due to the mask.</p>
<p>I know that you can hide the caret as mentioned in this <a href="https://stackoverflow.com/questions/44131/how-do-i-hide-the-input-caret-in-a-systemwindowsformstextbox">post</a>, is there something similar for positioning the caret at the beginning of the textbox when the control gets focus. </p>
| [
{
"answer_id": 119368,
"author": "Abbas",
"author_id": 4714,
"author_profile": "https://Stackoverflow.com/users/4714",
"pm_score": 6,
"selected": true,
"text": "<p>This should do the trick:</p>\n\n<pre><code> private void maskedTextBox1_Enter(object sender, EventArgs e)\n {\n this.BeginInvoke((MethodInvoker)delegate()\n {\n maskedTextBox1.Select(0, 0);\n }); \n }\n</code></pre>\n"
},
{
"answer_id": 119397,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 2,
"selected": false,
"text": "<p>Partial answer: you can position the caret by assigning a 0-length selection to the control in the MouseClick event, e.g.:</p>\n\n<pre><code>MaskedTextBox1.Select(5, 0)\n</code></pre>\n\n<p>...will set the caret at the 5th character position in the textbox.</p>\n\n<p>The reason this answer is only partial, is because I can't think of a generally reliable way to determine the position where the caret <i>should</i> be positioned on a click. This may be possible for some masks, but in some common cases (e.g. the US phone number mask), I can't really think of an easy way to separate the mask and prompt characters from actual user input...</p>\n"
},
{
"answer_id": 442552,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 3,
"selected": false,
"text": "<p>To improve upon Abbas's working solution, try this:</p>\n\n<pre><code>private void ueTxtAny_Enter(object sender, EventArgs e)\n{\n //This method will prevent the cursor from being positioned in the middle \n //of a textbox when the user clicks in it.\n MaskedTextBox textBox = sender as MaskedTextBox;\n\n if (textBox != null)\n {\n this.BeginInvoke((MethodInvoker)delegate()\n {\n int pos = textBox.SelectionStart;\n\n if (pos > textBox.Text.Length)\n pos = textBox.Text.Length;\n\n textBox.Select(pos, 0);\n });\n }\n}\n</code></pre>\n\n<p>This event handler can be re-used with multiple boxes, and it doesn't take away the user's ability to position the cursor in the middle of entered data (i.e does not force the cursor into zeroeth position when the box is not empty).</p>\n\n<p>I find this to be more closely mimicking a standard text box. Only glitch remaining (that I can see) is that after 'Enter' event, the user is still able to select the rest of the (empty) mask prompt if xe holds down the mouse and drags to the end.</p>\n"
},
{
"answer_id": 2479388,
"author": "Mike M",
"author_id": 297594,
"author_profile": "https://Stackoverflow.com/users/297594",
"pm_score": 3,
"selected": false,
"text": "<p>That is a big improvement over the default behaviour of MaskedTextBoxes. Thanks!</p>\n\n<p>I made a few changes to Ishmaeel's excellent solution. I prefer to call BeginInvoke only if the cursor needs to be moved. I also call the method from various event handlers, so the input parameter is the active MaskedTextBox.</p>\n\n<pre><code>private void maskedTextBoxGPS_Click( object sender, EventArgs e )\n{\n PositionCursorInMaskedTextBox( maskedTextBoxGPS );\n}\n\n\nprivate void PositionCursorInMaskedTextBox( MaskedTextBox mtb )\n{\n if (mtb == null) return;\n\n int pos = mtb.SelectionStart;\n\n if (pos > mtb.Text.Length)\n this.BeginInvoke( (MethodInvoker)delegate() { mtb.Select( mtb.Text.Length, 0 ); });\n}\n</code></pre>\n"
},
{
"answer_id": 6311071,
"author": "Brian Pressman",
"author_id": 793264,
"author_profile": "https://Stackoverflow.com/users/793264",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//not the prettiest, but it gets to the first non-masked area when a user mounse-clicks into the control\nprivate void txtAccount_MouseUp(object sender, MouseEventArgs e)\n{\n if (txtAccount.SelectionStart > txtAccount.Text.Length)\n txtAccount.Select(txtAccount.Text.Length, 0);\n}\n</code></pre>\n"
},
{
"answer_id": 46027019,
"author": "hmota",
"author_id": 2410517,
"author_profile": "https://Stackoverflow.com/users/2410517",
"pm_score": 0,
"selected": false,
"text": "<p>This solution works for me. Give it a try please.</p>\n\n<pre><code>private void maskedTextBox1_Click(object sender, EventArgs e)\n{\n\n maskedTextBox1.Select(maskedTextBox1.Text.Length, 0);\n}\n</code></pre>\n"
},
{
"answer_id": 47877385,
"author": "Gman Cornflake",
"author_id": 9111068,
"author_profile": "https://Stackoverflow.com/users/9111068",
"pm_score": 0,
"selected": false,
"text": "<p>I got mine to work using the Click event....no Invoke was needed.</p>\n\n<pre><code> private void maskedTextBox1_Click(object sender, EventArgs e)\n{\n maskedTextBox1.Select(0, 0); \n}\n</code></pre>\n"
},
{
"answer_id": 49435429,
"author": "Bill Kamer",
"author_id": 9536196,
"author_profile": "https://Stackoverflow.com/users/9536196",
"pm_score": 0,
"selected": false,
"text": "<p>This solution uses the Click method of the MaskedTextBox like Gman Cornflake used; however, I found it necessary to allow the user to click inside the MaskedTextBox once it contained data and the cursor stay where it is.</p>\n\n<p>The example below turns off prompts and literals and evaluates the length of the data in the MaskedTextBox and if equal to 0 it puts the cursor at the starting position; otherwise it just bypasses the code that puts the cursor at the starting position.</p>\n\n<p>The code is written in VB.NET 2017. Hope this helps!</p>\n\n<pre><code>Private Sub MaskedTextBox1_Click(sender As Object, e As EventArgs) Handles MaskedTextBox1.Click\n Me.MaskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals\n If Me.MaskedTextBox1.Text.Length = 0 Then\n MaskedTextBox1.Select(0, 0)\n End If\n Me.MaskedTextBox1.TextMaskFormat = MaskFormat.IncludePromptAndLiterals\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 60672918,
"author": "Joelius",
"author_id": 10883465,
"author_profile": "https://Stackoverflow.com/users/10883465",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an old question but google has led me here multiple times and none of the answers do exactly what I want.<br>\nFor example, the current answers don't work as I want when you're using <code>TextMaskFormat = MaskFormat.ExcludePromptAndLiterals</code>.</p>\n\n<p>The method below makes the cursor jump to the <strong>first prompt</strong> when the textbox is entered. Once you've entered the textbox, you can freely move the cursor.\nAlso it works fine for <code>MaskFormat.ExcludePromptAndLiterals</code>.</p>\n\n<p>That's why I think it's worth leaving this here :)</p>\n\n<pre><code>private void MaskedTextBox_Enter(object sender, EventArgs e)\n{\n // If attached to a MaskedTextBox' Enter-Event, this method will\n // make the cursor jump to the first prompt when the textbox gets focus.\n if (sender is MaskedTextBox textBox)\n {\n MaskFormat oldFormat = textBox.TextMaskFormat;\n textBox.TextMaskFormat = MaskFormat.IncludePromptAndLiterals;\n string fullText = textBox.Text;\n textBox.TextMaskFormat = oldFormat;\n\n int index = fullText.IndexOf(textBox.PromptChar);\n if (index > -1)\n {\n BeginInvoke(new Action(() => textBox.Select(index, 0)));\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4490/"
]
| I would like to be able to override the default behaviour for positioning the caret in a masked textbox.
The default is to place the caret where the mouse was clicked, the masked textbox already contains characters due to the mask.
I know that you can hide the caret as mentioned in this [post](https://stackoverflow.com/questions/44131/how-do-i-hide-the-input-caret-in-a-systemwindowsformstextbox), is there something similar for positioning the caret at the beginning of the textbox when the control gets focus. | This should do the trick:
```
private void maskedTextBox1_Enter(object sender, EventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate()
{
maskedTextBox1.Select(0, 0);
});
}
``` |
119,286 | <p>Consider the following ruby code</p>
<p>test.rb:</p>
<pre><code>begin
puts
thisFunctionDoesNotExist
x = 1+1
rescue Exception => e
p e
end
</code></pre>
<p>For debugging purposes, I would like the rescue block to know that the error occurred in line 4 of this file. Is there a clean way of doing that?</p>
| [
{
"answer_id": 119304,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 7,
"selected": true,
"text": "<pre><code>p e.backtrace \n</code></pre>\n\n<p>I ran it on an IRB session which has no source and it still gave relevant info.</p>\n\n<pre><code>=> [\"(irb):11:in `foo'\", \n \"(irb):17:in `irb_binding'\", \n \"/usr/lib64/ruby/1.8/irb/workspace.rb:52:in `irb_binding'\", \n \"/usr/lib64/ruby/1.8/irb/workspace.rb:52\"]\n</code></pre>\n\n<p>If you want a nicely parsed backtrace, the following regex might be handy: </p>\n\n<pre><code>p x.backtrace.map{ |x| \n x.match(/^(.+?):(\\d+)(|:in `(.+)')$/); \n [$1,$2,$4] \n}\n\n[\n [\"(irb)\", \"11\", \"foo\"], \n [\"(irb)\", \"48\", \"irb_binding\"], \n [\"/usr/lib64/ruby/1.8/irb/workspace.rb\", \"52\", \"irb_binding\"], \n [\"/usr/lib64/ruby/1.8/irb/workspace.rb\", \"52\", nil]\n]\n</code></pre>\n\n<p>( Regex /should/ be safe against weird characters in function names or directories/filenames ) \n( If you're wondering where foo camefrom, i made a def to grab the exception out : </p>\n\n<pre><code>>>def foo\n>> thisFunctionDoesNotExist\n>> rescue Exception => e \n>> return e \n>>end \n>>x = foo \n>>x.backtrace\n</code></pre>\n"
},
{
"answer_id": 119307,
"author": "dan-manges",
"author_id": 20072,
"author_profile": "https://Stackoverflow.com/users/20072",
"pm_score": 5,
"selected": false,
"text": "<p>You can access the backtrace from an Exception object. To see the entire backtrace:</p>\n\n<pre><code>p e.backtrace\n</code></pre>\n\n<p>It will contain an array of files and line numbers for the call stack. For a simple script like the one in your question, it would just contain one line.</p>\n\n<pre><code>[\"/Users/dan/Desktop/x.rb:4\"]\n</code></pre>\n\n<p>If you want the line number, you can examine the first line of the backtrace, and extract the value after the colon.</p>\n\n<pre><code>p e.backtrace[0].split(\":\").last\n</code></pre>\n"
},
{
"answer_id": 2880799,
"author": "rocky",
"author_id": 346919,
"author_profile": "https://Stackoverflow.com/users/346919",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible that in Ruby 1.9.3 you will be able to get access to not only this information in a more structured, reliable, and simpler way without using regular expressions to cut strings. </p>\n\n<p>The basic idea is to introduce a call frame object which gives access to information about the call stack.</p>\n\n<p>See <a href=\"http://wiki.github.com/rocky/rb-threadframe/\" rel=\"nofollow noreferrer\">http://wiki.github.com/rocky/rb-threadframe/</a>, which alas, requires patching Ruby 1.9. In RubyKaigi 2010 (late August 2010) a meeting is scheduled to discuss introducing a frame object into Ruby.</p>\n\n<p>Given this, the earliest this could happen is in Ruby 1.9.3.</p>\n"
},
{
"answer_id": 3114725,
"author": "John Bachir",
"author_id": 168143,
"author_profile": "https://Stackoverflow.com/users/168143",
"pm_score": 3,
"selected": false,
"text": "<p>Throwing my $0.02 in on this old thread-- here's a simple solution that maintains all the original data:</p>\n\n<pre><code>print e.backtrace.join(\"\\n\")\n</code></pre>\n"
},
{
"answer_id": 28897787,
"author": "Sergiy Seletskyy",
"author_id": 781048,
"author_profile": "https://Stackoverflow.com/users/781048",
"pm_score": 3,
"selected": false,
"text": "<p>Usually the backtrace contains a lot of lines from external gems\nIt's much more convenient to see only lines related to the project itself</p>\n\n<p>My suggestion is to filter the backtrace by the project folder name</p>\n\n<pre><code>puts e.backtrace.select { |x| x.match(/HERE-IS-YOUR-PROJECT-FOLDER-NAME/) }\n</code></pre>\n\n<p>And then you can parse filtered lines to extract line numbers as suggested in other answers.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17674/"
]
| Consider the following ruby code
test.rb:
```
begin
puts
thisFunctionDoesNotExist
x = 1+1
rescue Exception => e
p e
end
```
For debugging purposes, I would like the rescue block to know that the error occurred in line 4 of this file. Is there a clean way of doing that? | ```
p e.backtrace
```
I ran it on an IRB session which has no source and it still gave relevant info.
```
=> ["(irb):11:in `foo'",
"(irb):17:in `irb_binding'",
"/usr/lib64/ruby/1.8/irb/workspace.rb:52:in `irb_binding'",
"/usr/lib64/ruby/1.8/irb/workspace.rb:52"]
```
If you want a nicely parsed backtrace, the following regex might be handy:
```
p x.backtrace.map{ |x|
x.match(/^(.+?):(\d+)(|:in `(.+)')$/);
[$1,$2,$4]
}
[
["(irb)", "11", "foo"],
["(irb)", "48", "irb_binding"],
["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", "irb_binding"],
["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", nil]
]
```
( Regex /should/ be safe against weird characters in function names or directories/filenames )
( If you're wondering where foo camefrom, i made a def to grab the exception out :
```
>>def foo
>> thisFunctionDoesNotExist
>> rescue Exception => e
>> return e
>>end
>>x = foo
>>x.backtrace
``` |
119,295 | <p>Within our Active Directory domain, we have a MS SQL 2005 server, and a SharePoint (MOSS 3.0 I believe) server. Both authenticate against our LDAP server. Would like to allow these authenticated SharePoint visitors to see some of the data from the MS SQL database. Primary challenge is authentication.</p>
<p>Any tips on getting the pass-through authentication to work? I have searched (Google) for a proper connection string to use, but keep finding ones that have embedded credentials or other schemes. I gather that SSPI is what I want to use, but am not sure how to implement.</p>
<p>clarification: we don't have a single-sign-on server (e.g. Shibboleth) setup yet</p>
| [
{
"answer_id": 119348,
"author": "Leo Moore",
"author_id": 6336,
"author_profile": "https://Stackoverflow.com/users/6336",
"pm_score": 2,
"selected": true,
"text": "<p>If you are using C# the code and connection string is:</p>\n\n<pre><code>using System.Data.SqlClient; \n... \nSqlConnection oSQLConn = new SqlConnection(); \noSQLConn.ConnectionString = \n \"Data Source=(local);\" + \n \"Initial Catalog=myDatabaseName;\" +\n \"Integrated Security=SSPI\";\n //Or\n // \"Server=(local);\" + \n // \"Database=myDatabaseName;\" + \n // \"Trusted_Connection=Yes\";\noSQLConn.Open(); \n... \noSQLConn.Close(); \n</code></pre>\n\n<p>An excellent resource for connection strings can be found at <a href=\"http://www.carlprothman.net/Default.aspx?tabid=81\" rel=\"nofollow noreferrer\">Carl Prothman's Blog</a>. Yoy should probably replace <code>(local)</code> with the name of the SQL server.</p>\n\n<p>You will need to either configure SQL server to give the Domain Roles the access privilages you want. In SQL server you will need to go to Security\\Logins and make sure you have the Domain\\User Role (ie MyCompany\\SharpointUsers). In your config you should have</p>\n"
},
{
"answer_id": 119566,
"author": "Magnus Johansson",
"author_id": 3584,
"author_profile": "https://Stackoverflow.com/users/3584",
"pm_score": 0,
"selected": false,
"text": "<p>What do you mean by \"users of SharePoint\"?</p>\n\n<p>Do you mean that they want to see data from inside a SharePoint page?\nIn that case you have to do impersonation in that page/application, and possible set up Kerberos correctly.</p>\n\n<p>Then you will have to assign those SharePoint users (or better, their AD group) proper privileges on the SQL Server.</p>\n"
},
{
"answer_id": 4079917,
"author": "Kyle",
"author_id": 494988,
"author_profile": "https://Stackoverflow.com/users/494988",
"pm_score": 1,
"selected": false,
"text": "<p>Actually Windows Authentication verifies the user is legitimate without passing the username and password over the wire. Whereas Passthrough authentication does pass the username and password over the wire. They are not the same thing. Using the connection string and code provided by Leo Moore causes SQL to use Windows Authentication, which it uses by default - not Passthrough authentication, which the OP asked about. </p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18484/"
]
| Within our Active Directory domain, we have a MS SQL 2005 server, and a SharePoint (MOSS 3.0 I believe) server. Both authenticate against our LDAP server. Would like to allow these authenticated SharePoint visitors to see some of the data from the MS SQL database. Primary challenge is authentication.
Any tips on getting the pass-through authentication to work? I have searched (Google) for a proper connection string to use, but keep finding ones that have embedded credentials or other schemes. I gather that SSPI is what I want to use, but am not sure how to implement.
clarification: we don't have a single-sign-on server (e.g. Shibboleth) setup yet | If you are using C# the code and connection string is:
```
using System.Data.SqlClient;
...
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString =
"Data Source=(local);" +
"Initial Catalog=myDatabaseName;" +
"Integrated Security=SSPI";
//Or
// "Server=(local);" +
// "Database=myDatabaseName;" +
// "Trusted_Connection=Yes";
oSQLConn.Open();
...
oSQLConn.Close();
```
An excellent resource for connection strings can be found at [Carl Prothman's Blog](http://www.carlprothman.net/Default.aspx?tabid=81). Yoy should probably replace `(local)` with the name of the SQL server.
You will need to either configure SQL server to give the Domain Roles the access privilages you want. In SQL server you will need to go to Security\Logins and make sure you have the Domain\User Role (ie MyCompany\SharpointUsers). In your config you should have |
119,308 | <p>I have a huge database with some 100 tables and some 250 stored procedures. I want to know the list of tables affected by a subset of stored procedures. For example, I have a list of 50 stored procedures, out of 250, and I want to know the list of tables that will be affected by these 50 stored procedures. Is there any easy way for doing this, other than reading all the stored procedures and finding the list of tables manually? </p>
<p>PS: I am using SQL Server 2000 and SQL Server 2005 clients for this.</p>
| [
{
"answer_id": 119333,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": -1,
"selected": false,
"text": "<p>One very invasive option would be to get a duplicate database and set a trigger on every table that logs that something happened. Then run all the SP's. If you can't do lots of mods to the DB that wont work</p>\n\n<p>Also, be sure to add the logging to existing triggers rather than replace them with logging if you also want tables that the SP's effect via triggers.</p>\n"
},
{
"answer_id": 119385,
"author": "MotoWilliams",
"author_id": 2730,
"author_profile": "https://Stackoverflow.com/users/2730",
"pm_score": 1,
"selected": false,
"text": "<p><strong>sp_depends 'StoredProcName'</strong> will return the object name and object type that the stored proc depends on.</p>\n\n<p><strong>EDIT:</strong> I like @KG's answer better. More flexible IMHO.</p>\n"
},
{
"answer_id": 119403,
"author": "karlgrz",
"author_id": 318,
"author_profile": "https://Stackoverflow.com/users/318",
"pm_score": 4,
"selected": true,
"text": "<p>This would be your SQL Server query:</p>\n\n<pre><code>SELECT\n [NAME]\nFROM\n sysobjects\nWHERE\n xType = 'U' AND --specifies a user table object\n id in\n (\n SELECT \n sd.depid \n FROM \n sysobjects so,\n sysdepends sd\n WHERE\n so.name = 'NameOfStoredProcedure' AND \n sd.id = so.id\n )\n</code></pre>\n\n<p>Hope this helps someone.</p>\n"
},
{
"answer_id": 119424,
"author": "Jason Stangroome",
"author_id": 20819,
"author_profile": "https://Stackoverflow.com/users/20819",
"pm_score": 1,
"selected": false,
"text": "<p>I'd do it this way in SQL 2005 (uncomment the \"AND\" line if you only want it for a particular proc):</p>\n\n<pre><code>SELECT \n [Proc] = SCHEMA_NAME(p.schema_id) + '.' + p.name,\n [Table] = SCHEMA_NAME(t.schema_id) + '.' + t.name,\n [Column] = c.name,\n d.is_selected,\n d.is_updated\nFROM sys.procedures p\n INNER JOIN sys.sql_dependencies d\n ON d.object_id = p.object_id\n AND d.class IN (0,1)\n INNER JOIN sys.tables t\n ON t.object_id = d.referenced_major_id\n INNER JOIN sys.columns c\n ON c.object_id = t.object_id\n AND c.column_id = d.referenced_minor_id\nWHERE p.type IN ('P')\n-- AND p.object_id = OBJECT_ID('MyProc')\nORDER BY \n 1, 2, 3\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a huge database with some 100 tables and some 250 stored procedures. I want to know the list of tables affected by a subset of stored procedures. For example, I have a list of 50 stored procedures, out of 250, and I want to know the list of tables that will be affected by these 50 stored procedures. Is there any easy way for doing this, other than reading all the stored procedures and finding the list of tables manually?
PS: I am using SQL Server 2000 and SQL Server 2005 clients for this. | This would be your SQL Server query:
```
SELECT
[NAME]
FROM
sysobjects
WHERE
xType = 'U' AND --specifies a user table object
id in
(
SELECT
sd.depid
FROM
sysobjects so,
sysdepends sd
WHERE
so.name = 'NameOfStoredProcedure' AND
sd.id = so.id
)
```
Hope this helps someone. |
119,328 | <p>How do I truncate a java <code>String</code> so that I know it will fit in a given number of bytes storage once it is UTF-8 encoded?</p>
| [
{
"answer_id": 119338,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 3,
"selected": false,
"text": "<p>UTF-8 encoding has a neat trait that allows you to see where in a byte-set you are.</p>\n\n<p>check the stream at the character limit you want. </p>\n\n<ul>\n<li>If its high bit is 0, it's a single-byte char, just replace it with 0 and you're fine. </li>\n<li>If its high bit is 1 and so is the next bit, then you're at the start of a multi-byte char, so just set that byte to 0 and you're good. </li>\n<li>If the high bit is 1 but the next bit is 0, then you're in the middle of a character, travel back along the buffer until you hit a byte that has 2 or more 1s in the high bits, and replace that byte with 0.</li>\n</ul>\n\n<p>Example: If your stream is: 31 33 31 C1 A3 32 33 00, you can make your string 1, 2, 3, 5, 6, or 7 bytes long, but not 4, as that would put the 0 after C1, which is the start of a multi-byte char.</p>\n"
},
{
"answer_id": 119343,
"author": "mitchnull",
"author_id": 18645,
"author_profile": "https://Stackoverflow.com/users/18645",
"pm_score": 5,
"selected": false,
"text": "<p>You should use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/nio/charset/CharsetEncoder.html#encode-java.nio.CharBuffer-java.nio.ByteBuffer-boolean-\" rel=\"nofollow noreferrer\">CharsetEncoder</a>, the simple <code>getBytes()</code> + copy as many as you can can cut UTF-8 charcters in half.</p>\n<p>Something like this:</p>\n<pre><code>public static int truncateUtf8(String input, byte[] output) {\n \n ByteBuffer outBuf = ByteBuffer.wrap(output);\n CharBuffer inBuf = CharBuffer.wrap(input.toCharArray());\n\n CharsetEncoder utf8Enc = StandardCharsets.UTF_8.newEncoder();\n utf8Enc.encode(inBuf, outBuf, true);\n System.out.println("encoded " + inBuf.position() + " chars of " + input.length() + ", result: " + outBuf.position() + " bytes");\n return outBuf.position();\n}\n</code></pre>\n"
},
{
"answer_id": 119586,
"author": "Matt Quail",
"author_id": 15790,
"author_profile": "https://Stackoverflow.com/users/15790",
"pm_score": 6,
"selected": true,
"text": "<p>Here is a simple loop that counts how big the UTF-8 representation is going to be, and truncates when it is exceeded:</p>\n\n<pre><code>public static String truncateWhenUTF8(String s, int maxBytes) {\n int b = 0;\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n\n // ranges from http://en.wikipedia.org/wiki/UTF-8\n int skip = 0;\n int more;\n if (c <= 0x007f) {\n more = 1;\n }\n else if (c <= 0x07FF) {\n more = 2;\n } else if (c <= 0xd7ff) {\n more = 3;\n } else if (c <= 0xDFFF) {\n // surrogate area, consume next char as well\n more = 4;\n skip = 1;\n } else {\n more = 3;\n }\n\n if (b + more > maxBytes) {\n return s.substring(0, i);\n }\n b += more;\n i += skip;\n }\n return s;\n}\n</code></pre>\n\n<p>This <em>does</em> handle <a href=\"http://en.wikipedia.org/wiki/UTF-16\" rel=\"noreferrer\">surrogate pairs</a> that appear in the input string. Java's UTF-8 encoder (correctly) outputs surrogate pairs as a single 4-byte sequence instead of two 3-byte sequences, so <code>truncateWhenUTF8()</code> will return the longest truncated string it can. If you ignore surrogate pairs in the implementation then the truncated strings may be shorted than they needed to be.</p>\n\n<p>I haven't done a lot of testing on that code, but here are some preliminary tests:</p>\n\n<pre><code>private static void test(String s, int maxBytes, int expectedBytes) {\n String result = truncateWhenUTF8(s, maxBytes);\n byte[] utf8 = result.getBytes(Charset.forName(\"UTF-8\"));\n if (utf8.length > maxBytes) {\n System.out.println(\"BAD: our truncation of \" + s + \" was too big\");\n }\n if (utf8.length != expectedBytes) {\n System.out.println(\"BAD: expected \" + expectedBytes + \" got \" + utf8.length);\n }\n System.out.println(s + \" truncated to \" + result);\n}\n\npublic static void main(String[] args) {\n test(\"abcd\", 0, 0);\n test(\"abcd\", 1, 1);\n test(\"abcd\", 2, 2);\n test(\"abcd\", 3, 3);\n test(\"abcd\", 4, 4);\n test(\"abcd\", 5, 4);\n\n test(\"a\\u0080b\", 0, 0);\n test(\"a\\u0080b\", 1, 1);\n test(\"a\\u0080b\", 2, 1);\n test(\"a\\u0080b\", 3, 3);\n test(\"a\\u0080b\", 4, 4);\n test(\"a\\u0080b\", 5, 4);\n\n test(\"a\\u0800b\", 0, 0);\n test(\"a\\u0800b\", 1, 1);\n test(\"a\\u0800b\", 2, 1);\n test(\"a\\u0800b\", 3, 1);\n test(\"a\\u0800b\", 4, 4);\n test(\"a\\u0800b\", 5, 5);\n test(\"a\\u0800b\", 6, 5);\n\n // surrogate pairs\n test(\"\\uD834\\uDD1E\", 0, 0);\n test(\"\\uD834\\uDD1E\", 1, 0);\n test(\"\\uD834\\uDD1E\", 2, 0);\n test(\"\\uD834\\uDD1E\", 3, 0);\n test(\"\\uD834\\uDD1E\", 4, 4);\n test(\"\\uD834\\uDD1E\", 5, 4);\n\n}\n</code></pre>\n\n<p><strong>Updated</strong> Modified code example, it now handles surrogate pairs.</p>\n"
},
{
"answer_id": 119660,
"author": "user19050",
"author_id": 19050,
"author_profile": "https://Stackoverflow.com/users/19050",
"pm_score": 2,
"selected": false,
"text": "<p>You can calculate the number of bytes without doing any conversion.</p>\n\n<pre><code>foreach character in the Java string\n if 0 <= character <= 0x7f\n count += 1\n else if 0x80 <= character <= 0x7ff\n count += 2\n else if 0x800 <= character <= 0xd7ff // excluding the surrogate area\n count += 3\n else if 0xdc00 <= character <= 0xffff\n count += 3\n else { // surrogate, a bit more complicated\n count += 4\n skip one extra character in the input stream\n }\n</code></pre>\n\n<p>You would have to detect surrogate pairs (D800-DBFF and U+DC00–U+DFFF) and count 4 bytes for each valid surrogate pair. If you get the first value in the first range and the second in the second range, it's all ok, skip them and add 4.\nBut if not, then it is an invalid surrogate pair. I am not sure how Java deals with that, but your algorithm will have to do right counting in that (unlikely) case.</p>\n"
},
{
"answer_id": 35148974,
"author": "sigget",
"author_id": 150333,
"author_profile": "https://Stackoverflow.com/users/150333",
"pm_score": 4,
"selected": false,
"text": "<p>Here's what I came up with, it uses standard Java APIs so should be safe and compatible with all the unicode weirdness and surrogate pairs etc. The solution is taken from <a href=\"http://www.jroller.com/holy/entry/truncating_utf_string_to_the\" rel=\"noreferrer\">http://www.jroller.com/holy/entry/truncating_utf_string_to_the</a> with checks added for null and for avoiding decoding when the string is fewer bytes than <strong>maxBytes</strong>.</p>\n\n<pre><code>/**\n * Truncates a string to the number of characters that fit in X bytes avoiding multi byte characters being cut in\n * half at the cut off point. Also handles surrogate pairs where 2 characters in the string is actually one literal\n * character.\n *\n * Based on: http://www.jroller.com/holy/entry/truncating_utf_string_to_the\n */\npublic static String truncateToFitUtf8ByteLength(String s, int maxBytes) {\n if (s == null) {\n return null;\n }\n Charset charset = Charset.forName(\"UTF-8\");\n CharsetDecoder decoder = charset.newDecoder();\n byte[] sba = s.getBytes(charset);\n if (sba.length <= maxBytes) {\n return s;\n }\n // Ensure truncation by having byte buffer = maxBytes\n ByteBuffer bb = ByteBuffer.wrap(sba, 0, maxBytes);\n CharBuffer cb = CharBuffer.allocate(maxBytes);\n // Ignore an incomplete character\n decoder.onMalformedInput(CodingErrorAction.IGNORE)\n decoder.decode(bb, cb, true);\n decoder.flush(cb);\n return new String(cb.array(), 0, cb.position());\n}\n</code></pre>\n"
},
{
"answer_id": 52962632,
"author": "Suresh Gupta",
"author_id": 2218806,
"author_profile": "https://Stackoverflow.com/users/2218806",
"pm_score": 3,
"selected": false,
"text": "<p>you can use -new String( data.getBytes(\"UTF-8\") , 0, maxLen, \"UTF-8\");</p>\n"
},
{
"answer_id": 70338834,
"author": "walen",
"author_id": 6404321,
"author_profile": "https://Stackoverflow.com/users/6404321",
"pm_score": -1,
"selected": false,
"text": "<p>Based on <a href=\"https://stackoverflow.com/a/119338/6404321\">billjamesdev's answer</a> I've come up with the following method which, as far as I can tell, is the simplest <em>and</em> still works OK with surrogate pairs:</p>\n<pre><code>public static String utf8ByteTrim(String s, int trimSize) {\n final byte[] bytes = s.getBytes(StandardCharsets.UTF_8);\n if ((bytes[trimSize-1] & 0x80) != 0) { // inside a multibyte sequence\n while ((bytes[trimSize-1] & 0x40) == 0) { // 2nd, 3rd, 4th bytes\n trimSize--;\n }\n trimSize--;\n }\n return new String(bytes, 0, trimSize, StandardCharsets.UTF_8);\n}\n</code></pre>\n<p>Some testing:</p>\n<pre><code>String test = "Aæ尝试";\nIntStream.range(1, 16).forEachOrdered(i ->\n System.out.println("Size " + i + ": " + utf8ByteTrim(test, i))\n);\n\n---\n\nSize 1: A\nSize 2: A\nSize 3: A\nSize 4: Aæ\nSize 5: Aæ\nSize 6: Aæ\nSize 7: Aæ\nSize 8: Aæ\nSize 9: Aæ\nSize 10: Aæ\nSize 11: Aæ尝\nSize 12: Aæ尝\nSize 13: Aæ尝试\nSize 14: Aæ尝试\nSize 15: Aæ尝试\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220/"
]
| How do I truncate a java `String` so that I know it will fit in a given number of bytes storage once it is UTF-8 encoded? | Here is a simple loop that counts how big the UTF-8 representation is going to be, and truncates when it is exceeded:
```
public static String truncateWhenUTF8(String s, int maxBytes) {
int b = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// ranges from http://en.wikipedia.org/wiki/UTF-8
int skip = 0;
int more;
if (c <= 0x007f) {
more = 1;
}
else if (c <= 0x07FF) {
more = 2;
} else if (c <= 0xd7ff) {
more = 3;
} else if (c <= 0xDFFF) {
// surrogate area, consume next char as well
more = 4;
skip = 1;
} else {
more = 3;
}
if (b + more > maxBytes) {
return s.substring(0, i);
}
b += more;
i += skip;
}
return s;
}
```
This *does* handle [surrogate pairs](http://en.wikipedia.org/wiki/UTF-16) that appear in the input string. Java's UTF-8 encoder (correctly) outputs surrogate pairs as a single 4-byte sequence instead of two 3-byte sequences, so `truncateWhenUTF8()` will return the longest truncated string it can. If you ignore surrogate pairs in the implementation then the truncated strings may be shorted than they needed to be.
I haven't done a lot of testing on that code, but here are some preliminary tests:
```
private static void test(String s, int maxBytes, int expectedBytes) {
String result = truncateWhenUTF8(s, maxBytes);
byte[] utf8 = result.getBytes(Charset.forName("UTF-8"));
if (utf8.length > maxBytes) {
System.out.println("BAD: our truncation of " + s + " was too big");
}
if (utf8.length != expectedBytes) {
System.out.println("BAD: expected " + expectedBytes + " got " + utf8.length);
}
System.out.println(s + " truncated to " + result);
}
public static void main(String[] args) {
test("abcd", 0, 0);
test("abcd", 1, 1);
test("abcd", 2, 2);
test("abcd", 3, 3);
test("abcd", 4, 4);
test("abcd", 5, 4);
test("a\u0080b", 0, 0);
test("a\u0080b", 1, 1);
test("a\u0080b", 2, 1);
test("a\u0080b", 3, 3);
test("a\u0080b", 4, 4);
test("a\u0080b", 5, 4);
test("a\u0800b", 0, 0);
test("a\u0800b", 1, 1);
test("a\u0800b", 2, 1);
test("a\u0800b", 3, 1);
test("a\u0800b", 4, 4);
test("a\u0800b", 5, 5);
test("a\u0800b", 6, 5);
// surrogate pairs
test("\uD834\uDD1E", 0, 0);
test("\uD834\uDD1E", 1, 0);
test("\uD834\uDD1E", 2, 0);
test("\uD834\uDD1E", 3, 0);
test("\uD834\uDD1E", 4, 4);
test("\uD834\uDD1E", 5, 4);
}
```
**Updated** Modified code example, it now handles surrogate pairs. |
119,336 | <p>I've got a customer trying to access one of my sites, and they keep getting this error > ssl_error_rx_record_too_long</p>
<p>They're getting this error on all browsers, all platforms. I can't reproduce the problem at all.</p>
<p>My server and myself are located in the USA, the customer is located in India.</p>
<p>I googled on the problem, and the main source seems to be that the SSL port is speaking in HTTP. I checked my server, and this is not happening. I tried <a href="http://support.servertastic.com/error-code-ssl-error-rx-record-too-long/" rel="noreferrer">the solution mentioned here</a>, but the customer has stated it did not fix the issue.</p>
<p>Can anyone tell me how I can fix this, or how I can reproduce this???</p>
<p><strong>THE SOLUTION</strong></p>
<p>Turns out the customer had a misconfigured local proxy!</p>
<p>Hope that helps anyone finding this question trying to debug it in the future.</p>
| [
{
"answer_id": 119345,
"author": "dan-manges",
"author_id": 20072,
"author_profile": "https://Stackoverflow.com/users/20072",
"pm_score": 3,
"selected": false,
"text": "<p>Ask the user for the exact URL they're using in their browser. If they're entering <a href=\"https://your.site:80\" rel=\"noreferrer\">https://your.site:80</a>, they may receive the ssl_error_rx_record_too_long error.</p>\n"
},
{
"answer_id": 331044,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>In my case the problem was that https was unable to start correctly because Listen 443 was in \"IfDefine SSL\" derective, but my apache didnt start with -DSSL option. The fix was to change my apachectl script in:</p>\n\n<pre><code>$HTTPD -k $ARGV\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>$HTTPD -k $ARGV -DSSL\n</code></pre>\n\n<p>Hope that helps somebody.</p>\n"
},
{
"answer_id": 853883,
"author": "Christian Davén",
"author_id": 12534,
"author_profile": "https://Stackoverflow.com/users/12534",
"pm_score": 4,
"selected": false,
"text": "<p>In my case I had forgot to set <code>SSLEngine On</code> in the configuration. Like so,</p>\n\n<pre><code><VirtualHost _default_:443>\n SSLEngine On\n ...\n</VirtualHost>\n</code></pre>\n\n<p><a href=\"http://httpd.apache.org/docs/2.2/mod/mod_ssl.html#sslengine\" rel=\"noreferrer\">http://httpd.apache.org/docs/2.2/mod/mod_ssl.html#sslengine</a></p>\n"
},
{
"answer_id": 887350,
"author": "alexm",
"author_id": 102765,
"author_profile": "https://Stackoverflow.com/users/102765",
"pm_score": 5,
"selected": false,
"text": "<p>In my case I had to change the <VirtualHost *> back to <VirtualHost *:80> (which is the default on Ubuntu). Otherwise, the port 443 wasn't using SSL and was sending plain HTML back to the browser.</p>\n\n<p>You can check whether this is your case quite easily: just connect to your server <a href=\"http://www.example.com:443\" rel=\"noreferrer\">http://www.example.com:443</a>. If you see plain HTML, your Apache is not using SSL on port 443 at all, most probably due to a VirtualHost misconfiguration.</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 893109,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>My problem was due to a LOW MTU over a VPN connection.</p>\n\n<pre><code>netsh interface ipv4 show inter\n\nIdx Met MTU State Name\n--- --- ----- ----------- -------------------\n 1 4275 4294967295 connected Loopback Pseudo-Interface 1\n 10 4250 **1300** connected Wireless Network Connection\n 31 25 1400 connected Remote Access to XYZ Network\n</code></pre>\n\n<p>Fix:\n<strong>netsh interface ipv4 set interface \"Wireless Network Connection\" mtu=1400</strong></p>\n\n<p>It may be an issue over a non-VPN connection also...</p>\n"
},
{
"answer_id": 1064029,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I had a messed up virtual host config. Remember you need one virtual host without SSL for port 80, and another one with SSL for port 443. You cannot have both in one virtual host, as the webmin-generated config tried to do.</p>\n"
},
{
"answer_id": 1398515,
"author": "Pierre-Gilles Levallois",
"author_id": 2162529,
"author_profile": "https://Stackoverflow.com/users/2162529",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem in some browser to access to my SSL site.\nI have found that <strong>I had to give to fireFox the right proxy</strong> (FireFox was accessing directly to internet).</p>\n\n<p>Depending of the lan configuration (Tunneling, filtering, proxy redirection), the \"direct access to internet\" mode for FireFox throws this error.</p>\n"
},
{
"answer_id": 2547884,
"author": "Ben",
"author_id": 197606,
"author_profile": "https://Stackoverflow.com/users/197606",
"pm_score": 7,
"selected": false,
"text": "<p>The solution for me was that <code>default-ssl</code> was not enabled in apache 2.... just putting <code>SSLEngine On</code></p>\n\n<p>I had to execute <code>a2ensite default-ssl</code> and everything worked.</p>\n"
},
{
"answer_id": 3371811,
"author": "rogovsky",
"author_id": 406747,
"author_profile": "https://Stackoverflow.com/users/406747",
"pm_score": 2,
"selected": false,
"text": "<p>Please see <a href=\"http://www.errorhelp.com/index.php/search/details/69648/ssl_error_rx_record_too_long\" rel=\"nofollow noreferrer\">this link</a>.</p>\n\n<p>I looked in all my apache log files until I found the actual error (I had changed the <code><VirtualHost></code> from <code>_default_</code> to my <code>fqdn</code>). When I fixed this error, everything worked fine.</p>\n"
},
{
"answer_id": 4214783,
"author": "drillingman",
"author_id": 413122,
"author_profile": "https://Stackoverflow.com/users/413122",
"pm_score": 4,
"selected": false,
"text": "<p>If you have the error after setup a new https vhost and the config seems to be right, remember to link in <code>sites-enabled</code> too.</p>\n"
},
{
"answer_id": 4762977,
"author": "Randall",
"author_id": 584940,
"author_profile": "https://Stackoverflow.com/users/584940",
"pm_score": 9,
"selected": true,
"text": "<p>The <a href=\"http://support.servertastic.com/error-code-ssl-error-rx-record-too-long/\" rel=\"noreferrer\">link mentioned by Subimage</a> was right on the money for me. It suggested changing the virtual host tag, ie, from <code><VirtualHost myserver.example.com:443></code> to <code><VirtualHost _default_:443></code></p>\n\n<blockquote>\n <p>Error code: <code>ssl_error_rx_record_too_long</code></p>\n \n <p>This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate.</p>\n \n <p>Below are some things we recommend trying.</p>\n \n <ul>\n <li><p>Ensure that port 443 is open and enabled on your server. This is the standard port for https communications.</p></li>\n <li><p>If SSL is using a non-standard port then FireFox 3 can sometimes give this error. Ensure SSL is running on port 443.</p></li>\n <li><p>If using Apache2 check that you are using port 443 for SSL. This can be done by setting the ports.conf file as follows</p>\n\n<pre><code>Listen 80\nListen 443 https\n</code></pre></li>\n <li><p>Make sure you do not have more than one SSL certificate sharing the same IP. Please ensure that all SSL certificates utilise their own dedicated IP.</p></li>\n <li><p>If using Apache2 check your vhost config. Some users have reported changing <code><VirtualHost></code> to <code>_default_</code> resolved the error.</p></li>\n </ul>\n</blockquote>\n\n<p>That fixed my problem. It's rare that I google an error message and get the first hit with the right answer! :-)</p>\n\n<p><em>In addition to the above</em>, these are some other solutions that other folks have found were causing the issue:</p>\n\n<ul>\n<li><p>Make sure that your SSL certificate is not expired</p></li>\n<li><p>Try to specify the Cipher:</p>\n\n<p><code>SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3</code></p></li>\n</ul>\n"
},
{
"answer_id": 6700450,
"author": "fimbulvetr",
"author_id": 220922,
"author_profile": "https://Stackoverflow.com/users/220922",
"pm_score": 2,
"selected": false,
"text": "<p>In my case, I had the wrong IP Address in the virtual host file. The listen was 443, and the stanza was <code><VirtualHost 192.168.0.1:443></code> but the server did not have the 192.168.0.1 address! </p>\n"
},
{
"answer_id": 10178561,
"author": "Tarka",
"author_id": 210226,
"author_profile": "https://Stackoverflow.com/users/210226",
"pm_score": 3,
"selected": false,
"text": "<p>Old question, but first result in Google for me, so here's what I had to do.</p>\n\n<p><strong>Ubuntu 12.04 Desktop with Apache installed</strong></p>\n\n<p>All the configuration and mod_ssl was installed when I installed Apache, but it just wasn't linked in the right spots yet. Note: all paths below are relative to <strong>/etc/apache2/</strong></p>\n\n<p><code>mod_ssl</code> is stored in <code>./mods-available</code>, and the SSL site configuration is in <code>./sites-available</code>, you just have to link these to their correct places in <code>./mods-enabled</code> and <code>./sites-enabled</code></p>\n\n<pre><code>cd /etc/apache2\ncd ./mods-enabled\nsudo ln -s ../mods-available/ssl.* ./\ncd ../sites-enabled\nsudo ln -s ../sites-available/default-ssl ./\n</code></pre>\n\n<p>Restart Apache and it should work. I was trying to access <a href=\"https://localhost\">https://localhost</a>, so your results may vary for external access, but this worked for me.</p>\n"
},
{
"answer_id": 11504885,
"author": "Anna B",
"author_id": 252124,
"author_profile": "https://Stackoverflow.com/users/252124",
"pm_score": 2,
"selected": false,
"text": "<p>You might also try fixing the hosts file.</p>\n\n<p>Keep the vhost file with the fully qualified domain and add the hostname in the hosts file <strong>/etc/hosts</strong> (debian)</p>\n\n<pre><code>ip.ip.ip.ip name name.domain.com\n</code></pre>\n\n<p>After restarting apache2, the error should be gone.</p>\n"
},
{
"answer_id": 12606798,
"author": "Anon",
"author_id": 918986,
"author_profile": "https://Stackoverflow.com/users/918986",
"pm_score": 0,
"selected": false,
"text": "<p>For me the solution was that my ddclient was not cronning properly...</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10596/"
]
| I've got a customer trying to access one of my sites, and they keep getting this error > ssl\_error\_rx\_record\_too\_long
They're getting this error on all browsers, all platforms. I can't reproduce the problem at all.
My server and myself are located in the USA, the customer is located in India.
I googled on the problem, and the main source seems to be that the SSL port is speaking in HTTP. I checked my server, and this is not happening. I tried [the solution mentioned here](http://support.servertastic.com/error-code-ssl-error-rx-record-too-long/), but the customer has stated it did not fix the issue.
Can anyone tell me how I can fix this, or how I can reproduce this???
**THE SOLUTION**
Turns out the customer had a misconfigured local proxy!
Hope that helps anyone finding this question trying to debug it in the future. | The [link mentioned by Subimage](http://support.servertastic.com/error-code-ssl-error-rx-record-too-long/) was right on the money for me. It suggested changing the virtual host tag, ie, from `<VirtualHost myserver.example.com:443>` to `<VirtualHost _default_:443>`
>
> Error code: `ssl_error_rx_record_too_long`
>
>
> This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate.
>
>
> Below are some things we recommend trying.
>
>
> * Ensure that port 443 is open and enabled on your server. This is the standard port for https communications.
> * If SSL is using a non-standard port then FireFox 3 can sometimes give this error. Ensure SSL is running on port 443.
> * If using Apache2 check that you are using port 443 for SSL. This can be done by setting the ports.conf file as follows
>
>
>
> ```
> Listen 80
> Listen 443 https
>
> ```
> * Make sure you do not have more than one SSL certificate sharing the same IP. Please ensure that all SSL certificates utilise their own dedicated IP.
> * If using Apache2 check your vhost config. Some users have reported changing `<VirtualHost>` to `_default_` resolved the error.
>
>
>
That fixed my problem. It's rare that I google an error message and get the first hit with the right answer! :-)
*In addition to the above*, these are some other solutions that other folks have found were causing the issue:
* Make sure that your SSL certificate is not expired
* Try to specify the Cipher:
`SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3` |
119,404 | <p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
| [
{
"answer_id": 119418,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 6,
"selected": true,
"text": "<p>You can use <a href=\"http://spacepants.org/src/pymad/\" rel=\"noreferrer\">pymad</a>. It's an external library, but don't fall for the Not Invented Here trap. Any particular reason you don't want any external libraries?</p>\n\n<pre><code>import mad\n\nmf = mad.MadFile(\"foo.mp3\")\ntrack_length_in_milliseconds = mf.total_time() \n</code></pre>\n\n<p>Spotted <a href=\"http://simonwillison.net/2003/Dec/4/mp3lengths/\" rel=\"noreferrer\">here</a>.</p>\n\n<p>--</p>\n\n<p>If you really don't want to use an external library, have a look <a href=\"http://ibofobi.dk/stuff/mp3/\" rel=\"noreferrer\">here</a> and check out how he's done it. Warning: it's complicated.</p>\n"
},
{
"answer_id": 119436,
"author": "Mats Wiklander",
"author_id": 5140,
"author_profile": "https://Stackoverflow.com/users/5140",
"pm_score": 0,
"selected": false,
"text": "<p>You might count the number of frames in the file. Each frame has a start code, although I can't recollect the exact value of the start code and I don't have MPEG specs laying around. Each frame has a certain length, around 40ms for MPEG1 layer II.</p>\n\n<p>This method works for CBR-files (Constant Bit Rate), how VBR-files work is a completely different story.</p>\n\n<p>From the document below:</p>\n\n<p>For Layer I files us this formula:</p>\n\n<p>FrameLengthInBytes = (12 * BitRate / SampleRate + Padding) * 4</p>\n\n<p>For Layer II & III files use this formula:</p>\n\n<p>FrameLengthInBytes = 144 * BitRate / SampleRate + Padding </p>\n\n<p><a href=\"http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm\" rel=\"nofollow noreferrer\">Information about MPEG Audio Frame Header</a></p>\n"
},
{
"answer_id": 119616,
"author": "Matt Blaine",
"author_id": 16272,
"author_profile": "https://Stackoverflow.com/users/16272",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p>Simple, parse MP3 binary blob to calculate something, in Python</p>\n </blockquote>\n</blockquote>\n\n<p>That sounds like a pretty tall order. I don't know Python, but here's some code I've refactored from another program I once tried to write.</p>\n\n<p><strong>Note:</strong> It's in C++ (sorry, it's what I've got). Also, as-is, it'll only handle constant bit rate MPEG 1 Audio Layer 3 files. That <em>should</em> cover most, but I can't make any guarantee as to this working in all situations. Hopefully this does what you want, and hopefully refactoring it into Python is easier than doing it from scratch.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>// determines the duration, in seconds, of an MP3;\n// assumes MPEG 1 (not 2 or 2.5) Audio Layer 3 (not 1 or 2)\n// constant bit rate (not variable)\n\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n\nusing namespace std;\n\n//Bitrates, assuming MPEG 1 Audio Layer 3\nconst int bitrates[16] = {\n 0, 32000, 40000, 48000, 56000, 64000, 80000, 96000,\n 112000, 128000, 160000, 192000, 224000, 256000, 320000, 0\n };\n\n\n//Intel processors are little-endian;\n//search Google or see: http://en.wikipedia.org/wiki/Endian\nint reverse(int i)\n{\n int toReturn = 0;\n toReturn |= ((i & 0x000000FF) << 24);\n toReturn |= ((i & 0x0000FF00) << 8);\n toReturn |= ((i & 0x00FF0000) >> 8);\n toReturn |= ((i & 0xFF000000) >> 24);\n return toReturn;\n}\n\n//In short, data in ID3v2 tags are stored as\n//\"syncsafe integers\". This is so the tag info\n//isn't mistaken for audio data, and attempted to\n//be \"played\". For more info, have fun Googling it.\nint syncsafe(int i)\n{\n int toReturn = 0;\n toReturn |= ((i & 0x7F000000) >> 24);\n toReturn |= ((i & 0x007F0000) >> 9);\n toReturn |= ((i & 0x00007F00) << 6);\n toReturn |= ((i & 0x0000007F) << 21);\n return toReturn; \n}\n\n//How much room does ID3 version 1 tag info\n//take up at the end of this file (if any)?\nint id3v1size(ifstream& infile)\n{\n streampos savePos = infile.tellg(); \n\n //get to 128 bytes from file end\n infile.seekg(0, ios::end);\n streampos length = infile.tellg() - (streampos)128;\n infile.seekg(length);\n\n int size;\n char buffer[3] = {0};\n infile.read(buffer, 3);\n if( buffer[0] == 'T' && buffer[1] == 'A' && buffer[2] == 'G' )\n size = 128; //found tag data\n else\n size = 0; //nothing there\n\n infile.seekg(savePos);\n\n return size;\n\n}\n\n//how much room does ID3 version 2 tag info\n//take up at the beginning of this file (if any)\nint id3v2size(ifstream& infile)\n{\n streampos savePos = infile.tellg(); \n infile.seekg(0, ios::beg);\n\n char buffer[6] = {0};\n infile.read(buffer, 6);\n if( buffer[0] != 'I' || buffer[1] != 'D' || buffer[2] != '3' )\n { \n //no tag data\n infile.seekg(savePos);\n return 0;\n }\n\n int size = 0;\n infile.read(reinterpret_cast<char*>(&size), sizeof(size));\n size = syncsafe(size);\n\n infile.seekg(savePos);\n //\"size\" doesn't include the 10 byte ID3v2 header\n return size + 10;\n}\n\nint main(int argCount, char* argValues[])\n{\n //you'll have to change this\n ifstream infile(\"C:/Music/Bush - Comedown.mp3\", ios::binary);\n\n if(!infile.is_open())\n {\n infile.close();\n cout << \"Error opening file\" << endl;\n system(\"PAUSE\");\n return 0;\n }\n\n //determine beginning and end of primary frame data (not ID3 tags)\n infile.seekg(0, ios::end);\n streampos dataEnd = infile.tellg();\n\n infile.seekg(0, ios::beg);\n streampos dataBegin = 0;\n\n dataEnd -= id3v1size(infile);\n dataBegin += id3v2size(infile);\n\n infile.seekg(dataBegin,ios::beg);\n\n //determine bitrate based on header for first frame of audio data\n int headerBytes = 0;\n infile.read(reinterpret_cast<char*>(&headerBytes),sizeof(headerBytes));\n\n headerBytes = reverse(headerBytes);\n int bitrate = bitrates[(int)((headerBytes >> 12) & 0xF)];\n\n //calculate duration, in seconds\n int duration = (dataEnd - dataBegin)/(bitrate/8);\n\n infile.close();\n\n //print duration in minutes : seconds\n cout << duration/60 << \":\" << duration%60 << endl;\n\n system(\"PAUSE\");\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 5059165,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 3,
"selected": false,
"text": "<p>For google followers' sake, here are a few more external libs:</p>\n\n<p>mpg321 -t</p>\n\n<p>ffmpeg -i</p>\n\n<p>midentify (mplayer basically) see <a href=\"https://stackoverflow.com/questions/497681/using-mplayer-to-determine-length-of-audio-video-file\">Using mplayer to determine length of audio/video file</a></p>\n\n<p>mencoder (pass it invalid params, it will spit out an error message but also give you info on the file in question, ex $ mencoder inputfile.mp3 -o fake)</p>\n\n<p>mediainfo program <a href=\"http://mediainfo.sourceforge.net/en\" rel=\"nofollow noreferrer\">http://mediainfo.sourceforge.net/en</a></p>\n\n<p>exiftool</p>\n\n<p>the linux \"file\" command</p>\n\n<p>mp3info</p>\n\n<p>sox</p>\n\n<p>refs:\n<a href=\"https://superuser.com/questions/36871/linux-command-line-utility-to-determine-mp3-bitrate\">https://superuser.com/questions/36871/linux-command-line-utility-to-determine-mp3-bitrate</a></p>\n\n<p><a href=\"http://www.ruby-forum.com/topic/139468\" rel=\"nofollow noreferrer\">http://www.ruby-forum.com/topic/139468</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/993971/mp3-length-in-milliseconds\">mp3 length in milliseconds</a></p>\n\n<p>(making this a wiki for others to add to).</p>\n\n<p>and libs: .net: naudio, java: jlayer, c: libmad</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 10132100,
"author": "Bala Clark",
"author_id": 55825,
"author_profile": "https://Stackoverflow.com/users/55825",
"pm_score": 2,
"selected": false,
"text": "<p>Also take a look at audioread (some linux distros including ubuntu have packages), <a href=\"https://github.com/sampsyo/audioread\" rel=\"nofollow\">https://github.com/sampsyo/audioread</a></p>\n\n<pre><code>audio = audioread.audio_open('/path/to/mp3')\nprint audio.channels, audio.samplerate, audio.duration\n</code></pre>\n"
},
{
"answer_id": 29028948,
"author": "Johnny Zhao",
"author_id": 1523716,
"author_profile": "https://Stackoverflow.com/users/1523716",
"pm_score": 3,
"selected": false,
"text": "<p>simply use <code>mutagen</code></p>\n\n<pre><code>$pip install mutagen\n</code></pre>\n\n<p>use it in python shell:</p>\n\n<pre><code>from mutagen.mp3 import MP3\naudio = MP3(file_path)\nprint audio.info.length\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9440/"
]
| What is the simplest way to determine the length (in seconds) of a given mp3 file, **without using outside libraries**? (python source highly appreciated) | You can use [pymad](http://spacepants.org/src/pymad/). It's an external library, but don't fall for the Not Invented Here trap. Any particular reason you don't want any external libraries?
```
import mad
mf = mad.MadFile("foo.mp3")
track_length_in_milliseconds = mf.total_time()
```
Spotted [here](http://simonwillison.net/2003/Dec/4/mp3lengths/).
--
If you really don't want to use an external library, have a look [here](http://ibofobi.dk/stuff/mp3/) and check out how he's done it. Warning: it's complicated. |
119,426 | <p>Are there any industry standard conventions for naming jar files?</p>
| [
{
"answer_id": 119430,
"author": "Ron Tuffin",
"author_id": 939,
"author_profile": "https://Stackoverflow.com/users/939",
"pm_score": 6,
"selected": true,
"text": "<p>I have been using </p>\n\n<pre><code>*Informative*-*name*-*M*.*m*.*b*.jar\n</code></pre>\n\n<p>Where:</p>\n\n<p><em>M</em> = <code>major version number</code> (changed when backward compatibility is not necessarily maintained)</p>\n\n<p><em>m</em> = <code>minor version number</code> (feature additions etc)</p>\n\n<p><em>b</em> = <code>build number</code> (for releases containing bug fixes)</p>\n"
},
{
"answer_id": 34895253,
"author": "wdk",
"author_id": 227061,
"author_profile": "https://Stackoverflow.com/users/227061",
"pm_score": 2,
"selected": false,
"text": "<p>If your jar is used for JEE then <a href=\"http://www.oracle.com/technetwork/java/namingconventions-139351.html\" rel=\"nofollow\">these guidelines</a> apply:</p>\n\n<blockquote>\n <p>The module name is used as the EJB archive name. By default, the\n module name should be based on the package name and should be written\n in all-lowercase ASCII letters. In case of conflict, the module name\n should be a more specific version (including other part of the package\n name):</p>\n \n <p>EJB archive: -ejb.jar</p>\n \n <p>EJB client archive: -ejb-client.jar</p>\n</blockquote>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939/"
]
| Are there any industry standard conventions for naming jar files? | I have been using
```
*Informative*-*name*-*M*.*m*.*b*.jar
```
Where:
*M* = `major version number` (changed when backward compatibility is not necessarily maintained)
*m* = `minor version number` (feature additions etc)
*b* = `build number` (for releases containing bug fixes) |
119,432 | <p>Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing.</p>
<p>Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)?</p>
| [
{
"answer_id": 119442,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>You could potentially make an Ajax call to the server from a try/catch, but that's probably about the best you can do.</p>\n\n<p>May I suggest JavaScript unit testing instead? Possibly with <a href=\"https://github.com/pivotal/jsunit\" rel=\"nofollow noreferrer\">JSUnit</a>?</p>\n"
},
{
"answer_id": 119510,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 7,
"selected": true,
"text": "<p>You could try setting up your own handler for the <a href=\"http://developer.mozilla.org/En/DOM:window.onerror\" rel=\"noreferrer\">onerror event</a> and use XMLHttpRequest to tell the server what went wrong, however since it's not part of any specification, <a href=\"http://www.quirksmode.org/dom/events/error.html\" rel=\"noreferrer\">support is somewhat flaky</a>.</p>\n\n<p>Here's an example from <a href=\"http://www.the-art-of-web.com/javascript/ajax-onerror/\" rel=\"noreferrer\">Using XMLHttpRequest to log JavaScript errors</a>:</p>\n\n<pre><code>window.onerror = function(msg, url, line)\n{\n var req = new XMLHttpRequest();\n var params = \"msg=\" + encodeURIComponent(msg) + '&amp;url=' + encodeURIComponent(url) + \"&amp;line=\" + line;\n req.open(\"POST\", \"/scripts/logerror.php\");\n req.send(params);\n};\n</code></pre>\n"
},
{
"answer_id": 119546,
"author": "cleg",
"author_id": 29503,
"author_profile": "https://Stackoverflow.com/users/29503",
"pm_score": 0,
"selected": false,
"text": "<p>Also I recomend using <a href=\"http://tracetool.sourceforge.net/\" rel=\"nofollow noreferrer\">TraceTool</a> utility, it comes with JavaScript support and is very handy for JS monitoring.</p>\n"
},
{
"answer_id": 119634,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 0,
"selected": false,
"text": "<p>If you're wanting to log the client-side errors back to the server you're going to have to do some kind of server processing. Best bet would be to have a web service which you can access via JavaScript (AJAX) and you pass your error log info to it.</p>\n\n<p>Doesn't 100% solve the problem cuz if the problem is with the web server hosting the web service you're in trouble, you're other option would be to send the info via a standard page via a query string, One method of doing that is via dynamically generating Image tags (which are then removed) as the browser will try and load the source of an image. It gets around cross-domain JavaScript calls nicely though. Keep in mind that you're in trouble if someone has images turned off ;)</p>\n"
},
{
"answer_id": 120614,
"author": "Karl",
"author_id": 2932,
"author_profile": "https://Stackoverflow.com/users/2932",
"pm_score": 4,
"selected": false,
"text": "<p>I have just implemented server side error logging on javascript errors on a project at work. There is a mixture of legacy code and new code using <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a>. </p>\n\n<p>I use a combination of <code>window.onerror</code> and wrapping the jQuery event handlers and onready function with an error handling function (see: <a href=\"http://blogs.cozi.com/tech/2008/04/javascript-error-tracking-why-windowonerror-is-not-enough.html\" rel=\"noreferrer\">JavaScript Error Tracking: Why window.onerror Is Not Enough</a>).</p>\n\n<ul>\n<li><code>window.onerror</code>: catches all errrors in IE (and most errors in Firefox), but does nothing in Safari and Opera.</li>\n<li>jQuery event handlers: catches jQuery event errors in all browsers.</li>\n<li>jQuery ready function: catches initialisation errors in all browsers.</li>\n</ul>\n\n<p>Once I have caught the error, I add some extra properties to it (url, browser, etc) and then post it back to the server using an ajax call.</p>\n\n<p>On the server I have a small page which just takes the posted arguments and outputs them to our normal server logging framework.</p>\n\n<p><em>I would like to open source the code for this (as a jQuery plugin). If anyone is interested let me know, it would help to convince the bosses!</em></p>\n"
},
{
"answer_id": 7415609,
"author": "Ztyx",
"author_id": 260805,
"author_profile": "https://Stackoverflow.com/users/260805",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Short answer:</strong> Yes, it is possible.</p>\n\n<p><strong>Longer answer:</strong> People have already written about how you can (at least partially) solve this issue by writing your own code. However, do note that there are services out there that seems to have made sure the JS code needed works in many browsers. I've found the following:</p>\n\n<ul>\n<li><a href=\"http://trackjs.com\" rel=\"noreferrer\">http://trackjs.com</a></li>\n<li><a href=\"https://www.atatus.com\" rel=\"noreferrer\">https://www.atatus.com</a></li>\n<li><a href=\"http://jserrlog.appspot.com\" rel=\"noreferrer\">http://jserrlog.appspot.com</a></li>\n<li><a href=\"http://muscula.com\" rel=\"noreferrer\">http://muscula.com</a></li>\n<li><a href=\"https://sentry.io\" rel=\"noreferrer\">https://sentry.io</a></li>\n<li><a href=\"https://rollbar.com\" rel=\"noreferrer\">https://rollbar.com</a></li>\n<li><a href=\"https://catchjs.com\" rel=\"noreferrer\">https://catchjs.com</a></li>\n</ul>\n\n<p>I can't speak for any of these services as I haven't tried them yet.</p>\n"
},
{
"answer_id": 14676224,
"author": "levelnis",
"author_id": 1859009,
"author_profile": "https://Stackoverflow.com/users/1859009",
"pm_score": 0,
"selected": false,
"text": "<p>I've been using <a href=\"https://appfail.net/\" rel=\"nofollow\">Appfail</a> recently, which captures both asp.net and JavaScript errors</p>\n"
},
{
"answer_id": 16024977,
"author": "Leandro Lages",
"author_id": 1784149,
"author_profile": "https://Stackoverflow.com/users/1784149",
"pm_score": 2,
"selected": false,
"text": "<p>If you use Google Analytics, you can log javascript errors into Google Analytics Events.</p>\n\n<p>See this app: <a href=\"http://siteapps.com/app/log_javascript_errors_with_ga-181\" rel=\"nofollow\">http://siteapps.com/app/log_javascript_errors_with_ga-181</a></p>\n\n<p>Hope it helps.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17558/"
]
| Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing.
Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)? | You could try setting up your own handler for the [onerror event](http://developer.mozilla.org/En/DOM:window.onerror) and use XMLHttpRequest to tell the server what went wrong, however since it's not part of any specification, [support is somewhat flaky](http://www.quirksmode.org/dom/events/error.html).
Here's an example from [Using XMLHttpRequest to log JavaScript errors](http://www.the-art-of-web.com/javascript/ajax-onerror/):
```
window.onerror = function(msg, url, line)
{
var req = new XMLHttpRequest();
var params = "msg=" + encodeURIComponent(msg) + '&url=' + encodeURIComponent(url) + "&line=" + line;
req.open("POST", "/scripts/logerror.php");
req.send(params);
};
``` |
119,441 | <p>I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:</p>
<pre class="lang-html prettyprint-override"><code><p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
</code></pre>
<p>How do I convert the above to something like this:</p>
<pre class="lang-html prettyprint-override"><code><p>
Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit.
</p>
<p>
Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper
libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
</code></pre>
<p>Is this possible with jQuery?</p>
<p><strong>Edit</strong>: As <a href="https://stackoverflow.com/users/9535/sebastian-hoitz">Sebastian</a> <a href="https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery#119450">pointed out</a>, this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy.</p>
| [
{
"answer_id": 119450,
"author": "Sebastian Hoitz",
"author_id": 9535,
"author_profile": "https://Stackoverflow.com/users/9535",
"pm_score": 1,
"selected": false,
"text": "<p>You need to get the content of the p tag and replace all the dolors in it with the highlighted version.</p>\n\n<p>You don't even need to have jQuery for this. :-)</p>\n"
},
{
"answer_id": 119473,
"author": "mlarsen",
"author_id": 17700,
"author_profile": "https://Stackoverflow.com/users/17700",
"pm_score": 7,
"selected": true,
"text": "<p><del>Try <a href=\"http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html\" rel=\"nofollow noreferrer\">highlight: JavaScript text highlighting jQuery plugin</a>.</del>\n<strong>Warning: The source code available on this page contains a cryptocurrency mining script, either use the code below or remove the mining script from the script downloaded from the website.</strong></p>\n<pre><code>/*\n\nhighlight v4\n\nHighlights arbitrary terms.\n\n<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>\n\nMIT license.\n\nJohann Burkard\n<http://johannburkard.de>\n<mailto:[email protected]>\n\n*/\n\njQuery.fn.highlight = function(pat) {\n function innerHighlight(node, pat) {\n var skip = 0;\n if (node.nodeType == 3) {\n var pos = node.data.toUpperCase().indexOf(pat);\n if (pos >= 0) {\n var spannode = document.createElement('span');\n spannode.className = 'highlight';\n var middlebit = node.splitText(pos);\n var endbit = middlebit.splitText(pat.length);\n var middleclone = middlebit.cloneNode(true);\n spannode.appendChild(middleclone);\n middlebit.parentNode.replaceChild(spannode, middlebit);\n skip = 1;\n }\n }\n else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {\n for (var i = 0; i < node.childNodes.length; ++i) {\n i += innerHighlight(node.childNodes[i], pat);\n }\n }\n return skip;\n }\n return this.length && pat && pat.length ? this.each(function() {\n innerHighlight(this, pat.toUpperCase());\n }) : this;\n};\n\njQuery.fn.removeHighlight = function() {\n return this.find("span.highlight").each(function() {\n this.parentNode.firstChild.nodeName;\n with (this.parentNode) {\n replaceChild(this.firstChild, this);\n normalize();\n }\n }).end();\n};\n</code></pre>\n<p>Also try the <a href=\"http://bartaz.github.com/sandbox.js/jquery.highlight.html\" rel=\"nofollow noreferrer\">"updated" version of the original script</a>.</p>\n<pre><code>/*\n * jQuery Highlight plugin\n *\n * Based on highlight v3 by Johann Burkard\n * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html\n *\n * Code a little bit refactored and cleaned (in my humble opinion).\n * Most important changes:\n * - has an option to highlight only entire words (wordsOnly - false by default),\n * - has an option to be case sensitive (caseSensitive - false by default)\n * - highlight element tag and class names can be specified in options\n *\n * Usage:\n * // wrap every occurrance of text 'lorem' in content\n * // with <span class='highlight'> (default options)\n * $('#content').highlight('lorem');\n *\n * // search for and highlight more terms at once\n * // so you can save some time on traversing DOM\n * $('#content').highlight(['lorem', 'ipsum']);\n * $('#content').highlight('lorem ipsum');\n *\n * // search only for entire word 'lorem'\n * $('#content').highlight('lorem', { wordsOnly: true });\n *\n * // don't ignore case during search of term 'lorem'\n * $('#content').highlight('lorem', { caseSensitive: true });\n *\n * // wrap every occurrance of term 'ipsum' in content\n * // with <em class='important'>\n * $('#content').highlight('ipsum', { element: 'em', className: 'important' });\n *\n * // remove default highlight\n * $('#content').unhighlight();\n *\n * // remove custom highlight\n * $('#content').unhighlight({ element: 'em', className: 'important' });\n *\n *\n * Copyright (c) 2009 Bartek Szopka\n *\n * Licensed under MIT license.\n *\n */\n\njQuery.extend({\n highlight: function (node, re, nodeName, className) {\n if (node.nodeType === 3) {\n var match = node.data.match(re);\n if (match) {\n var highlight = document.createElement(nodeName || 'span');\n highlight.className = className || 'highlight';\n var wordNode = node.splitText(match.index);\n wordNode.splitText(match[0].length);\n var wordClone = wordNode.cloneNode(true);\n highlight.appendChild(wordClone);\n wordNode.parentNode.replaceChild(highlight, wordNode);\n return 1; //skip added node in parent\n }\n } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children\n !/(script|style)/i.test(node.tagName) && // ignore script and style nodes\n !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted\n for (var i = 0; i < node.childNodes.length; i++) {\n i += jQuery.highlight(node.childNodes[i], re, nodeName, className);\n }\n }\n return 0;\n }\n});\n\njQuery.fn.unhighlight = function (options) {\n var settings = { className: 'highlight', element: 'span' };\n jQuery.extend(settings, options);\n\n return this.find(settings.element + "." + settings.className).each(function () {\n var parent = this.parentNode;\n parent.replaceChild(this.firstChild, this);\n parent.normalize();\n }).end();\n};\n\njQuery.fn.highlight = function (words, options) {\n var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };\n jQuery.extend(settings, options);\n \n if (words.constructor === String) {\n words = [words];\n }\n words = jQuery.grep(words, function(word, i){\n return word != '';\n });\n words = jQuery.map(words, function(word, i) {\n return word.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n });\n if (words.length == 0) { return this; };\n\n var flag = settings.caseSensitive ? "" : "i";\n var pattern = "(" + words.join("|") + ")";\n if (settings.wordsOnly) {\n pattern = "\\\\b" + pattern + "\\\\b";\n }\n var re = new RegExp(pattern, flag);\n \n return this.each(function () {\n jQuery.highlight(this, re, settings.element, settings.className);\n });\n};\n</code></pre>\n"
},
{
"answer_id": 120161,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 5,
"selected": false,
"text": "<pre><code>function hiliter(word, element) {\n var rgxp = new RegExp(word, 'g');\n var repl = '<span class=\"myClass\">' + word + '</span>';\n element.innerHTML = element.innerHTML.replace(rgxp, repl);\n}\nhiliter('dolor');\n</code></pre>\n"
},
{
"answer_id": 405908,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Is it possible to get this above example:</p>\n\n<pre><code>jQuery.fn.highlight = function (str, className)\n{\n var regex = new RegExp(str, \"g\");\n\n return this.each(function ()\n {\n this.innerHTML = this.innerHTML.replace(\n regex,\n \"<span class=\\\"\" + className + \"\\\">\" + str + \"</span>\"\n );\n });\n};\n</code></pre>\n\n<p>not to replace text inside html-tags like , this otherwise breakes the page.</p>\n"
},
{
"answer_id": 2676556,
"author": "bjarlestam",
"author_id": 321463,
"author_profile": "https://Stackoverflow.com/users/321463",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a variation that ignores and preserves case:</p>\n\n<pre><code>jQuery.fn.highlight = function (str, className) {\n var regex = new RegExp(\"\\\\b\"+str+\"\\\\b\", \"gi\");\n\n return this.each(function () {\n this.innerHTML = this.innerHTML.replace(regex, function(matched) {return \"<span class=\\\"\" + className + \"\\\">\" + matched + \"</span>\";});\n });\n};\n</code></pre>\n"
},
{
"answer_id": 15007014,
"author": "Hawkee",
"author_id": 461272,
"author_profile": "https://Stackoverflow.com/users/461272",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote a very simple function that uses jQuery to iterate the elements wrapping each keyword with a .highlight class.</p>\n\n<pre><code>function highlight_words(word, element) {\n if(word) {\n var textNodes;\n word = word.replace(/\\W/g, '');\n var str = word.split(\" \");\n $(str).each(function() {\n var term = this;\n var textNodes = $(element).contents().filter(function() { return this.nodeType === 3 });\n textNodes.each(function() {\n var content = $(this).text();\n var regex = new RegExp(term, \"gi\");\n content = content.replace(regex, '<span class=\"highlight\">' + term + '</span>');\n $(this).replaceWith(content);\n });\n });\n }\n}\n</code></pre>\n\n<p>More info:</p>\n\n<p><a href=\"http://www.hawkee.com/snippet/9854/\" rel=\"nofollow\">http://www.hawkee.com/snippet/9854/</a></p>\n"
},
{
"answer_id": 30569608,
"author": "iamawebgeek",
"author_id": 3796431,
"author_profile": "https://Stackoverflow.com/users/3796431",
"pm_score": 2,
"selected": false,
"text": "<p>You can use my highlight plugin <a href=\"https://github.com/iamwebdesigner/jQuiteLight\" rel=\"nofollow\">jQuiteLight</a>, that can also work with regular expressions.</p>\n\n<p><strong>To install using <a href=\"http://npmjs.com\" rel=\"nofollow\">npm</a> type:</strong></p>\n\n<pre><code>npm install jquitelight --save\n</code></pre>\n\n<p><strong>To install using <a href=\"http://bower.io\" rel=\"nofollow\">bower</a> type:</strong></p>\n\n<pre><code>bower install jquitelight \n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>// for strings\n$(\".element\").mark(\"query here\");\n// for RegExp\n$(\".element\").mark(new RegExp(/query h[a-z]+/));\n</code></pre>\n\n<p><strong>More advanced usage <a href=\"https://github.com/iamwebdesigner/jQuiteLight#advanced-usage-tricks\" rel=\"nofollow\">here</a></strong></p>\n"
},
{
"answer_id": 32758672,
"author": "dude",
"author_id": 3894981,
"author_profile": "https://Stackoverflow.com/users/3894981",
"pm_score": 5,
"selected": false,
"text": "<h1>Why using a selfmade highlighting function is a bad idea</h1>\n\n<p>The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:</p>\n\n<ul>\n<li>You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. <code>innerHTML</code>)</li>\n<li>If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.</li>\n<li>You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!</li>\n</ul>\n\n<p>Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.</p>\n\n<h1>Use an existing plugin</h1>\n\n<p>When using an existing, well implemented plugin, you don't have to worry about above named things. The article <strong><a href=\"https://www.sitepoint.com/10-jquery-text-highlighter-plugins/\" rel=\"noreferrer\">10 jQuery text highlighter plugins</a></strong> on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.</p>\n\n<h1>Have a look at <a href=\"https://markjs.io/\" rel=\"noreferrer\">mark.js</a></h1>\n\n<p><a href=\"https://markjs.io/\" rel=\"noreferrer\">mark.js</a> is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:</p>\n\n<ul>\n<li>search for keywords separately instead of the complete term</li>\n<li>map diacritics (For example if \"justo\" should also match \"justò\")</li>\n<li>ignore matches inside custom elements</li>\n<li>use custom highlighting element</li>\n<li>use custom highlighting class</li>\n<li>map custom synonyms</li>\n<li>search also inside iframes</li>\n<li>receive not found terms</li>\n</ul>\n\n<p><strong><a href=\"https://markjs.io/configurator.html\" rel=\"noreferrer\">DEMO</a></strong></p>\n\n<p>Alternatively you can see <a href=\"https://jsfiddle.net/julmot/vpav6tL1/\" rel=\"noreferrer\">this fiddle</a>.</p>\n\n<p><strong>Usage example</strong>:</p>\n\n<pre><code>// Highlight \"keyword\" in the specified context\n$(\".context\").mark(\"keyword\");\n\n// Highlight the custom regular expression in the specified context\n$(\".context\").markRegExp(/Lorem/gmi);\n</code></pre>\n\n<p>It's free and developed open-source on GitHub (<a href=\"https://github.com/julmot/mark.js\" rel=\"noreferrer\">project reference</a>).</p>\n"
},
{
"answer_id": 33545382,
"author": "L.Grillo",
"author_id": 1764509,
"author_profile": "https://Stackoverflow.com/users/1764509",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$(function () {\n $(\"#txtSearch\").keyup(function (event) {\n var txt = $(\"#txtSearch\").val()\n if (txt.length > 3) {\n $(\"span.hilightable\").each(function (i, v) {\n v.innerHTML = v.innerText.replace(txt, \"<hilight>\" + txt + \"</hilight>\");\n });\n\n }\n });\n});\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/xs019c6z/\" rel=\"nofollow\">Jfiddle</a> here</p>\n"
},
{
"answer_id": 40007548,
"author": "abe312",
"author_id": 3719699,
"author_profile": "https://Stackoverflow.com/users/3719699",
"pm_score": -1,
"selected": false,
"text": "<p><strong>I have created a <a href=\"https://github.com/abe312/colors.js\" rel=\"nofollow\">repository</a> on similar concept that changes the colors of the texts whose colors are recognised by html5 (we don't have to use actual #rrggbb values and could just use the names as html5 standardised about 140 of them)</strong></p>\n\n<p><strong><em><a href=\"https://github.com/abe312/colors.js\" rel=\"nofollow\">colors.js</a></em></strong>\n<a href=\"https://i.stack.imgur.com/6W9eB.png\" rel=\"nofollow\"><img src=\"https://i.stack.imgur.com/6W9eB.png\" alt=\"colors.js\"></a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$( document ).ready(function() {\r\n \r\n function hiliter(word, element) {\r\n var rgxp = new RegExp(\"\\\\b\" + word + \"\\\\b\" , 'gi'); // g modifier for global and i for case insensitive \r\n var repl = '<span class=\"myClass\">' + word + '</span>';\r\n element.innerHTML = element.innerHTML.replace(rgxp, repl);\r\n \r\n };\r\n\r\n hiliter('dolor', document.getElementById('dolor'));\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.myClass{\r\n\r\nbackground-color:red;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\r\n<html>\r\n <head>\r\n <title>highlight</title>\r\n \r\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js\"></script>\r\n \r\n <link href=\"main.css\" type=\"text/css\" rel=\"stylesheet\"/>\r\n \r\n </head>\r\n <body id='dolor'>\r\n<p >\r\n Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n</p>\r\n<p>\r\n Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.\r\n Aliquam rhoncus eros at augue. Suspendisse vitae mauris.\r\n</p>\r\n <script type=\"text/javascript\" src=\"main.js\" charset=\"utf-8\"></script>\r\n </body>\r\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 44744765,
"author": "Van Peer",
"author_id": 1836483,
"author_profile": "https://Stackoverflow.com/users/1836483",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://jsfiddle.net/vanpeer/kdahpLck/\" rel=\"nofollow noreferrer\">JSFiddle</a></p>\n<p>Uses <code>.each()</code>, <code>.replace()</code>, <code>.html()</code>. Tested with jQuery 1.11 and 3.2.</p>\n<p>In the above example, reads the 'keyword' to be highlighted and appends span tag with the 'highlight' class. The text 'keyword' is highlighted for all selected classes in the <code>.each()</code>.</p>\n<p>HTML</p>\n<pre class=\"lang-html prettyprint-override\"><code><body>\n <label name="lblKeyword" id="lblKeyword" class="highlight">keyword</label>\n <p class="filename">keyword</p>\n <p class="content">keyword</p>\n <p class="system"><i>keyword</i></p>\n</body>\n</code></pre>\n<p>JS</p>\n<pre class=\"lang-js prettyprint-override\"><code>$(document).ready(function() {\n var keyWord = $("#lblKeyword").text(); \n var replaceD = "<span class='highlight'>" + keyWord + "</span>";\n $(".system, .filename, .content").each(function() {\n var text = $(this).text();\n text = text.replace(keyWord, replaceD);\n $(this).html(text);\n });\n});\n</code></pre>\n<p>CSS</p>\n<pre class=\"lang-css prettyprint-override\"><code>.highlight {\n background-color: yellow;\n}\n</code></pre>\n"
},
{
"answer_id": 49041257,
"author": "Cybernetic",
"author_id": 1639594,
"author_profile": "https://Stackoverflow.com/users/1639594",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the following <strong>function</strong> to highlight any word in your text.</p>\n<pre><code>function color_word(text_id, word, color) {\n words = $('#' + text_id).text().split(' ');\n words = words.map(function(item) { return item == word ? "<span style='color: " + color + "'>" + word + '</span>' : item });\n new_words = words.join(' ');\n $('#' + text_id).html(new_words);\n }\n</code></pre>\n<p>Simply <em>target the element</em> that contains the text, <em>choosing the word</em> to colorize and the <em>color</em> of choice.</p>\n<p>Here is an <strong>example</strong>:</p>\n<pre><code><div id='my_words'>\nThis is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery's html() function will produce the desired result.\n</div>\n</code></pre>\n<p><strong>Usage</strong>,</p>\n<pre><code>color_word('my_words', 'possible', 'hotpink')\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/Ht1Ai.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ht1Ai.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 73156791,
"author": "Akhtarujjaman Shuvo",
"author_id": 6286562,
"author_profile": "https://Stackoverflow.com/users/6286562",
"pm_score": 0,
"selected": false,
"text": "<p>This is a modified version from @bjarlestam.</p>\n<p>This will only search text.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>jQuery.fn.highlight = function(str) {\n var regex = new RegExp(str, \"gi\");\n return this.each(function() {\n this.innerHTML = this.innerText.replace(regex, function(matched) {\n return \"<span class='mark'>\" + matched + \"</span>\";\n });\n });\n};\n\n// Mark\njQuery('table tr td').highlight('desh')</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.mark {\n background: #fde293;\n color: #222;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<h2>HTML Table</h2>\n\n<table>\n <tr>\n <th>Company</th>\n <th>Contact</th>\n <th>Country</th>\n </tr>\n <tr>\n <td>Sodeshi</td>\n <td>Francisco Chang</td>\n <td>Mexico</td>\n </tr>\n <tr>\n <td>Ernst Handel</td>\n <td>Roland Mendel</td>\n <td>Austria</td>\n </tr>\n <tr>\n <td>Island Trading</td>\n <td>Helen Bennett</td>\n <td>Bangladesh</td>\n </tr>\n\n</table></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Usages: <code>jQuery('.selector').highlight('sample text')</code></p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
| I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:
```html
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
```
How do I convert the above to something like this:
```html
<p>
Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit.
</p>
<p>
Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper
libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
```
Is this possible with jQuery?
**Edit**: As [Sebastian](https://stackoverflow.com/users/9535/sebastian-hoitz) [pointed out](https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery#119450), this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy. | ~~Try [highlight: JavaScript text highlighting jQuery plugin](http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html).~~
**Warning: The source code available on this page contains a cryptocurrency mining script, either use the code below or remove the mining script from the script downloaded from the website.**
```
/*
highlight v4
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:[email protected]>
*/
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.length && pat && pat.length ? this.each(function() {
innerHighlight(this, pat.toUpperCase());
}) : this;
};
jQuery.fn.removeHighlight = function() {
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};
```
Also try the ["updated" version of the original script](http://bartaz.github.com/sandbox.js/jquery.highlight.html).
```
/*
* jQuery Highlight plugin
*
* Based on highlight v3 by Johann Burkard
* http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
*
* Code a little bit refactored and cleaned (in my humble opinion).
* Most important changes:
* - has an option to highlight only entire words (wordsOnly - false by default),
* - has an option to be case sensitive (caseSensitive - false by default)
* - highlight element tag and class names can be specified in options
*
* Usage:
* // wrap every occurrance of text 'lorem' in content
* // with <span class='highlight'> (default options)
* $('#content').highlight('lorem');
*
* // search for and highlight more terms at once
* // so you can save some time on traversing DOM
* $('#content').highlight(['lorem', 'ipsum']);
* $('#content').highlight('lorem ipsum');
*
* // search only for entire word 'lorem'
* $('#content').highlight('lorem', { wordsOnly: true });
*
* // don't ignore case during search of term 'lorem'
* $('#content').highlight('lorem', { caseSensitive: true });
*
* // wrap every occurrance of term 'ipsum' in content
* // with <em class='important'>
* $('#content').highlight('ipsum', { element: 'em', className: 'important' });
*
* // remove default highlight
* $('#content').unhighlight();
*
* // remove custom highlight
* $('#content').unhighlight({ element: 'em', className: 'important' });
*
*
* Copyright (c) 2009 Bartek Szopka
*
* Licensed under MIT license.
*
*/
jQuery.extend({
highlight: function (node, re, nodeName, className) {
if (node.nodeType === 3) {
var match = node.data.match(re);
if (match) {
var highlight = document.createElement(nodeName || 'span');
highlight.className = className || 'highlight';
var wordNode = node.splitText(match.index);
wordNode.splitText(match[0].length);
var wordClone = wordNode.cloneNode(true);
highlight.appendChild(wordClone);
wordNode.parentNode.replaceChild(highlight, wordNode);
return 1; //skip added node in parent
}
} else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
!/(script|style)/i.test(node.tagName) && // ignore script and style nodes
!(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
for (var i = 0; i < node.childNodes.length; i++) {
i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
}
}
return 0;
}
});
jQuery.fn.unhighlight = function (options) {
var settings = { className: 'highlight', element: 'span' };
jQuery.extend(settings, options);
return this.find(settings.element + "." + settings.className).each(function () {
var parent = this.parentNode;
parent.replaceChild(this.firstChild, this);
parent.normalize();
}).end();
};
jQuery.fn.highlight = function (words, options) {
var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
jQuery.extend(settings, options);
if (words.constructor === String) {
words = [words];
}
words = jQuery.grep(words, function(word, i){
return word != '';
});
words = jQuery.map(words, function(word, i) {
return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
});
if (words.length == 0) { return this; };
var flag = settings.caseSensitive ? "" : "i";
var pattern = "(" + words.join("|") + ")";
if (settings.wordsOnly) {
pattern = "\\b" + pattern + "\\b";
}
var re = new RegExp(pattern, flag);
return this.each(function () {
jQuery.highlight(this, re, settings.element, settings.className);
});
};
``` |
119,462 | <p>I'd like to remove all of the black from a picture attached to a sprite so that it becomes transparent. </p>
| [
{
"answer_id": 124493,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This looks like it'll do the trick:</p>\n\n<p><a href=\"http://www.quartzcompositions.com/phpBB2/viewtopic.php?t=281\" rel=\"nofollow noreferrer\">http://www.quartzcompositions.com/phpBB2/viewtopic.php?t=281</a></p>\n"
},
{
"answer_id": 129688,
"author": "thescreamingdrills",
"author_id": 20824,
"author_profile": "https://Stackoverflow.com/users/20824",
"pm_score": 2,
"selected": false,
"text": "<p>I'll copy and paste in case that link dies:</p>\n\n<p><em>\" I used a 'Color Matrix' patch, setting 'Alpha Vector (W)' and 'Bias Vector(X,Y,Z)' to 1 and all other to 0.\nYou will then find the alpha channel from the input image at the output.\"</em> </p>\n\n<p>I found this before, but I can't figure out exactly how to do it. </p>\n\n<p>I found another solution using core image filter: </p>\n\n<pre><code>kernel vec4 darkToTransparent(sampler image)\n{\n vec4 color = sample(image, samplerCoord(image));\n color.a = (color.r+color.g+color.b) > 0.005 ? 1.0:0.;\n return color;\n}\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20824/"
]
| I'd like to remove all of the black from a picture attached to a sprite so that it becomes transparent. | I'll copy and paste in case that link dies:
*" I used a 'Color Matrix' patch, setting 'Alpha Vector (W)' and 'Bias Vector(X,Y,Z)' to 1 and all other to 0.
You will then find the alpha channel from the input image at the output."*
I found this before, but I can't figure out exactly how to do it.
I found another solution using core image filter:
```
kernel vec4 darkToTransparent(sampler image)
{
vec4 color = sample(image, samplerCoord(image));
color.a = (color.r+color.g+color.b) > 0.005 ? 1.0:0.;
return color;
}
``` |
119,477 | <p>I have an MSSQL2005 stored procedure here, which is supposed to take an XML message as input, and store it's content into a table.
The table fields are varchars, because our delphi backend application could not handle unicode.
Now, the messages that come in, are encoded ISO-8859-1. All is fine until characters over the > 128 standard set are included (in this case, ÄÖäö, which are an integral part of finnish). This causes the DB server to raise exception 0xc00ce508.
The database's default, as well as the table's and field's, collation is set to latin1, which should be the same as ISO-8859-1.</p>
<p>The XML message is parsed using the XML subsystem, like so:</p>
<pre><code>ALTER PROCEDURE [dbo].[parse] @XmlIn NVARCHAR(1000) AS
SET NOCOUNT ON
DECLARE @XmlDocumentHandle INT
DECLARE @XmlDocument VARCHAR(1000)
BEGIN
SET @XmlDocument = @XmlIn
EXECUTE sp_xml_preparedocument @XmlDocumentHandle OUTPUT, @XmlDocument
BEGIN TRANSACTION
//the xml message's fields are looped through here, and rows added or modified in two tables accordingly
// like ...
DECLARE TempCursor CURSOR FOR
SELECT AM_WORK_ID,CUSTNO,STYPE,REFE,VIN_NUMBER,REG_NO,VEHICLE_CONNO,READY_FOR_INVOICE,IS_SP,SMANID,INVOICENO,SUB_STATUS,TOTAL,TOTAL0,VAT,WRKORDNO
FROM OPENXML (@XmlDocumentHandle, '/ORDER_NEW_CP_REQ/ORDER_NEW_CUSTOMER_REQ',8)
WITH (AM_WORK_ID int '@EXIDNO',CUSTNO int '@CUSTNO',STYPE VARCHAR(1) '@STYPE',REFE VARCHAR(50) '@REFE',VIN_NUMBER VARCHAR(30) '@VEHICLE_VINNO',
REG_NO VARCHAR(20) '@VEHICLE_LICNO',VEHICLE_CONNO VARCHAR(30) '@VEHICLE_CONNO',READY_FOR_INVOICE INT '@READY_FOR_INVOICE',IS_SP INT '@IS_SP',
SMANID INT '@SMANID',INVOICENO INT '@INVOICENO',SUB_STATUS VARCHAR(1) '@SUB_STATUS',TOTAL NUMERIC(12,2) '@TOTAL',TOTAL0 NUMERIC(12,2) '@TOTAL0',VAT NUMERIC(12,2) '@VAT',WRKORDNO INT '@WRKORDNO')
OPEN TempCursor
FETCH NEXT FROM TempCursor
INTO @wAmWork,@wCustNo,@wType,@wRefe,@wVIN,@wReg,@wConNo,@wRdy,@wIsSp,@wSMan,@wInvoNo,@wSubStatus,@wTot,@wTot0,@wVat,@wWrkOrdNo
// ... etc
COMMIT TRANSACTION
EXECUTE sp_xml_removedocument @XmlDocumentHandle
END
</code></pre>
<p>Previously, the stored procedure used to use nvarchar for input, but since that caused problems with the ancient backend application (Delphi 5 + ODBC), we had to switch the fields to varchars, at which point everything broke.</p>
<p>I also tried taking in nvarchar and converting that to varchar at the start, but the result is the same.</p>
| [
{
"answer_id": 119836,
"author": "TToni",
"author_id": 20703,
"author_profile": "https://Stackoverflow.com/users/20703",
"pm_score": 0,
"selected": false,
"text": "<p>The errorcode you mention seems to come from the MSXML Library. How is that involved there? From your question I would assume that you pass a varchar parameter to a stored procedure, then insert or update a varchar column with that parameter.</p>\n\n<p>However that does not match with your exception code so it must happen outside of the actual stored procedure or you are doing additional things based on xml inside the stored procedure.</p>\n\n<p>Please check that and modify your question accordingly.</p>\n"
},
{
"answer_id": 120489,
"author": "anon6439",
"author_id": 15477,
"author_profile": "https://Stackoverflow.com/users/15477",
"pm_score": 1,
"selected": false,
"text": "<p>I'll answer my own question, since I managed to resolve the more than cryptic problem...</p>\n\n<p>1) The stored procedure must reflect the correct code page for the transformation:</p>\n\n<pre><code>@XmlIn NVARCHAR(2000)\n@XmlDocument VARCHAR(2000)\nSELECT @XmlDocument = @XmlIn COLLATE SQL_Latin1_General_CP1_CI_AS\n</code></pre>\n\n<p>2) The XML input must specify the same charset:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n</code></pre>\n"
},
{
"answer_id": 141394,
"author": "TToni",
"author_id": 20703,
"author_profile": "https://Stackoverflow.com/users/20703",
"pm_score": 2,
"selected": true,
"text": "<p>I don't know if anybody with enough rights to edit the answer will see this but while the answer is correct I would like to add that without specifying the collation explicitly the default collation of the database would be used in this case since it is implicitly assigned to every varchar-variable without a collation statement.</p>\n\n<p>So</p>\n\n<pre><code>DECLARE @XmlDocument VARCHAR(2000) COLLATE SQL_Latin1_General_CP1_CI_AS\n</code></pre>\n\n<p>should do the trick, too.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15477/"
]
| I have an MSSQL2005 stored procedure here, which is supposed to take an XML message as input, and store it's content into a table.
The table fields are varchars, because our delphi backend application could not handle unicode.
Now, the messages that come in, are encoded ISO-8859-1. All is fine until characters over the > 128 standard set are included (in this case, ÄÖäö, which are an integral part of finnish). This causes the DB server to raise exception 0xc00ce508.
The database's default, as well as the table's and field's, collation is set to latin1, which should be the same as ISO-8859-1.
The XML message is parsed using the XML subsystem, like so:
```
ALTER PROCEDURE [dbo].[parse] @XmlIn NVARCHAR(1000) AS
SET NOCOUNT ON
DECLARE @XmlDocumentHandle INT
DECLARE @XmlDocument VARCHAR(1000)
BEGIN
SET @XmlDocument = @XmlIn
EXECUTE sp_xml_preparedocument @XmlDocumentHandle OUTPUT, @XmlDocument
BEGIN TRANSACTION
//the xml message's fields are looped through here, and rows added or modified in two tables accordingly
// like ...
DECLARE TempCursor CURSOR FOR
SELECT AM_WORK_ID,CUSTNO,STYPE,REFE,VIN_NUMBER,REG_NO,VEHICLE_CONNO,READY_FOR_INVOICE,IS_SP,SMANID,INVOICENO,SUB_STATUS,TOTAL,TOTAL0,VAT,WRKORDNO
FROM OPENXML (@XmlDocumentHandle, '/ORDER_NEW_CP_REQ/ORDER_NEW_CUSTOMER_REQ',8)
WITH (AM_WORK_ID int '@EXIDNO',CUSTNO int '@CUSTNO',STYPE VARCHAR(1) '@STYPE',REFE VARCHAR(50) '@REFE',VIN_NUMBER VARCHAR(30) '@VEHICLE_VINNO',
REG_NO VARCHAR(20) '@VEHICLE_LICNO',VEHICLE_CONNO VARCHAR(30) '@VEHICLE_CONNO',READY_FOR_INVOICE INT '@READY_FOR_INVOICE',IS_SP INT '@IS_SP',
SMANID INT '@SMANID',INVOICENO INT '@INVOICENO',SUB_STATUS VARCHAR(1) '@SUB_STATUS',TOTAL NUMERIC(12,2) '@TOTAL',TOTAL0 NUMERIC(12,2) '@TOTAL0',VAT NUMERIC(12,2) '@VAT',WRKORDNO INT '@WRKORDNO')
OPEN TempCursor
FETCH NEXT FROM TempCursor
INTO @wAmWork,@wCustNo,@wType,@wRefe,@wVIN,@wReg,@wConNo,@wRdy,@wIsSp,@wSMan,@wInvoNo,@wSubStatus,@wTot,@wTot0,@wVat,@wWrkOrdNo
// ... etc
COMMIT TRANSACTION
EXECUTE sp_xml_removedocument @XmlDocumentHandle
END
```
Previously, the stored procedure used to use nvarchar for input, but since that caused problems with the ancient backend application (Delphi 5 + ODBC), we had to switch the fields to varchars, at which point everything broke.
I also tried taking in nvarchar and converting that to varchar at the start, but the result is the same. | I don't know if anybody with enough rights to edit the answer will see this but while the answer is correct I would like to add that without specifying the collation explicitly the default collation of the database would be used in this case since it is implicitly assigned to every varchar-variable without a collation statement.
So
```
DECLARE @XmlDocument VARCHAR(2000) COLLATE SQL_Latin1_General_CP1_CI_AS
```
should do the trick, too. |
119,548 | <p>I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients. </p>
<p>The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error:</p>
<blockquote>
<p>The process cannot access the file because it is being used by another process.</p>
</blockquote>
<p>The solutions that I have tried to implement in C# and failed are as below.</p>
<ol>
<li>Implemented singleton class that contains code that writes to a file.</li>
<li>Used lock statement to wrap the code that writes to the file. </li>
<li>I have also tried to use open source logger log4net but it also is not a perfect solution. </li>
<li>I know about logging to system event logger, but I do not have that choice.</li>
</ol>
<p>I want to know if there exists a perfect and complete solution to such a problem? </p>
| [
{
"answer_id": 119564,
"author": "Joel",
"author_id": 13713,
"author_profile": "https://Stackoverflow.com/users/13713",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe write a \"queue line\" of sorts for writing to the file, so when you try to write to the file it keeps checking to see if the file is locked, if it is - it keeps waiting, if it isn't locked - then write to it.</p>\n"
},
{
"answer_id": 119569,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>You could push the results onto an MSMQ Queue and have a windows service pick the items off of the queue and log them. It's a little heavy, but it should work.</p>\n"
},
{
"answer_id": 119599,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 5,
"selected": true,
"text": "<p>The locking is probably failing because your webservice is being run by more than one worker process.\nYou could protect the access with a named mutex, which is shared across processes, unlike the locks you get by using <code>lock(someobject) {...}</code>:</p>\n\n<pre><code>Mutex lock = new Mutex(\"mymutex\", false);\n\nlock.WaitOne();\n\n// access file\n\nlock.ReleaseMutex();\n</code></pre>\n"
},
{
"answer_id": 119604,
"author": "pradeeptp",
"author_id": 20933,
"author_profile": "https://Stackoverflow.com/users/20933",
"pm_score": 0,
"selected": false,
"text": "<p>Joel and charles. That was quick! :)</p>\n\n<p>Joel: When you say \"queue line\" do you mean creating a separate thread that runs in a loop to keep checking the queue as well as write to a file when it is not locked?</p>\n\n<p>Charles: I know about MSMQ and windows service combination, but like I said I have no choice other than writing to a file from within the web service :)</p>\n\n<p>thanks\npradeep_tp</p>\n"
},
{
"answer_id": 119641,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 0,
"selected": false,
"text": "<p>Trouble with all the approached tried so far is that multiple threads can enter the code.\nThat is multiple threads try to acquire and use the file handler - hence the errors - you need a single thread outside of the worker threads to do the work - with a single file handle held open.</p>\n\n<p>Probably easiest thing to do would be to create a thread during application start in Global.asax and have that listen to a synchronized in-memory queue (System.Collections.Generics.Queue). Have the thread open and own the lifetime of the file handle, only that thread can write to the file.</p>\n\n<p>Client requests in ASP will lock the queue momentarily, push the new logging message onto the queue, then unlock.</p>\n\n<p>The logger thread will poll the queue periodically for new messages - when messages arrive on the queue, the thread will read and dispatch the data in to the file.</p>\n"
},
{
"answer_id": 119645,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 1,
"selected": false,
"text": "<p>You don't say how your web service is hosted, so I'll assume it's in IIS. I don't think the file should be accessed by multiple processes unless your service runs in multiple application pools. Nevertheless, I guess you could get this error when multiple threads in one process are trying to write.</p>\n\n<p>I think I'd go for the solution you suggest yourself, Pradeep, build a single object that does all the writing to the log file. Inside that object I'd have a Queue into which all data to be logged gets written. I'd have a separate thread reading from this queue and writing to the log file. In a thread-pooled hosting environment like IIS, it doesn't seem too nice to create another thread, but it's only one... Bear in mind that the in-memory queue will not survive IIS resets; you might lose some entries that are \"in-flight\" when the IIS process goes down.</p>\n\n<p>Other alternatives certainly include using a separate process (such as a Service) to write to the file, but that has extra deployment overhead and IPC costs. If that doesn't work for you, go with the singleton.</p>\n"
},
{
"answer_id": 119646,
"author": "pradeeptp",
"author_id": 20933,
"author_profile": "https://Stackoverflow.com/users/20933",
"pm_score": 0,
"selected": false,
"text": "<p>To know what I am trying to do in my code, following is the singletone class I have implemented in C#</p>\n\n<p>public sealed class FileWriteTest\n{</p>\n\n<pre><code>private static volatile FileWriteTest instance;\n\nprivate static object syncRoot = new Object();\n\nprivate static Queue logMessages = new Queue();\n\nprivate static ErrorLogger oNetLogger = new ErrorLogger();\n\nprivate FileWriteTest() { }\n\npublic static FileWriteTest Instance\n{\n get\n {\n if (instance == null)\n {\n lock (syncRoot)\n {\n if (instance == null)\n {\n instance = new FileWriteTest();\n Thread MyThread = new Thread(new ThreadStart(StartCollectingLogs));\n MyThread.Start();\n\n }\n }\n }\n\n return instance;\n }\n}\n\nprivate static void StartCollectingLogs()\n{\n\n //Infinite loop\n while (true)\n {\n cdoLogMessage objMessage = new cdoLogMessage();\n if (logMessages.Count != 0)\n {\n objMessage = (cdoLogMessage)logMessages.Dequeue();\n oNetLogger.WriteLog(objMessage.LogText, objMessage.SeverityLevel);\n\n }\n }\n}\n\npublic void WriteLog(string logText, SeverityLevel errorSeverity)\n{\n cdoLogMessage objMessage = new cdoLogMessage();\n objMessage.LogText = logText;\n objMessage.SeverityLevel = errorSeverity;\n logMessages.Enqueue(objMessage);\n\n}\n</code></pre>\n\n<p>}</p>\n\n<p>When I run this code in debug mode (simulates just one user access), I get the error \"stack overflow\" at the line where queue is dequeued. </p>\n\n<p>Note: In the above code ErrorLogger is a class that has code to write to the File. objMessage is an entity class to carry the log message.</p>\n"
},
{
"answer_id": 119804,
"author": "Silver Dragon",
"author_id": 9440,
"author_profile": "https://Stackoverflow.com/users/9440",
"pm_score": 0,
"selected": false,
"text": "<p>Alternatively, you might want to do error logging into the database (if you're using one)</p>\n"
},
{
"answer_id": 119874,
"author": "pradeeptp",
"author_id": 20933,
"author_profile": "https://Stackoverflow.com/users/20933",
"pm_score": 0,
"selected": false,
"text": "<p>Koth,</p>\n\n<p>I have implemented Mutex lock, which has removed the \"stack overflow\" error. I yet have to do a load testing before I can conclude whether it is working fine in all cases.</p>\n\n<p>I was reading about Mutex objets in one of the websites, which says that Mutex affects the performance. I want to know one thing with putting lock through Mutex. </p>\n\n<p>Suppose User Process1 is writing to a file and at the same time User Process2 tries to write to the same file. Since Process1 has put a lock on the code block, will Process2 will keep trying or just die after the first attempet iteself.?</p>\n\n<p>thanks\npradeep_tp</p>\n"
},
{
"answer_id": 121151,
"author": "CSharpAtl",
"author_id": 11907,
"author_profile": "https://Stackoverflow.com/users/11907",
"pm_score": 0,
"selected": false,
"text": "<p>It will wait until the mutex is released....</p>\n"
},
{
"answer_id": 123698,
"author": "Joel",
"author_id": 13713,
"author_profile": "https://Stackoverflow.com/users/13713",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Joel: When you say \"queue line\" do you\n mean creating a separate thread that\n runs in a loop to keep checking the\n queue as well as write to a file when\n it is not locked?</p>\n</blockquote>\n\n<p>Yeah, that's basically what I was thinking. Have another thread that has a while loop until it can get access to the file and save, then end.</p>\n\n<p>But you would have to do it in a way where the first thread to start looking gets access first. Which is why I say queue.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20933/"
]
| I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients.
The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error:
>
> The process cannot access the file because it is being used by another process.
>
>
>
The solutions that I have tried to implement in C# and failed are as below.
1. Implemented singleton class that contains code that writes to a file.
2. Used lock statement to wrap the code that writes to the file.
3. I have also tried to use open source logger log4net but it also is not a perfect solution.
4. I know about logging to system event logger, but I do not have that choice.
I want to know if there exists a perfect and complete solution to such a problem? | The locking is probably failing because your webservice is being run by more than one worker process.
You could protect the access with a named mutex, which is shared across processes, unlike the locks you get by using `lock(someobject) {...}`:
```
Mutex lock = new Mutex("mymutex", false);
lock.WaitOne();
// access file
lock.ReleaseMutex();
``` |
119,559 | <p>Is there an easy way to programmatically determine the number of lines within a text file? </p>
| [
{
"answer_id": 119572,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 10,
"selected": true,
"text": "<p><strong>Seriously belated edit: If you're using .NET 4.0 or later</strong></p>\n\n<p>The <code>File</code> class has a new <a href=\"http://msdn.microsoft.com/en-us/library/dd383503.aspx\" rel=\"noreferrer\"><code>ReadLines</code></a> method which lazily enumerates lines rather than greedily reading them all into an array like <code>ReadAllLines</code>. So now you can have both efficiency and conciseness with:</p>\n\n<pre><code>var lineCount = File.ReadLines(@\"C:\\file.txt\").Count();\n</code></pre>\n\n<hr>\n\n<p><strong>Original Answer</strong></p>\n\n<p>If you're not too bothered about efficiency, you can simply write:</p>\n\n<pre><code>var lineCount = File.ReadAllLines(@\"C:\\file.txt\").Length;\n</code></pre>\n\n<p>For a more efficient method you could do:</p>\n\n<pre><code>var lineCount = 0;\nusing (var reader = File.OpenText(@\"C:\\file.txt\"))\n{\n while (reader.ReadLine() != null)\n {\n lineCount++;\n }\n}\n</code></pre>\n\n<p><strong>Edit: In response to questions about efficiency</strong></p>\n\n<p>The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).</p>\n\n<p>In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler.</p>\n"
},
{
"answer_id": 119574,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>You could quickly read it in, and increment a counter, just use a loop to increment, doing nothing with the text.</p>\n"
},
{
"answer_id": 119579,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 4,
"selected": false,
"text": "<p>The easiest:</p>\n\n<pre><code>int lines = File.ReadAllLines(\"myfile\").Length;\n</code></pre>\n"
},
{
"answer_id": 119581,
"author": "geocoin",
"author_id": 379,
"author_profile": "https://Stackoverflow.com/users/379",
"pm_score": 1,
"selected": false,
"text": "<p>count the carriage returns/line feeds. I believe in unicode they are still 0x000D and 0x000A respectively. that way you can be as efficient or as inefficient as you want, and decide if you have to deal with both characters or not</p>\n"
},
{
"answer_id": 119583,
"author": "user8456",
"author_id": 8456,
"author_profile": "https://Stackoverflow.com/users/8456",
"pm_score": 3,
"selected": false,
"text": "<p>If by easy you mean a lines of code that are easy to decipher but per chance inefficient?</p>\n\n<pre><code>string[] lines = System.IO.File.RealAllLines($filename);\nint cnt = lines.Count();\n</code></pre>\n\n<p>That's probably the quickest way to know how many lines. </p>\n\n<p>You could also do (depending on if you are buffering it in)</p>\n\n<pre><code>#for large files\nwhile (...reads into buffer){\nstring[] lines = Regex.Split(buffer,System.Enviorment.NewLine);\n}\n</code></pre>\n\n<p>There are other numerous ways but one of the above is probably what you'll go with.</p>\n"
},
{
"answer_id": 119602,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 3,
"selected": false,
"text": "<p>This would use less memory, but probably take longer</p>\n\n<pre><code>int count = 0;\nstring line;\nTextReader reader = new StreamReader(\"file.txt\");\nwhile ((line = reader.ReadLine()) != null)\n{\n count++;\n}\nreader.Close();\n</code></pre>\n"
},
{
"answer_id": 119638,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": -1,
"selected": false,
"text": "<p>You can launch the \"<a href=\"http://unixhelp.ed.ac.uk/CGI/man-cgi?wc\" rel=\"nofollow noreferrer\">wc</a>.exe\" executable (comes with <a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow noreferrer\">UnixUtils</a> and does not need installation) run as an external process. It supports different line count methods (like unix vs mac vs windows).</p>\n"
},
{
"answer_id": 12769601,
"author": "Muhammad Usman -kai hiwatari",
"author_id": 1726814,
"author_profile": "https://Stackoverflow.com/users/1726814",
"pm_score": -1,
"selected": false,
"text": "<pre><code>try {\n string path = args[0];\n FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);\n int i;\n string s = \"\";\n while ((i = fh.ReadByte()) != -1)\n s = s + (char)i;\n\n //its for reading number of paragraphs\n int count = 0;\n for (int j = 0; j < s.Length - 1; j++) {\n if (s.Substring(j, 1) == \"\\n\")\n count++;\n }\n\n Console.WriteLine(\"The total searches were :\" + count);\n\n fh.Close();\n\n} catch(Exception ex) {\n Console.WriteLine(ex.Message);\n} \n</code></pre>\n"
},
{
"answer_id": 37336120,
"author": "Krythic",
"author_id": 3214889,
"author_profile": "https://Stackoverflow.com/users/3214889",
"pm_score": 1,
"selected": false,
"text": "<p>A viable option, and one that I have personally used, would be to add your own header to the first line of the file. I did this for a custom model format for my game. Basically, I have a tool that optimizes my .obj files, getting rid of the crap I don't need, converts them to a better layout, and then writes the total number of lines, faces, normals, vertices, and texture UVs on the very first line. That data is then used by various array buffers when the model is loaded. </p>\n\n<p>This is also useful because you only need to loop through the file once to load it in, instead of once to count the lines, and again to read the data into your created buffers.</p>\n"
},
{
"answer_id": 50508830,
"author": "Walter Verhoeven",
"author_id": 8000382,
"author_profile": "https://Stackoverflow.com/users/8000382",
"pm_score": 3,
"selected": false,
"text": "<p>Reading a file in and by itself takes some time, garbage collecting the result is another problem as you read the whole file just to count the newline character(s),</p>\n\n<p>At some point, someone is going to have to read the characters in the file, regardless if this the framework or if it is your code. This means you have to open the file and read it into memory if the file is large this is going to potentially be a problem as the memory needs to be garbage collected. </p>\n\n<p><a href=\"http://www.nimaara.com/2018/03/20/counting-lines-of-a-text-file/\" rel=\"noreferrer\">Nima Ara made a nice analysis that you might take into consideration</a></p>\n\n<p>Here is the solution proposed, as it reads 4 characters at a time, counts the line feed character and re-uses the same memory address again for the next character comparison. </p>\n\n<pre><code>private const char CR = '\\r'; \nprivate const char LF = '\\n'; \nprivate const char NULL = (char)0;\n\npublic static long CountLinesMaybe(Stream stream) \n{\n Ensure.NotNull(stream, nameof(stream));\n\n var lineCount = 0L;\n\n var byteBuffer = new byte[1024 * 1024];\n const int BytesAtTheTime = 4;\n var detectedEOL = NULL;\n var currentChar = NULL;\n\n int bytesRead;\n while ((bytesRead = stream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)\n {\n var i = 0;\n for (; i <= bytesRead - BytesAtTheTime; i += BytesAtTheTime)\n {\n currentChar = (char)byteBuffer[i];\n\n if (detectedEOL != NULL)\n {\n if (currentChar == detectedEOL) { lineCount++; }\n\n currentChar = (char)byteBuffer[i + 1];\n if (currentChar == detectedEOL) { lineCount++; }\n\n currentChar = (char)byteBuffer[i + 2];\n if (currentChar == detectedEOL) { lineCount++; }\n\n currentChar = (char)byteBuffer[i + 3];\n if (currentChar == detectedEOL) { lineCount++; }\n }\n else\n {\n if (currentChar == LF || currentChar == CR)\n {\n detectedEOL = currentChar;\n lineCount++;\n }\n i -= BytesAtTheTime - 1;\n }\n }\n\n for (; i < bytesRead; i++)\n {\n currentChar = (char)byteBuffer[i];\n\n if (detectedEOL != NULL)\n {\n if (currentChar == detectedEOL) { lineCount++; }\n }\n else\n {\n if (currentChar == LF || currentChar == CR)\n {\n detectedEOL = currentChar;\n lineCount++;\n }\n }\n }\n }\n\n if (currentChar != LF && currentChar != CR && currentChar != NULL)\n {\n lineCount++;\n }\n return lineCount;\n}\n</code></pre>\n\n<p>Above you can see that a line is read one character at a time as well by the underlying framework as you need to read all characters to see the line feed. </p>\n\n<p>If you profile it as done bay Nima you would see that this is a rather fast and efficient way of doing this.</p>\n"
},
{
"answer_id": 63327465,
"author": "Khalil Al-rahman Yossefi",
"author_id": 5827730,
"author_profile": "https://Stackoverflow.com/users/5827730",
"pm_score": 0,
"selected": false,
"text": "<p>Use this:</p>\n<pre><code> int get_lines(string file)\n {\n var lineCount = 0;\n using (var stream = new StreamReader(file))\n {\n while (stream.ReadLine() != null)\n {\n lineCount++;\n }\n }\n return lineCount;\n }\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
]
| Is there an easy way to programmatically determine the number of lines within a text file? | **Seriously belated edit: If you're using .NET 4.0 or later**
The `File` class has a new [`ReadLines`](http://msdn.microsoft.com/en-us/library/dd383503.aspx) method which lazily enumerates lines rather than greedily reading them all into an array like `ReadAllLines`. So now you can have both efficiency and conciseness with:
```
var lineCount = File.ReadLines(@"C:\file.txt").Count();
```
---
**Original Answer**
If you're not too bothered about efficiency, you can simply write:
```
var lineCount = File.ReadAllLines(@"C:\file.txt").Length;
```
For a more efficient method you could do:
```
var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
while (reader.ReadLine() != null)
{
lineCount++;
}
}
```
**Edit: In response to questions about efficiency**
The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).
In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler. |
119,578 | <p>What is the best way to disable the warnings generated via <code>_CRT_SECURE_NO_DEPRECATE</code> that allows them to be reinstated with ease and will work across Visual Studio versions?</p>
| [
{
"answer_id": 119619,
"author": "dennisV",
"author_id": 20208,
"author_profile": "https://Stackoverflow.com/users/20208",
"pm_score": 1,
"selected": false,
"text": "<p>You can define the _CRT_SECURE_NO_WARNINGS symbol to suppress them and undefine it to reinstate them back.</p>\n"
},
{
"answer_id": 119752,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 8,
"selected": true,
"text": "<p>If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add <code>_CRT_SECURE_NO_WARNINGS</code> symbol to your project settings via \"Project\"->\"Properties\"->\"Configuration properties\"->\"C/C++\"->\"Preprocessor\"->\"Preprocessor definitions\".</p>\n\n<p>Also you can define it just before you include a header file which generates this warning.\nYou should add something like this</p>\n\n<pre><code>#ifdef _MSC_VER\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n</code></pre>\n\n<p>And just a small remark, make sure you understand what this warning stands for, and maybe, if you don't intend to use other compilers than MSVC, consider using safer version of functions i.e. strcpy_s instead of strcpy.</p>\n"
},
{
"answer_id": 120042,
"author": "Drealmer",
"author_id": 12291,
"author_profile": "https://Stackoverflow.com/users/12291",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use the <a href=\"https://msdn.microsoft.com/en-us/library/ms175759(v=vs.140).aspx\" rel=\"nofollow noreferrer\">Secure Template Overloads</a>, they will help you replace the unsecure calls with secure ones anywhere it is possible to easily deduce buffer size (static arrays).</p>\n\n<p>Just add the following:</p>\n\n<pre><code>#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 \n</code></pre>\n\n<p>Then fix the remaining warnings by hand, by using the _s functions.</p>\n"
},
{
"answer_id": 120322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>i work on a multi platform project, so i can't use _s function and i don't want pollute my code with visual studio specific code.<br/>\nmy solution is disable the warning 4996 on the visual studio project. go to Project -> Properties -> Configuration properties -> C/C++ -> Advanced -> Disable specific warning add the value 4996.<br/>\n if you use also the mfc and/or atl library (not my case) define before include mfc _AFX_SECURE_NO_DEPRECATE and before include atl _ATL_SECURE_NO_DEPRECATE.<br/>\n i use this solution across visual studio 2003 and 2005.</p>\n\n<p>p.s. if you use only visual studio the secure template overloads could be a good solution.</p>\n"
},
{
"answer_id": 121573,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 6,
"selected": false,
"text": "<p>You could disable the warnings temporarily in places where they appear by using</p>\n\n<pre><code>#pragma warning(push)\n#pragma warning(disable: warning-code) //4996 for _CRT_SECURE_NO_WARNINGS equivalent\n// deprecated code here\n#pragma warning(pop)\n</code></pre>\n\n<p>so you don't disable all warnings, which can be harmful at times.</p>\n"
},
{
"answer_id": 14107686,
"author": "Adrian Borchardt",
"author_id": 1940499,
"author_profile": "https://Stackoverflow.com/users/1940499",
"pm_score": 2,
"selected": false,
"text": "<p>The best way to do this is by a simple check and assess. I usually do something like this:</p>\n\n<pre><code>#ifndef _DEPRECATION_DISABLE /* One time only */\n#define _DEPRECATION_DISABLE /* Disable deprecation true */\n#if (_MSC_VER >= 1400) /* Check version */\n#pragma warning(disable: 4996) /* Disable deprecation */\n#endif /* #if defined(NMEA_WIN) && (_MSC_VER >= 1400) */\n#endif /* #ifndef _DEPRECATION_DISABLE */\n</code></pre>\n\n<p>All that is really required is the following: </p>\n\n<pre><code>#pragma warning(disable: 4996)\n</code></pre>\n\n<p>Hasn't failed me yet; Hope this helps</p>\n"
},
{
"answer_id": 14225814,
"author": "Gustavo Litovsky",
"author_id": 1628786,
"author_profile": "https://Stackoverflow.com/users/1628786",
"pm_score": 2,
"selected": false,
"text": "<p>For the warning by warning case, It's wise to restore it to default at some point, since you are doing it on a case by case basis.</p>\n\n<pre><code>#pragma warning(disable: 4996) /* Disable deprecation */\n// Code that causes it goes here\n#pragma warning(default: 4996) /* Restore default */\n</code></pre>\n"
},
{
"answer_id": 17094446,
"author": "PicoCreator",
"author_id": 793842,
"author_profile": "https://Stackoverflow.com/users/793842",
"pm_score": 3,
"selected": false,
"text": "<p>Combination of @[macbirdie] and @[Adrian Borchardt] answer. Which proves to be very useful in production environment (not messing up previously existing warning, especially during cross-platform compile)</p>\n\n<pre><code>#if (_MSC_VER >= 1400) // Check MSC version\n#pragma warning(push)\n#pragma warning(disable: 4996) // Disable deprecation\n#endif \n//... // ...\nstrcat(base, cat); // Sample depreciated code\n//... // ...\n#if (_MSC_VER >= 1400) // Check MSC version\n#pragma warning(pop) // Renable previous depreciations\n#endif\n</code></pre>\n"
},
{
"answer_id": 27518473,
"author": "s.c",
"author_id": 3663253,
"author_profile": "https://Stackoverflow.com/users/3663253",
"pm_score": 2,
"selected": false,
"text": "<p>you can disable security check. go to</p>\n\n<p>Project -> Properties -> Configuration properties -> C/C++ -> Code Generation -> Security Check</p>\n\n<p>and select Disable Security Check (/GS-)</p>\n"
},
{
"answer_id": 32858904,
"author": "jww",
"author_id": 608639,
"author_profile": "https://Stackoverflow.com/users/608639",
"pm_score": 0,
"selected": false,
"text": "<p>Another late answer... Here's how Microsoft uses it in their <code>wchar.h</code>. Notice they also disable <a href=\"http://msdn.microsoft.com/en-us/library/ms182089%28v=vs.100%29.aspx\" rel=\"nofollow\">Warning C6386</a>:</p>\n\n<pre><code>__inline _CRT_INSECURE_DEPRECATE_MEMORY(wmemcpy_s) wchar_t * __CRTDECL\nwmemcpy(_Out_opt_cap_(_N) wchar_t *_S1, _In_opt_count_(_N) const wchar_t *_S2, _In_ size_t _N)\n{\n #pragma warning( push )\n #pragma warning( disable : 4996 6386 )\n return (wchar_t *)memcpy(_S1, _S2, _N*sizeof(wchar_t));\n #pragma warning( pop )\n} \n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8516/"
]
| What is the best way to disable the warnings generated via `_CRT_SECURE_NO_DEPRECATE` that allows them to be reinstated with ease and will work across Visual Studio versions? | If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add `_CRT_SECURE_NO_WARNINGS` symbol to your project settings via "Project"->"Properties"->"Configuration properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".
Also you can define it just before you include a header file which generates this warning.
You should add something like this
```
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
```
And just a small remark, make sure you understand what this warning stands for, and maybe, if you don't intend to use other compilers than MSVC, consider using safer version of functions i.e. strcpy\_s instead of strcpy. |
119,588 | <p>I've just built a basic ASP MVC web site for deployment on our intranet. It expects users to be on the same domain as the IIS box and if you're not an authenticated Windows User, you should not get access.</p>
<p>I've just deployed this to IIS6 running on Server 2003 R2 SP2. The web app is configured with it's own pool with it's own pool user account. The IIS Directory Security options for the web app are set to "Windows Integrated Security" only and the web.config file has:</p>
<pre><code><authentication mode="Windows" />
</code></pre>
<p>From a Remote Desktop session on the IIS6 server itself, an IE7 browser window can successfully authenticate and navigate the web app if accessed via <a href="http://localhost/myapp" rel="nofollow noreferrer">http://localhost/myapp</a>.</p>
<p>However, also from the server, if accessed via the server's name (ie <a href="http://myserver/myapp" rel="nofollow noreferrer">http://myserver/myapp</a>) then IE7 presents a credentials dialog which after three attempts entering the correct credentials eventually returns "HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials".</p>
<p>The same problem occurs when a workstation browses to the web app url (naturally using the server's name and not "localhost").</p>
<p>The IIS6 server is a member of the only domain we have and has no firewall enabled.</p>
<p>Is there something I have failed to configure correctly for this to work?</p>
<p>Thanks,</p>
<hr>
<p>I have tried the suggestions from Matt Ryan, Graphain, and Mike Dimmick to date without success. I have just built a virtual machine test lab with a Server 2003 DC and a separate server 2003 IIS6 server and I am able to replicate the problem.</p>
<p>I am seeing an entry in the IIS6 server's System Event Log the first time I try to access the site via the non-localhost url (ie <a href="http://iis/myapp" rel="nofollow noreferrer">http://iis/myapp</a>). FQDN urls fail too. </p>
<blockquote>
<p><em>Source: Kerberos, Event ID: 4</em><br>
The kerberos client received a KRB_AP_ERR_MODIFIED error from the server host/iis.test.local. The target name used was HTTP/iis.test.local. This indicates that the password used to encrypt the kerberos service ticket is different than that on the target server. Commonly, this is due to identically named machine accounts in the target realm (TEST.LOCAL), and the client realm.</p>
</blockquote>
| [
{
"answer_id": 119689,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds to me as though you've done everything right.</p>\n\n<p>I'm sure you are but have you made sure you are using 'DOMAIN\\user' as the user account and not just 'user'?</p>\n"
},
{
"answer_id": 119813,
"author": "Matt Ryan",
"author_id": 19548,
"author_profile": "https://Stackoverflow.com/users/19548",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like the new Loopback check security feature of Windows Server 2003 SP1. As I understand it, is designed to prevent a particular type of interception attack.</p>\n\n<p>From <a href=\"http://support.microsoft.com/kb/896861\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/896861</a></p>\n\n<h2>SYMPTOMS</h2>\n\n<p>When you use the fully qualified domain name (FQDN) or a custom host header to browse a local Web site that is hosted on a computer that is running Microsoft Internet Information Services (IIS) 5.1 or IIS 6, you may receive an error message that resembles the following:\nHTTP 401.1 - Unauthorized: Logon Failed\nThis issue occurs when the Web site uses Integrated Authentication and has a name that is mapped to the local loopback address.</p>\n\n<p>Note You only receive this error message if you try to browse the Web site directly on the server. If you browse the Web site from a client computer, the Web site works as expected.</p>\n\n<h2>CAUSE</h2>\n\n<p>This issue occurs if you install Microsoft Windows XP Service Pack 2 (SP2) or Microsoft Windows Server 2003 Service Pack 1 (SP1). Windows XP SP2 and Windows Server 2003 SP1 include a loopback check security feature that is designed to help prevent reflection attacks on your computer. Therefore, authentication fails if the FQDN or the custom host header that you use does not match the local computer name.</p>\n\n<h2>Workaround</h2>\n\n<ul>\n<li>Method 1: Disable the loopback check</li>\n<li>Method 2: Specify host names</li>\n</ul>\n\n<p>See <a href=\"http://support.microsoft.com/kb/896861\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/896861</a> for details.</p>\n\n<hr>\n\n<p>Edit - just noticed that you said you were seeing this from Client PCs as well... that's more unusual. But I'd still look to test one of these workarounds, to see if it corrected the problem (and if so, might indicate a problem with your DNS config).</p>\n"
},
{
"answer_id": 120345,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 0,
"selected": false,
"text": "<p>IE7 only sends Windows credentials (NTLM, Kerberos) if it identifies the server as being on the Intranet. IE7 also added an Intranet zone lockdown feature - if you're not on a domain, by default <em>no</em> servers are in the Intranet zone. This was done to prevent zone-migration attacks.</p>\n\n<p>To change this, go to Tools/Internet Options, Security tab, then click Local Intranet. You can then manually add servers that should be treated as Intranet, by clicking the Sites button, then Advanced, or tell IE not to automatically detect your Intranet and selecting the other checkboxes as appropriate.</p>\n"
},
{
"answer_id": 131703,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 0,
"selected": false,
"text": "<p>I just encountered the opposite problem - my site authenticates externally but not locally. </p>\n\n<p>I compared it to the sites we have working and the difference was that the site that failed to authenticate was using Windows Authentication.</p>\n\n<p>However, other sites I work with (this is a dev server) tend to have Basic Authentication.</p>\n\n<p>Not sure why exactly but this fixed it.</p>\n\n<p>However, at the same time I noticed \"Default Domain\" and \"Realm\" settings.</p>\n\n<p>I know it's very unlikely but could these perhaps help at all?</p>\n"
},
{
"answer_id": 132209,
"author": "Jason Stangroome",
"author_id": 20819,
"author_profile": "https://Stackoverflow.com/users/20819",
"pm_score": 4,
"selected": true,
"text": "<p>After extensive Googling I managed to find a solution on the following MSDN article:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms998297.aspx\" rel=\"noreferrer\">How To: Create a Service Account for an ASP.NET 2.0 Application</a></p>\n\n<p>Specifically the Additional Considerations section which describes \"Creating Service Principal Names (SPNs) for Domain Accounts\" using the setspn tool from the Windows Support Tools:</p>\n\n<blockquote>\n <p>setspn -A HTTP/myserver MYDOMAIN\\MyPoolUser<br>\n setspn -A HTTP/myserver.fqdn.com MYDOMAIN\\MyPoolUser</p>\n</blockquote>\n\n<p>This solved my problem on both my virtual test lab and my original problem server.</p>\n\n<p>There is also an important note in the article that using Windows Authentication with custom pool users constrains the associated DNS name to be used by that pool only. That is, another pool with another identity would need to be associated with a different DNS name.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20819/"
]
| I've just built a basic ASP MVC web site for deployment on our intranet. It expects users to be on the same domain as the IIS box and if you're not an authenticated Windows User, you should not get access.
I've just deployed this to IIS6 running on Server 2003 R2 SP2. The web app is configured with it's own pool with it's own pool user account. The IIS Directory Security options for the web app are set to "Windows Integrated Security" only and the web.config file has:
```
<authentication mode="Windows" />
```
From a Remote Desktop session on the IIS6 server itself, an IE7 browser window can successfully authenticate and navigate the web app if accessed via <http://localhost/myapp>.
However, also from the server, if accessed via the server's name (ie <http://myserver/myapp>) then IE7 presents a credentials dialog which after three attempts entering the correct credentials eventually returns "HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials".
The same problem occurs when a workstation browses to the web app url (naturally using the server's name and not "localhost").
The IIS6 server is a member of the only domain we have and has no firewall enabled.
Is there something I have failed to configure correctly for this to work?
Thanks,
---
I have tried the suggestions from Matt Ryan, Graphain, and Mike Dimmick to date without success. I have just built a virtual machine test lab with a Server 2003 DC and a separate server 2003 IIS6 server and I am able to replicate the problem.
I am seeing an entry in the IIS6 server's System Event Log the first time I try to access the site via the non-localhost url (ie <http://iis/myapp>). FQDN urls fail too.
>
> *Source: Kerberos, Event ID: 4*
>
> The kerberos client received a KRB\_AP\_ERR\_MODIFIED error from the server host/iis.test.local. The target name used was HTTP/iis.test.local. This indicates that the password used to encrypt the kerberos service ticket is different than that on the target server. Commonly, this is due to identically named machine accounts in the target realm (TEST.LOCAL), and the client realm.
>
>
> | After extensive Googling I managed to find a solution on the following MSDN article:
[How To: Create a Service Account for an ASP.NET 2.0 Application](http://msdn.microsoft.com/en-us/library/ms998297.aspx)
Specifically the Additional Considerations section which describes "Creating Service Principal Names (SPNs) for Domain Accounts" using the setspn tool from the Windows Support Tools:
>
> setspn -A HTTP/myserver MYDOMAIN\MyPoolUser
>
> setspn -A HTTP/myserver.fqdn.com MYDOMAIN\MyPoolUser
>
>
>
This solved my problem on both my virtual test lab and my original problem server.
There is also an important note in the article that using Windows Authentication with custom pool users constrains the associated DNS name to be used by that pool only. That is, another pool with another identity would need to be associated with a different DNS name. |
119,609 | <p>I have 20 ips from my isp. I have them bound to a router box running centos. What commands, and in what order, do I set up so that the other boxes on my lan, based either on their mac addresses or 192 ips can I have them route out my box on specific ips. For example I want mac addy <code>xxx:xxx:xxx0400</code> to go out <code>72.049.12.157</code> and <code>xxx:xxx:xxx:0500</code> to go out <code>72.049.12.158</code>.</p>
| [
{
"answer_id": 119655,
"author": "Christopher Mahan",
"author_id": 479,
"author_profile": "https://Stackoverflow.com/users/479",
"pm_score": 0,
"selected": false,
"text": "<p>What's the router hardware and software version?</p>\n\n<p>Are you trying to do this with a linux box? Stop now and go get a router. It will save you money long-term.</p>\n"
},
{
"answer_id": 119970,
"author": "BigMikeD",
"author_id": 17782,
"author_profile": "https://Stackoverflow.com/users/17782",
"pm_score": 1,
"selected": false,
"text": "<p>Use <code>iptables</code> to setup <code>NAT</code>.<br/></p>\n\n<pre><code>iptables -t nat -I POSTROUTING -s 192.168.0.0/24 -j SNAT --to-source 72.049.12.157\niptables -t nat -I POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source 72.049.12.158\n</code></pre>\n\n<p>This should cause any ips on the <code>192.168.0.0</code> subnet to have an 'external' ip of <code>72.049.12.157</code> and those on the <code>192.168.1.0</code> subnet to have an 'external' ip of <code>72.049.12.158</code>. For MAC address matching, use <code>-m mac --mac-source MAC-ADDRESS</code> in place of the <code>-s 192.168.0.0/24</code> argument<br/></p>\n\n<p>Don't forget to activate ip forwarding:<br/></p>\n\n<pre><code>cat /proc/sys/net/ipv4/ip_forward\n</code></pre>\n\n<p>If the above returns a <code>0</code> then it won't work, you'll have to enable it. Unfortunately this is distro-specific and I don't know CentOS.<br/>\nFor a quick hack, do this:<br/></p>\n\n<pre><code>echo 1 > /proc/sys/net/ipv4/ip_forward\n</code></pre>\n"
},
{
"answer_id": 120056,
"author": "xmjx",
"author_id": 15259,
"author_profile": "https://Stackoverflow.com/users/15259",
"pm_score": 0,
"selected": false,
"text": "<p>Answering this question with the little information you gave amounts to rewriting a routing Howto here. You could either</p>\n\n<ul>\n<li>read about routing and IP in general (e.g. Linux System Administrator's Guide) or</li>\n<li>give us more info on the exact IP addresses you got.</li>\n</ul>\n\n<p>The above answer using NAT is definately not what you intend to use when you have public IP addresses. This solution is not going to scale well.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8456/"
]
| I have 20 ips from my isp. I have them bound to a router box running centos. What commands, and in what order, do I set up so that the other boxes on my lan, based either on their mac addresses or 192 ips can I have them route out my box on specific ips. For example I want mac addy `xxx:xxx:xxx0400` to go out `72.049.12.157` and `xxx:xxx:xxx:0500` to go out `72.049.12.158`. | Use `iptables` to setup `NAT`.
```
iptables -t nat -I POSTROUTING -s 192.168.0.0/24 -j SNAT --to-source 72.049.12.157
iptables -t nat -I POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source 72.049.12.158
```
This should cause any ips on the `192.168.0.0` subnet to have an 'external' ip of `72.049.12.157` and those on the `192.168.1.0` subnet to have an 'external' ip of `72.049.12.158`. For MAC address matching, use `-m mac --mac-source MAC-ADDRESS` in place of the `-s 192.168.0.0/24` argument
Don't forget to activate ip forwarding:
```
cat /proc/sys/net/ipv4/ip_forward
```
If the above returns a `0` then it won't work, you'll have to enable it. Unfortunately this is distro-specific and I don't know CentOS.
For a quick hack, do this:
```
echo 1 > /proc/sys/net/ipv4/ip_forward
``` |
119,627 | <p>I'm trying to store an xml serialized object in a cookie, but i get an error like this:</p>
<pre><code>A potentially dangerous Request.Cookies value was detected from the client (KundeContextCookie="<?xml version="1.0" ...")
</code></pre>
<p>I know the problem from similiar cases when you try to store something that looks like javascript code in a form input field.</p>
<p>What is the best practise here? Is there a way (like the form problem i described) to supress this warning from the asp.net framework, or should i JSON serialize instead or perhaps should i binary serialize it? What is common practise when storing serialized data in a cookie?</p>
<p>EDIT:
Thanks for the feedback. The reason i want to store more data in the cookie than the ID is because the object i really need takes about 2 seconds to retreive from a service i have no control over. I made a lightweight object 'KundeContext' to hold a few of the properties from the full object, but these are used 90% of the time. This way i only have to call the slow service on 10% of my pages. If i only stored the Id i would still have to call the service on almost all my pages.</p>
<p>I could store all the strings and ints seperately but the object has other lightweight objects like 'contactinformation' and 'address' that would be tedious to manually store for each of their properties.</p>
| [
{
"answer_id": 119665,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 2,
"selected": true,
"text": "<p>I wouldn't store data in XML in the cookie - there is a limit on cookie size for starters (used to be 4K for <em>all</em> headers including the cookie). Pick a less verbose encoding strategy such as delimiters instead e.g. a|b|c or separate cookie values. Delimited encoding makes it especially easy and fast to decode the values.</p>\n\n<p>The error you see is ASP.NET complaining that the headers look like an XSS attack.</p>\n"
},
{
"answer_id": 119673,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 3,
"selected": false,
"text": "<p>Storing serialized data in a cookie is a very, very bad idea. Since users have complete control over cookie data, it's just too easy for them to use this mechanism to feed you malicious data. In other words: <i>any</i> weakness in your deserialization code becomes instantly exploitable (or at least a way to crash something).</p>\n\n<p>Instead, only keep the simplest identifier possible in your cookies, of a type of which the format can easily be validated (for example, a GUID). Then, store your serialized data server-side (in a database, XML file on the filesystem, or whatever) and retrieve it using that identifier.</p>\n\n<p>Edit: also, in this scenario, make sure that your identifier is random enough to make it infeasible for users to guess each other's identifiers, and impersonate each other by simply changing their own identifier a bit. Again, GUIDs (or ASP.NET session identifiers) work very well for this purpose.</p>\n\n<p>Second edit after scenario clarification by question owner: why use your own cookies at all in this case? If you keep a reference to either the original object or your lightweight object in the session state (Session object), ASP.NET will take care of all implementation details for you in a pretty efficient way.</p>\n"
},
{
"answer_id": 119674,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 1,
"selected": false,
"text": "<p>Look into the <a href=\"http://msdn.microsoft.com/en-us/library/ms972976.aspx\" rel=\"nofollow noreferrer\">View State</a>. Perhaps you'd like to persist the data across post-backs in the ViewState instead of using cookies. Otherwise, you should probably store the XML on the server and a unique identifier to that data in the cookie, instead.</p>\n"
},
{
"answer_id": 119875,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 0,
"selected": false,
"text": "<p>You might look into using <a href=\"http://msdn.microsoft.com/en-us/library/ms972429.aspx\" rel=\"nofollow noreferrer\">Session State</a> to store the value. You can configure it to use a cookie to store the session id. This is also more secure, because the value is neither visible or changeable by the user-side.</p>\n\n<p>Another alternative is to use a distributed caching mechanism to store the value. My current favorite is <a href=\"http://www.codeplex.com/memcachedproviders\" rel=\"nofollow noreferrer\">Memcached</a>.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11619/"
]
| I'm trying to store an xml serialized object in a cookie, but i get an error like this:
```
A potentially dangerous Request.Cookies value was detected from the client (KundeContextCookie="<?xml version="1.0" ...")
```
I know the problem from similiar cases when you try to store something that looks like javascript code in a form input field.
What is the best practise here? Is there a way (like the form problem i described) to supress this warning from the asp.net framework, or should i JSON serialize instead or perhaps should i binary serialize it? What is common practise when storing serialized data in a cookie?
EDIT:
Thanks for the feedback. The reason i want to store more data in the cookie than the ID is because the object i really need takes about 2 seconds to retreive from a service i have no control over. I made a lightweight object 'KundeContext' to hold a few of the properties from the full object, but these are used 90% of the time. This way i only have to call the slow service on 10% of my pages. If i only stored the Id i would still have to call the service on almost all my pages.
I could store all the strings and ints seperately but the object has other lightweight objects like 'contactinformation' and 'address' that would be tedious to manually store for each of their properties. | I wouldn't store data in XML in the cookie - there is a limit on cookie size for starters (used to be 4K for *all* headers including the cookie). Pick a less verbose encoding strategy such as delimiters instead e.g. a|b|c or separate cookie values. Delimited encoding makes it especially easy and fast to decode the values.
The error you see is ASP.NET complaining that the headers look like an XSS attack. |
119,651 | <p>Let me start off with a bit of background.</p>
<p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p>
<p>A now, for the actual question.</p>
<p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p>
<p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p>
<pre><code>from difflib import SequenceMatcher
spybot = open("spybotsd160.exe", "rb").read()
testuff = open("TestuffSetup.exe", "rb").read()
s = SequenceMatcher(None, spybot, testuff)
print s.find_longest_match(0, len(spybot), 0, len(testuff))
</code></pre>
<p>Is there a better library for Python or for another language that can do this?
A completely different way to tackle the problem is welcome as well.</p>
| [
{
"answer_id": 119671,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you contact CA and ask them to tell them what they're searching for, for that virus?</p>\n\n<p>Or, you could copy the file and change each individual byte until the warning disappeared (may take a while depending on the size).</p>\n\n<p>It's possible the virus detection may be a lot more complicated than simply looking for a fixed string.</p>\n"
},
{
"answer_id": 119698,
"author": "mana",
"author_id": 12016,
"author_profile": "https://Stackoverflow.com/users/12016",
"pm_score": 1,
"selected": false,
"text": "<p>Better not wonder about the complexity and time these kinds of algorithms need.</p>\n\n<p>If you have interest in this - here <a href=\"http://www.acm.org/jea/ARTICLES/Vol4Nbr2.ps\" rel=\"nofollow noreferrer\">.ps document linked here</a> you can find a good introduction into this thematic.</p>\n\n<p>If a good implementation for these algorithms exist, I can not tell.</p>\n"
},
{
"answer_id": 119718,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>See <a href=\"http://en.wikipedia.org/wiki/Longest_common_substring_problem\" rel=\"noreferrer\">the longest common substring problem</a>. I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays.</p>\n\n<p>Using perl <a href=\"http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm\" rel=\"noreferrer\">Tree::Suffix</a> might be easiest solution. Apparently it gives all common substrings in a specified length range:</p>\n\n<pre><code>@lcs = $tree->lcs;\n@lcs = $tree->lcs($min_len, $max_len);\n@lcs = $tree->longest_common_substrings;\n</code></pre>\n"
},
{
"answer_id": 119847,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "<p>Note that even if you did find it this way, there's no guarantee that the longest match is actually the one being looked for. Instead, you may find common initialisation code or string tables added by the same compiler for instance.</p>\n"
},
{
"answer_id": 120589,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect that looking for binary strings isn't going to help you. An install program is likely to be doing some 'suspicious' things. </p>\n\n<p>You probably need to talk to CA and spybot about white-listing your installer, or about what is triggering the alert.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15109/"
]
| Let me start off with a bit of background.
This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.
A now, for the actual question.
Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.
I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.
```
from difflib import SequenceMatcher
spybot = open("spybotsd160.exe", "rb").read()
testuff = open("TestuffSetup.exe", "rb").read()
s = SequenceMatcher(None, spybot, testuff)
print s.find_longest_match(0, len(spybot), 0, len(testuff))
```
Is there a better library for Python or for another language that can do this?
A completely different way to tackle the problem is welcome as well. | See [the longest common substring problem](http://en.wikipedia.org/wiki/Longest_common_substring_problem). I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays.
Using perl [Tree::Suffix](http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm) might be easiest solution. Apparently it gives all common substrings in a specified length range:
```
@lcs = $tree->lcs;
@lcs = $tree->lcs($min_len, $max_len);
@lcs = $tree->longest_common_substrings;
``` |
119,669 | <p>How can I fetch data in a Winforms application or ASP.NET form from a SAP database? The .NET framework used is 2.0. , language is C# and SAP version is 7.10. </p>
| [
{
"answer_id": 119671,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you contact CA and ask them to tell them what they're searching for, for that virus?</p>\n\n<p>Or, you could copy the file and change each individual byte until the warning disappeared (may take a while depending on the size).</p>\n\n<p>It's possible the virus detection may be a lot more complicated than simply looking for a fixed string.</p>\n"
},
{
"answer_id": 119698,
"author": "mana",
"author_id": 12016,
"author_profile": "https://Stackoverflow.com/users/12016",
"pm_score": 1,
"selected": false,
"text": "<p>Better not wonder about the complexity and time these kinds of algorithms need.</p>\n\n<p>If you have interest in this - here <a href=\"http://www.acm.org/jea/ARTICLES/Vol4Nbr2.ps\" rel=\"nofollow noreferrer\">.ps document linked here</a> you can find a good introduction into this thematic.</p>\n\n<p>If a good implementation for these algorithms exist, I can not tell.</p>\n"
},
{
"answer_id": 119718,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>See <a href=\"http://en.wikipedia.org/wiki/Longest_common_substring_problem\" rel=\"noreferrer\">the longest common substring problem</a>. I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays.</p>\n\n<p>Using perl <a href=\"http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm\" rel=\"noreferrer\">Tree::Suffix</a> might be easiest solution. Apparently it gives all common substrings in a specified length range:</p>\n\n<pre><code>@lcs = $tree->lcs;\n@lcs = $tree->lcs($min_len, $max_len);\n@lcs = $tree->longest_common_substrings;\n</code></pre>\n"
},
{
"answer_id": 119847,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "<p>Note that even if you did find it this way, there's no guarantee that the longest match is actually the one being looked for. Instead, you may find common initialisation code or string tables added by the same compiler for instance.</p>\n"
},
{
"answer_id": 120589,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect that looking for binary strings isn't going to help you. An install program is likely to be doing some 'suspicious' things. </p>\n\n<p>You probably need to talk to CA and spybot about white-listing your installer, or about what is triggering the alert.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021/"
]
| How can I fetch data in a Winforms application or ASP.NET form from a SAP database? The .NET framework used is 2.0. , language is C# and SAP version is 7.10. | See [the longest common substring problem](http://en.wikipedia.org/wiki/Longest_common_substring_problem). I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays.
Using perl [Tree::Suffix](http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm) might be easiest solution. Apparently it gives all common substrings in a specified length range:
```
@lcs = $tree->lcs;
@lcs = $tree->lcs($min_len, $max_len);
@lcs = $tree->longest_common_substrings;
``` |
119,679 | <p>I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table.</p>
| [
{
"answer_id": 119704,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 1,
"selected": false,
"text": "<p>You could try exporting all of your stored procedures into a text file and then use a simple search.</p>\n\n<p>A more advanced technique would be to use a regexp search to find all SELECT FROM and INSERT FROM entries.</p>\n"
},
{
"answer_id": 119719,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT Distinct SO.Name\nFROM sysobjects SO (NOLOCK)\nINNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID\nAND SO.Type = 'P'\nAND (SC.Text LIKE '%UPDATE%' OR SC.Text LIKE '%INSERT%')\nORDER BY SO.Name\n</code></pre>\n\n<p><a href=\"http://www.knowdotnet.com/articles/storedprocfinds.html\" rel=\"nofollow noreferrer\">This link</a> was used as a resource for the SP search.</p>\n"
},
{
"answer_id": 119731,
"author": "Gareth D",
"author_id": 3580,
"author_profile": "https://Stackoverflow.com/users/3580",
"pm_score": 2,
"selected": false,
"text": "<p>Use sys.dm_sql_referencing_entities</p>\n\n<p>Note that sp_depends is obsoleted.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb630351.aspx\" rel=\"nofollow noreferrer\">MSDN Reference</a></p>\n"
},
{
"answer_id": 119734,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 4,
"selected": true,
"text": "<pre><code>select\n so.name,\n sc.text\nfrom\n sysobjects so inner join syscomments sc on so.id = sc.id\nwhere\n sc.text like '%INSERT INTO xyz%'\n or sc.text like '%UPDATE xyz%'\n</code></pre>\n\n<p>This will give you a list of all stored procedure contents with INSERT or UPDATE in them for a particular table (you can obviously tweak the query to suit). Also longer procedures will be broken across multiple rows in the returned recordset so you may need to do a bit of manual sifting through the results.</p>\n\n<p><strong>Edit</strong>: Tweaked query to return SP name as well. Also, note the above query will return any UDFs as well as SPs.</p>\n"
},
{
"answer_id": 119760,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 1,
"selected": false,
"text": "<p>This seems to work:</p>\n<pre><code>select \nso.name as [proc], \nso2.name as [table], \nsd.is_updated \nfrom sysobjects so \ninner join sys.sql_dependencies sd on so.id = sd.object_id \ninner join sysobjects so2 on sd.referenced_major_id = so2.id \nwhere so.xtype = 'p' -- procedure \nand is_updated = 1 -- proc updates table, or at least, I think that's what this means\n</code></pre>\n"
},
{
"answer_id": 120108,
"author": "Michael Prewecki",
"author_id": 4403,
"author_profile": "https://Stackoverflow.com/users/4403",
"pm_score": 1,
"selected": false,
"text": "<p>If you download sp_search_code from Vyaskn's website it will allow you to find any text within your database objects.</p>\n\n<p><a href=\"http://vyaskn.tripod.com/sql_server_search_stored_procedure_code.htm\" rel=\"nofollow noreferrer\">http://vyaskn.tripod.com/sql_server_search_stored_procedure_code.htm</a></p>\n"
},
{
"answer_id": 121329,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 4,
"selected": false,
"text": "<p><code>sys.sql_dependencies</code> has a list of entities with dependencies, including tables and columns that a sproc includes in queries. See <a href=\"https://stackoverflow.com/questions/69923/stored-procedures-reverse-engineering#93967\">this post</a> for an example of a query that gets out dependencies. The code snippet below will get a list of table/column dependencies by stored procedure</p>\n\n<pre><code>select sp.name as sproc_name\n ,t.name as table_name\n ,c.name as column_name\n from sys.sql_dependencies d\n join sys.objects t\n on t.object_id = d.referenced_major_id\n join sys.objects sp\n on sp.object_id = d.object_id\n join sys.columns c\n on c.object_id = t.object_id\n and c.column_id = d.referenced_minor_id\nwhere sp.type = 'P'\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
]
| I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table. | ```
select
so.name,
sc.text
from
sysobjects so inner join syscomments sc on so.id = sc.id
where
sc.text like '%INSERT INTO xyz%'
or sc.text like '%UPDATE xyz%'
```
This will give you a list of all stored procedure contents with INSERT or UPDATE in them for a particular table (you can obviously tweak the query to suit). Also longer procedures will be broken across multiple rows in the returned recordset so you may need to do a bit of manual sifting through the results.
**Edit**: Tweaked query to return SP name as well. Also, note the above query will return any UDFs as well as SPs. |
119,696 | <p>Is there anywhere on the web free vista look and feel theme pack for java?</p>
| [
{
"answer_id": 119722,
"author": "Josh Moore",
"author_id": 5004,
"author_profile": "https://Stackoverflow.com/users/5004",
"pm_score": 0,
"selected": false,
"text": "<p>If you use SWT it has a native vista look and feel built in. However, if you are using swing I honestly do not know.</p>\n"
},
{
"answer_id": 120198,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 2,
"selected": false,
"text": "<p>I'm guessing that what you want is to use the system look and feel regardless on whatever platform your application is started. This can be done with</p>\n\n<pre><code>UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );\n</code></pre>\n\n<p>on the main() method (you have to handle possible exceptions of course ;-).</p>\n\n<p>As I don't have a vista installation here I can't check whether the jvm natively supports the vista laf...</p>\n\n<p>edit: Seems to be possible with the above statement. See this thread in the java forums:</p>\n\n<p><a href=\"http://forums.sun.com/thread.jspa?threadID=5287193&tstart=345\" rel=\"nofollow noreferrer\">http://forums.sun.com/thread.jspa?threadID=5287193&tstart=345</a></p>\n"
},
{
"answer_id": 123743,
"author": "Jay R.",
"author_id": 5074,
"author_profile": "https://Stackoverflow.com/users/5074",
"pm_score": 0,
"selected": false,
"text": "<p>Using Java6u13 on Vista shows a Windows LookAndFeel that is pretty decent. Its as free as Java is.</p>\n\n<p>Sun has a tutorial on LookAndFeel usage <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html\" rel=\"nofollow noreferrer\">here</a> and if you want to play with the <a href=\"http://java.sun.com/products/jfc/jws/SwingSet2.jnlp\" rel=\"nofollow noreferrer\">SwingSet demo</a>, it shows you the System LookAndFeel and lets you change it. Then you can get an idea of what the LookAndFeel looks like. Calling <pre><code>UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());</pre></code>\nas <a href=\"https://stackoverflow.com/questions/119696/vista-skin-lf#120198\">dhiller</a> suggests, will set the look and feel based on your system. If you wanted to see what the Vista look and feel looks like, you'll need Vista though.</p>\n\n<p>Another option is to use <a href=\"https://substance.dev.java.net/\" rel=\"nofollow noreferrer\">Substance</a> or <a href=\"https://nimbus.dev.java.net/\" rel=\"nofollow noreferrer\">Nimbus</a> if you want something different from the Metal look and feel. Substance is a separate look and feel collection and Nimbus is available as of the 6u10 release.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15878/"
]
| Is there anywhere on the web free vista look and feel theme pack for java? | I'm guessing that what you want is to use the system look and feel regardless on whatever platform your application is started. This can be done with
```
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
```
on the main() method (you have to handle possible exceptions of course ;-).
As I don't have a vista installation here I can't check whether the jvm natively supports the vista laf...
edit: Seems to be possible with the above statement. See this thread in the java forums:
<http://forums.sun.com/thread.jspa?threadID=5287193&tstart=345> |
119,730 | <p>I have a <code>VARCHAR</code> column in a <code>SQL Server 2000</code> database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer. </p>
<p>When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order.</p>
<pre><code>1
2
10
A
B
B1
</code></pre>
<p>What is the best way to achieve this? </p>
| [
{
"answer_id": 119780,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 4,
"selected": false,
"text": "<p>There are a few possible ways to do this.</p>\n\n<p>One would be</p>\n\n<pre><code>SELECT\n ...\nORDER BY\n CASE \n WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value) \n ELSE 9999999 -- or something huge\n END,\n value\n</code></pre>\n\n<p>the first part of the ORDER BY converts everything to an int (with a huge value for non-numerics, to sort last) then the last part takes care of alphabetics.</p>\n\n<p>Note that the performance of this query is probably at least moderately ghastly on large amounts of data.</p>\n"
},
{
"answer_id": 119796,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": -1,
"selected": false,
"text": "<pre><code>SELECT FIELD FROM TABLE\nORDER BY \n isnumeric(FIELD) desc, \n CASE ISNUMERIC(test) \n WHEN 1 THEN CAST(CAST(test AS MONEY) AS INT)\n ELSE NULL \n END,\n FIELD\n</code></pre>\n\n<p>As per <a href=\"http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_23258510.html\" rel=\"nofollow noreferrer\">this link</a> you need to cast to MONEY then INT to avoid ordering '$' as a number.</p>\n"
},
{
"answer_id": 119800,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select\n Field1, Field2...\nfrom\n Table1\norder by\n isnumeric(Field1) desc,\n case when isnumeric(Field1) = 1 then cast(Field1 as int) else null end,\n Field1\n</code></pre>\n\n<p>This will return values in the order you gave in your question.</p>\n\n<p>Performance won't be too great with all that casting going on, so another approach is to add another column to the table in which you store an integer copy of the data and then sort by that first and then the column in question. This will obviously require some changes to the logic that inserts or updates data in the table, to populate both columns. Either that, or put a trigger on the table to populate the second column whenever data is inserted or updated.</p>\n"
},
{
"answer_id": 119817,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 2,
"selected": false,
"text": "<p>This seems to work: </p>\n\n<pre><code>select your_column \nfrom your_table \norder by \ncase when isnumeric(your_column) = 1 then your_column else 999999999 end, \nyour_column \n</code></pre>\n"
},
{
"answer_id": 119842,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 7,
"selected": true,
"text": "<p>One possible solution is to pad the numeric values with a character in front so that all are of the same string length.</p>\n\n<p>Here is an example using that approach:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>select MyColumn\nfrom MyTable\norder by \n case IsNumeric(MyColumn) \n when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn\n else MyColumn\n end\n</code></pre>\n\n<p>The <code>100</code> should be replaced with the actual length of that column.</p>\n"
},
{
"answer_id": 4685143,
"author": "JohnB",
"author_id": 287311,
"author_profile": "https://Stackoverflow.com/users/287311",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT *, CONVERT(int, your_column) AS your_column_int\nFROM your_table\nORDER BY your_column_int\n</code></pre>\n\n<p><em>OR</em></p>\n\n<pre><code>SELECT *, CAST(your_column AS int) AS your_column_int\nFROM your_table\nORDER BY your_column_int\n</code></pre>\n\n<p>Both are fairly portable I think.</p>\n"
},
{
"answer_id": 6773742,
"author": "Orz",
"author_id": 855573,
"author_profile": "https://Stackoverflow.com/users/855573",
"pm_score": 2,
"selected": false,
"text": "<p>I solved it in a very simple way writing this in the \"order\" part</p>\n\n<pre><code>ORDER BY (\nsr.codice +0\n)\nASC\n</code></pre>\n\n<p>This seems to work very well, in fact I had the following sorting:</p>\n\n<pre><code>16079 Customer X \n016082 Customer Y\n16413 Customer Z\n</code></pre>\n\n<p>So the <code>0</code> in front of <code>16082</code> is considered correctly.</p>\n"
},
{
"answer_id": 15781451,
"author": "Bernhard",
"author_id": 1498669,
"author_profile": "https://Stackoverflow.com/users/1498669",
"pm_score": 3,
"selected": false,
"text": "<p>you can always convert your varchar-column to bigint as integer might be too short...</p>\n\n<pre><code>select cast([yourvarchar] as BIGINT)\n</code></pre>\n\n<p>but you should always care for alpha characters</p>\n\n<pre><code>where ISNUMERIC([yourvarchar] +'e0') = 1\n</code></pre>\n\n<p>the +'e0' comes from <a href=\"http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber\" rel=\"noreferrer\">http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber</a></p>\n\n<p>this would lead to your statement</p>\n\n<pre><code>SELECT\n *\nFROM\n Table\nORDER BY\n ISNUMERIC([yourvarchar] +'e0') DESC\n , LEN([yourvarchar]) ASC\n</code></pre>\n\n<p>the first sorting column will put numeric on top. \nthe second sorts by length, so 10 will preceed 0001 (which is stupid?!)</p>\n\n<p>this leads to the second version: </p>\n\n<pre><code>SELECT\n *\n FROM\n Table\n ORDER BY\n ISNUMERIC([yourvarchar] +'e0') DESC\n , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC\n</code></pre>\n\n<p>the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)</p>\n\n<p>so third version:</p>\n\n<pre><code> SELECT\n *\n FROM\n Table\n ORDER BY\n ISNUMERIC([yourvarchar] +'e0') DESC\n , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1\n THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC\n ELSE LTRIM(RTRIM([yourvarchar]))\n END ASC\n</code></pre>\n\n<p>now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed</p>\n"
},
{
"answer_id": 37144238,
"author": "Param Yadav",
"author_id": 6165840,
"author_profile": "https://Stackoverflow.com/users/6165840",
"pm_score": -1,
"selected": false,
"text": "<pre><code> SELECT *,\n ROW_NUMBER()OVER(ORDER BY CASE WHEN ISNUMERIC (ID)=1 THEN CONVERT(NUMERIC(20,2),SUBSTRING(Id, PATINDEX('%[0-9]%', Id), LEN(Id)))END DESC)Rn ---- numerical\n FROM\n (\n\n SELECT '1'Id UNION ALL\n SELECT '25.20' Id UNION ALL\n\n SELECT 'A115' Id UNION ALL\n SELECT '2541' Id UNION ALL\n SELECT '571.50' Id UNION ALL\n SELECT '67' Id UNION ALL\n SELECT 'B48' Id UNION ALL\n SELECT '500' Id UNION ALL\n SELECT '147.54' Id UNION ALL\n SELECT 'A-100' Id\n )A\n\n ORDER BY \n CASE WHEN ISNUMERIC (ID)=0 /* alphabetical sort */ \n THEN CASE WHEN PATINDEX('%[0-9]%', Id)=0\n THEN LEFT(Id,PATINDEX('%[0-9]%',Id))\n ELSE LEFT(Id,PATINDEX('%[0-9]%',Id)-1)\n END\n END DESC\n</code></pre>\n"
},
{
"answer_id": 44110188,
"author": "Nitika Chopra",
"author_id": 7534013,
"author_profile": "https://Stackoverflow.com/users/7534013",
"pm_score": 0,
"selected": false,
"text": "<p>This query is helpful for you. In this query, a column has data type varchar is arranged by good order.For example- In this column data are:- G1,G34,G10,G3. So, after running this query, you see the results: - G1,G10,G3,G34. </p>\n\n<pre><code>SELECT *,\n (CASE WHEN ISNUMERIC(column_name) = 1 THEN 0 ELSE 1 END) IsNum\nFROM table_name \nORDER BY IsNum, LEN(column_name), column_name;\n</code></pre>\n"
},
{
"answer_id": 50561956,
"author": "Dennis Xavier",
"author_id": 9056729,
"author_profile": "https://Stackoverflow.com/users/9056729",
"pm_score": 0,
"selected": false,
"text": "<p>This may help you, I have tried this when i got the same issue.</p>\n\n<p><code>SELECT *\nFROM tab\nORDER BY IIF(TRY_CAST(val AS INT) IS NULL, 1, 0),TRY_CAST(val AS INT);</code></p>\n"
},
{
"answer_id": 72877808,
"author": "Mikko",
"author_id": 5553320,
"author_profile": "https://Stackoverflow.com/users/5553320",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest and efficient way to get the job done is using TRY_CAST</p>\n<pre><code>SELECT my_column \nFROM my_table\nWHERE <condition>\nORDER BY TRY_CAST(my_column AS NUMERIC) DESC\n</code></pre>\n<p>This will sort all numbers in descending order and push down all non numeric values</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
]
| I have a `VARCHAR` column in a `SQL Server 2000` database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer.
When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order.
```
1
2
10
A
B
B1
```
What is the best way to achieve this? | One possible solution is to pad the numeric values with a character in front so that all are of the same string length.
Here is an example using that approach:
```sql
select MyColumn
from MyTable
order by
case IsNumeric(MyColumn)
when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
else MyColumn
end
```
The `100` should be replaced with the actual length of that column. |
119,754 | <p>I am sending newsletters from a Java server and one of the hyperlinks is arriving missing a period, rendering it useless:</p>
<pre><code>Please print your <a href=3D"http://xxxxxxx.xxx.xx.edu=
au//newsletter2/3/InnovExpoInviteVIP.pdf"> VIP invitation</a> for future re=
ference and check the Innovation Expo website <a href=3D"http://xxxxxxx.xx=
xx.xx.edu.au/2008/"> xxxxxxx.xxxx.xx.edu.au</a> for updates.
</code></pre>
<p>In the example above the period was lost between edu and au on the first hyperlink.</p>
<p>We have determined that the mail body is being line wrapped and the wrapping splits the line at the period, and that it is illegal to start a line with a period in an SMTP email:</p>
<p><a href="https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2</a></p>
<p>My question is this - what settings should I be using to ensure that the wrapping is period friendly and/or not performed in the first place?</p>
<p>UPDATE: After a <em>lot</em> of testing and debugging it turned out that our code was fine - the client's Linux server had shipped with a <em>very</em> old Java version and the old Mail classes were still in one of the lib folders and getting picked up in preference to ours.
JDK prior to 1.2 have this bug.</p>
| [
{
"answer_id": 119772,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>From an SMTP perspective, you can start a line with a period but you have to send two periods instead. If the SMTP client you're using doesn't do this, you may encounter the problem you describe.</p>\n\n<p>It might be worth trying an IP sniffer to see where the problem really is. There are likely at least two separate SMTP transactions involved in sending that email.</p>\n"
},
{
"answer_id": 119793,
"author": "jmagica",
"author_id": 20412,
"author_profile": "https://Stackoverflow.com/users/20412",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure, but it looks a bit as if your email is getting encoded. 0x3D is the hexadecimal character 61, which is the equals character ('=').</p>\n\n<p>What classes/libary are you using to send the emails? Check the settings regarding encoding.</p>\n"
},
{
"answer_id": 119822,
"author": "Jataro",
"author_id": 9292,
"author_profile": "https://Stackoverflow.com/users/9292",
"pm_score": 0,
"selected": false,
"text": "<p>Are you setting the Mime type to \"text/html\"? You should have something like this:</p>\n\n<pre><code>BodyPart bp = new MimeBodyPart();\nbp.setContent(message,\"text/html\");\n</code></pre>\n"
},
{
"answer_id": 119891,
"author": "Ioannis",
"author_id": 20428,
"author_profile": "https://Stackoverflow.com/users/20428",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure all your content is RFC2045 friendly by virtue of quoted-printable.\nUse the MimeUtility class in a method like this.</p>\n\n<pre>\n<code>\n private String mimeEncode (String input)\n {\n ByteArrayOutputStream bOut = new ByteArrayOutputStream();\n OutputStream out;\n try\n {\n out = MimeUtility.encode( bOut, \"quoted-printable\" );\n out.write( input.getBytes( ) );\n out.flush( );\n out.close( );\n bOut.close( );\n } catch (MessagingException e)\n {\n log.error( \"Encoding error occured:\",e );\n return input;\n } catch (IOException e)\n {\n log.error( \"Encoding error occured:\",e );\n return input;\n }\n\n return bOut.toString( );\n }\n\n</code>\n</pre>\n"
},
{
"answer_id": 425551,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I am having a similar problem, but using ASP.NET 2.0. Per application logs, the link in the email is correct '<a href=\"http://www.3rdmilclassrooms.com/\" rel=\"nofollow noreferrer\">http://www.3rdmilclassrooms.com/</a>' however then the email is received by the client the link is missing a period '<a href=\"http://www3rdmilclassrooms.com\" rel=\"nofollow noreferrer\">http://www3rdmilclassrooms.com</a>'</p>\n\n<p>I have done all I can to prove that the email is being sent with the correct link. My suspicion is that it is the email client or spam filter software that is modifying the hyperlink. Is it possible that an email spam filtering software would do that?</p>\n"
},
{
"answer_id": 425596,
"author": "Karl",
"author_id": 36093,
"author_profile": "https://Stackoverflow.com/users/36093",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem sending email programmatically over to a yahoo account. They would get one very long line of text and add their own linebreaks in the HTML email, thinking that that wouldnt cause a problem, but of course it would.</p>\n\n<p>the trick was not to try to send such a long line. Because HTML emails don't care about linebreaks, you should add your own every few blocks, or just before the offending line, to ensure that your URL doesn't get split at a period like that.</p>\n\n<p>I had to change my ASP VB from </p>\n\n<pre><code>var html;\nhtml = \"Blah Blah Blah Blah \";\nhtml = html & \" More Text Here....\";\n</code></pre>\n\n<p>to</p>\n\n<pre><code>var html;\nhtml = \"Blah Blah Blah Blah \" & VbCrLf;\nhtml = html & \" More Text Here....\";\n</code></pre>\n\n<p>And that's all it took to clean up the output as was being processed on their end.</p>\n"
},
{
"answer_id": 425686,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 0,
"selected": false,
"text": "<p>As Greg pointed out, the problem is with your SMTP client, which does not do dot-stuffing (doubling the leading dot).</p>\n\n<p>It appears that the e-mail is being encoded in quoted-printable. Switching to base64 (I assume you can do it with the current java mime implementation) will fix the problem.</p>\n"
},
{
"answer_id": 6687648,
"author": "mclase",
"author_id": 798820,
"author_profile": "https://Stackoverflow.com/users/798820",
"pm_score": 2,
"selected": false,
"text": "<p>I had a similar problem in HTML emails: mysterious missing periods, and in one case a strangely truncated message. JavaMail sends HTML email using the quoted-printable encoding which wraps lines at any point (i.e. not only on whitespace) so that no line exceeds 76 characters. (It uses an '=' at the end of the line as a soft carriage return, so the receiver can reassemble the lines.) This can easily result in a line beginning with a period, which should be doubled. (This is called 'dot-stuffing') If not, the period will be eaten by the receiving SMTP server or worse, if the period is the only character on a line, it will be interpreted by the SMTP server as the end of the message.</p>\n\n<p>I tracked it down to the GNU JavaMail 1.1.2 implementation (aka classpathx javamail). There is no newer version of this implementation and it hasn't been updated for 4 or 5 years. Looking at the source, it partially implements dot-stuffing -- it tries to handle the period on a line by itself case, but there's a bug that prevents even that case from working.</p>\n\n<p>Unfortunately, this was the default implementation on our platform (Centos 5), so I imagine it is also the default on RedHat.</p>\n\n<p>The fix on Centos is to install Sun's (or should I now say Oracle's?) JavaMail implementation (I used 1.4.4), and use the Centos <em>alternatives</em> command to install it in place of the default implementation. (Using <em>alternatives</em> ensures that installing Centos patches won't cause a reversion to the GNU implmentation.)</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9731/"
]
| I am sending newsletters from a Java server and one of the hyperlinks is arriving missing a period, rendering it useless:
```
Please print your <a href=3D"http://xxxxxxx.xxx.xx.edu=
au//newsletter2/3/InnovExpoInviteVIP.pdf"> VIP invitation</a> for future re=
ference and check the Innovation Expo website <a href=3D"http://xxxxxxx.xx=
xx.xx.edu.au/2008/"> xxxxxxx.xxxx.xx.edu.au</a> for updates.
```
In the example above the period was lost between edu and au on the first hyperlink.
We have determined that the mail body is being line wrapped and the wrapping splits the line at the period, and that it is illegal to start a line with a period in an SMTP email:
<https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2>
My question is this - what settings should I be using to ensure that the wrapping is period friendly and/or not performed in the first place?
UPDATE: After a *lot* of testing and debugging it turned out that our code was fine - the client's Linux server had shipped with a *very* old Java version and the old Mail classes were still in one of the lib folders and getting picked up in preference to ours.
JDK prior to 1.2 have this bug. | From an SMTP perspective, you can start a line with a period but you have to send two periods instead. If the SMTP client you're using doesn't do this, you may encounter the problem you describe.
It might be worth trying an IP sniffer to see where the problem really is. There are likely at least two separate SMTP transactions involved in sending that email. |
119,788 | <p>Before moving on to use SVN, I used to manage my project by simply keeping a <code>/develop/</code> directory and editing and testing files there, then moving them to the <code>/main/</code> directory. When I decided to move to SVN, I needed to be sure that the directories were indeed in sync.</p>
<p>So, what is a good way to write a shell script [ bash ] to recursively compare files with the same name in two different directories?</p>
<p>Note: The directory names used above are for sample only. I do not recommend storing your code in the top level :).</p>
| [
{
"answer_id": 119811,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "<p>The diff command has a -r option to recursively compare directories:</p>\n\n<pre><code>diff -r /develop /main\n</code></pre>\n"
},
{
"answer_id": 119812,
"author": "Animesh",
"author_id": 20386,
"author_profile": "https://Stackoverflow.com/users/20386",
"pm_score": 1,
"selected": false,
"text": "<p>[I read somewhere that answering your own questions is OK, so here goes :) ]</p>\n\n<p>I tried this, and it worked pretty well</p>\n\n<pre><code>[/]$ cd /develop/\n[/develop/]$ find | while read line; do diff -ruN \"/main/$line\" $line; done |less\n</code></pre>\n\n<p>You can choose to compare only specific files [e.g., only the .php ones] by editing the above line as</p>\n\n<pre><code>[/]$ cd /develop/\n[/develop/]$ find -name \"*.php\" | while read line; do diff -ruN \"/main/$line\" $line; done |less\n</code></pre>\n\n<p>Any other ideas?</p>\n"
},
{
"answer_id": 119830,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>The diff I have available allows recursive differences:</p>\n\n<pre><code>diff -r main develop\n</code></pre>\n\n<p>But with a shell script:</p>\n\n<pre><code>( cd main ; find . -type f -exec diff {} ../develop/{} ';' )\n</code></pre>\n"
},
{
"answer_id": 119910,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "<pre><code>diff -rqu /develop /main\n</code></pre>\n\n<p>It will only give you a summary of changes that way :) </p>\n\n<p>If you want to see only <em>new/missing</em> files</p>\n\n<pre><code>diff -rqu /develop /main | grep \"^Only\n</code></pre>\n\n<p>If you want to get them bare: </p>\n\n<pre><code>diff -rqu /develop /main | sed -rn \"/^Only/s/^Only in (.+?): /\\1/p\"\n</code></pre>\n"
},
{
"answer_id": 215409,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>The classic (System V Unix) answer would be <code>dircmp dir1 dir2</code>, which was a shell script that would list files found in either dir1 but not dir2 or in dir2 but not dir1 at the start (first page of output, from the <code>pr</code> command, so paginated with headings), followed by a comparison of each common file with an analysis (same, different, directory were the most common results).</p>\n\n<p>This seems to be in the process of vanishing - I have an independent reimplementation of it available if you need it. It's not rocket science (<code>cmp</code> is your friend).</p>\n"
},
{
"answer_id": 6740823,
"author": "sdaau",
"author_id": 277826,
"author_profile": "https://Stackoverflow.com/users/277826",
"pm_score": 1,
"selected": false,
"text": "<p>here is an example of a (somewhat messy) script of mine, <a href=\"http://sdaaubckp.svn.sourceforge.net/viewvc/sdaaubckp/single-scripts/dircompare.sh?content-type=text%2Fplain\" rel=\"nofollow\">dircompare.sh</a>, which will:</p>\n\n<ul>\n<li>sort files and directories in arrays depending on which directory they occur in (or both), in two recursive passes</li>\n<li>The files that occur in both directories, are sorted again in two arrays, depending on if <code>diff -q</code> determines if they differ or not</li>\n<li>for those files that <code>diff</code> claims are equal, show and compare timestamps</li>\n</ul>\n\n<p>Hope it can be found useful - Cheers!</p>\n\n<p>EDIT2: (<em>Actually, it works fine with remote files - the problem was unhandled Ctrl-C signal during a diff operation between local and remote file, which can take a while; script now updated with a trap to handle that - however, leaving the previous edit below for reference</em>):</p>\n\n<p>EDIT: ... except it seems to crash my server for a remote ssh directory (which I tried using over <code>~/.gvfs</code>)... So this is not <code>bash</code> anymore, but an alternative I guess is to use <code>rsync</code>, here's an example:</p>\n\n<pre><code>$ # get example revision 4527 as testdir1\n$ svn co https://openbabel.svn.sf.net/svnroot/openbabel/openbabel/trunk/data@4527 testdir1\n\n$ # get earlier example revision 2729 as testdir2\n$ svn co https://openbabel.svn.sf.net/svnroot/openbabel/openbabel/trunk/data@2729 testdir2\n\n$ # use rsync to generate a list \n$ rsync -ivr --times --cvs-exclude --dry-run testdir1/ testdir2/\nsending incremental file list\n.d..t...... ./\n>f.st...... CMakeLists.txt\n>f.st...... MACCS.txt\n>f..t...... SMARTS_InteLigand.txt\n...\n>f.st...... atomtyp.txt\n>f+++++++++ babel_povray3.inc\n>f.st...... bin2hex.pl\n>f.st...... bondtyp.h\n>f..t...... bondtyp.txt\n...\n</code></pre>\n\n<p>Note that:</p>\n\n<ul>\n<li>To get the above, you mustn't forget trailing slashes <code>/</code> at the end of directory names in <code>rsync</code></li>\n<li><code>--dry-run</code> - simulate only, don't update/transfer files</li>\n<li><code>-r</code> - recurse into directories</li>\n<li><code>-v</code> - verbose (but <strong>not</strong> related to file changes info)</li>\n<li><code>--cvs-exclude</code> - ignore <code>.svn</code> files</li>\n<li><code>-i</code> - \"--itemize-changes: output a change-summary for all updates\"</li>\n</ul>\n\n<p>Here is a brief excerpt of <code>man rsync</code> that explains the information shown by <code>-i</code> (for instance, the <code>>f.st......</code> strings above):\n</p>\n\n<pre><code>The \"%i\" escape has a cryptic output that is 11 letters long.\nThe general format is like the string YXcstpoguax, where Y is\nreplaced by the type of update being done, X is replaced by the\nfile-type, and the other letters represent attributes that may\nbe output if they are being modified.\n\nThe update types that replace the Y are as follows:\n\no A < means that a file is being transferred to the remote\n host (sent).\n\no A > means that a file is being transferred to the local\n host (received).\n\no A c means that a local change/creation is occurring for\n the item (such as the creation of a directory or the\n changing of a symlink, etc.).\n\n...\nThe file-types that replace the X are: f for a file, a d for a\ndirectory, an L for a symlink, a D for a device, and a S for a\nspecial file (e.g. named sockets and fifos).\n\nThe other letters in the string above are the actual letters\nthat will be output if the associated attribute for the item is\nbeing updated or a \".\" for no change. Three exceptions to this\nare: (1) a newly created item replaces each letter with a \"+\",\n(2) an identical item replaces the dots with spaces, and (3) an\n....\n</code></pre>\n\n<p></p>\n\n<p>A bit cryptic, indeed - but at least it shows basic directory comparison over <code>ssh</code>. Cheers!</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20386/"
]
| Before moving on to use SVN, I used to manage my project by simply keeping a `/develop/` directory and editing and testing files there, then moving them to the `/main/` directory. When I decided to move to SVN, I needed to be sure that the directories were indeed in sync.
So, what is a good way to write a shell script [ bash ] to recursively compare files with the same name in two different directories?
Note: The directory names used above are for sample only. I do not recommend storing your code in the top level :). | The diff command has a -r option to recursively compare directories:
```
diff -r /develop /main
``` |
119,792 | <p>I've got a Subversion repository, backed by the berkeley DB. Occasionally it breaks down due to some locks and such not being released, but this morning it was impossible to recover it using the 'svnadmin recover' command. Instead it failed with the following error:</p>
<pre><code>svnadmin: Berkeley DB error for filesystem 'db' while opening 'nodes' table:
Invalid argument
svnadmin: bdb: file nodes (meta pgno = 0) has LSN [1083][429767].
svnadmin: bdb: end of log is [1083][354707]
svnadmin: bdb: db/nodes: unexpected file type or format
</code></pre>
<p>I'm going to restore the repository from the last known good backup, but it would be good to know if there is a way this repository could be fixed.</p>
<p>edit: even the db_recover utility does not make a difference. It shows recovery is completed, but the same error persists when verifying the repository using svnadmin.</p>
| [
{
"answer_id": 119798,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>I've got a Subversion repository, backed by the berkeley DB.</p>\n</blockquote>\n\n<p>Sorry to hear that. I would suggest that at your earliest convenience, you dump that repository (<code>svnadmin dump</code>) and reload it into a new one backed by FSFS (<code>svnadmin load</code>).</p>\n"
},
{
"answer_id": 119862,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "<p>have you tried <a href=\"http://www.google.com/search?q=man+db_recover\" rel=\"nofollow noreferrer\">db_recover</a>? the latter tends to be able to correct more issues than svnadmin</p>\n"
},
{
"answer_id": 119957,
"author": "Linor",
"author_id": 3197,
"author_profile": "https://Stackoverflow.com/users/3197",
"pm_score": 1,
"selected": false,
"text": "<p>For those wanting to try the db_recover function, you first need to find the right <a href=\"http://subversion.tigris.org/faq.html#divining-bdb-version\" rel=\"nofollow noreferrer\">berkeley DB version</a>, and then use the proper version of the <a href=\"http://www.oracle.com/technology/software/products/berkeley-db/db/index.html\" rel=\"nofollow noreferrer\">berkeley DB software</a>. Then run the recover utility:</p>\n\n<pre><code>db_recover -c -v -h <path to subversion db dir>\n</code></pre>\n"
},
{
"answer_id": 2851717,
"author": "Yaşar Şentürk",
"author_id": 248495,
"author_profile": "https://Stackoverflow.com/users/248495",
"pm_score": 1,
"selected": false,
"text": "<p>I know this question is very old, but there is another alternative which worked for me:\n<code>svnadmin recover <svn path></code></p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3197/"
]
| I've got a Subversion repository, backed by the berkeley DB. Occasionally it breaks down due to some locks and such not being released, but this morning it was impossible to recover it using the 'svnadmin recover' command. Instead it failed with the following error:
```
svnadmin: Berkeley DB error for filesystem 'db' while opening 'nodes' table:
Invalid argument
svnadmin: bdb: file nodes (meta pgno = 0) has LSN [1083][429767].
svnadmin: bdb: end of log is [1083][354707]
svnadmin: bdb: db/nodes: unexpected file type or format
```
I'm going to restore the repository from the last known good backup, but it would be good to know if there is a way this repository could be fixed.
edit: even the db\_recover utility does not make a difference. It shows recovery is completed, but the same error persists when verifying the repository using svnadmin. | >
> I've got a Subversion repository, backed by the berkeley DB.
>
>
>
Sorry to hear that. I would suggest that at your earliest convenience, you dump that repository (`svnadmin dump`) and reload it into a new one backed by FSFS (`svnadmin load`). |
119,802 | <p>I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:</p>
<pre><code>server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT))
service = Service()
server.register_instance(service)
server.serve_forever()
</code></pre>
<p>I then have a ServiceRemote class that looks like this:</p>
<pre><code>def __init__(self,ip,port):
self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port))
def __getattr__(self, name):
# forward all calls to the rpc client
return getattr(self.rpcClient, name)
</code></pre>
<p>So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:</p>
<pre><code>@useDb
def select(self, db, fields, **kwargs):
pass
</code></pre>
<p>The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.</p>
<p>When I call this method, I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.</p>
<hr>
<p>Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.</p>
| [
{
"answer_id": 119943,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I know, the underlying protocol doesn't support named varargs (or any named args for that matter). The workaround for this is to create a wrapper that will take the **kwargs and pass it as an ordinary dictionary to the method you want to call. Something like this</p>\n\n<p>Server side:</p>\n\n<pre><code>def select_wrapper(self, db, fields, kwargs):\n \"\"\"accepts an ordinary dict which can pass through xmlrpc\"\"\"\n return select(self,db,fields, **kwargs)\n</code></pre>\n\n<p>On the client side:</p>\n\n<pre><code>def select(self, db, fields, **kwargs):\n \"\"\"you can call it with keyword arguments and they will be packed into a dict\"\"\"\n return self.rpcClient.select_wrapper(self,db,fields,kwargs)\n</code></pre>\n\n<p>Disclaimer: the code shows the general idea, you can do it a bit cleaner (for example writing a decorator to do that).</p>\n"
},
{
"answer_id": 119963,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 2,
"selected": false,
"text": "<p>XML-RPC doesn't really have a concept of 'keyword arguments', so xmlrpclib doesn't try to support them. You would need to pick a convention, then modify xmlrpclib._Method to accept keyword arguments and pass them along using that convention.</p>\n\n<p>For instance, I used to work with an XML-RPC server that passed keyword arguments as two arguments, '-KEYWORD' followed by the actual argument, in a flat list. I no longer have access to the code I wrote to access that XML-RPC server from Python, but it was fairly simple, along the lines of:</p>\n\n<pre><code>import xmlrpclib\n\n_orig_Method = xmlrpclib._Method\n\nclass KeywordArgMethod(_orig_Method): \n def __call__(self, *args, **kwargs):\n if args and kwargs:\n raise TypeError, \"Can't pass both positional and keyword args\"\n args = list(args) \n for key in kwargs:\n args.append('-%s' % key.upper())\n args.append(kwargs[key])\n return _orig_Method.__call__(self, *args) \n\nxmlrpclib._Method = KeywordArgMethod\n</code></pre>\n\n<p>It uses monkeypatching because that's by far the easiest method to do this, because of some clunky uses of module globals and name-mangled attributes (__request, for instance) in the ServerProxy class.</p>\n"
},
{
"answer_id": 119974,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 0,
"selected": false,
"text": "<p>As Thomas Wouters said, XML-RPC does not have keyword arguments. Only the order of arguments matters as far as the protocol is concerned and they can be called anything in XML: arg0, arg1, arg2 is perfectly fine, as is cheese, candy and bacon for the same arguments.</p>\n\n<p>Perhaps you should simply rethink your use of the protocol? Using something like document/literal SOAP would be much better than a workaround such as the ones presented in other answers here. Of course, this may not be feasible.</p>\n"
},
{
"answer_id": 120225,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 1,
"selected": false,
"text": "<p>Using the above advice, I created some working code.</p>\n\n<p>Server method wrapper:</p>\n\n<pre><code>def unwrap_kwargs(func):\n def wrapper(*args, **kwargs):\n print args\n if args and isinstance(args[-1], list) and len(args[-1]) == 2 and \"kwargs\" == args[-1][0]:\n func(*args[:-1], **args[-1][1])\n else:\n func(*args, **kwargs)\n return wrapper\n</code></pre>\n\n<p>Client setup (do once):</p>\n\n<pre><code>_orig_Method = xmlrpclib._Method\n\nclass KeywordArgMethod(_orig_Method): \n def __call__(self, *args, **kwargs):\n args = list(args) \n if kwargs:\n args.append((\"kwargs\", kwargs))\n return _orig_Method.__call__(self, *args)\n\nxmlrpclib._Method = KeywordArgMethod\n</code></pre>\n\n<p>I tested this, and it supports method with fixed, positional and keyword arguments.</p>\n"
},
{
"answer_id": 120291,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 5,
"selected": true,
"text": "<p>You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, example below:</p>\n\n<h2>Server</h2>\n\n<pre><code>from SimpleXMLRPCServer import SimpleXMLRPCServer\n\nclass Server(object):\n def __init__(self, hostport):\n self.server = SimpleXMLRPCServer(hostport)\n\n def register_function(self, function, name=None):\n def _function(args, kwargs):\n return function(*args, **kwargs)\n _function.__name__ = function.__name__\n self.server.register_function(_function, name)\n\n def serve_forever(self):\n self.server.serve_forever()\n\n#example usage\nserver = Server(('localhost', 8000))\ndef test(arg1, arg2):\n print 'arg1: %s arg2: %s' % (arg1, arg2)\n return 0\nserver.register_function(test)\nserver.serve_forever()\n</code></pre>\n\n<h2>Client</h2>\n\n<pre><code>import xmlrpclib\n\nclass ServerProxy(object):\n def __init__(self, url):\n self._xmlrpc_server_proxy = xmlrpclib.ServerProxy(url)\n def __getattr__(self, name):\n call_proxy = getattr(self._xmlrpc_server_proxy, name)\n def _call(*args, **kwargs):\n return call_proxy(args, kwargs)\n return _call\n\n#example usage\nserver = ServerProxy('http://localhost:8000')\nserver.test(1, 2)\nserver.test(arg2=2, arg1=1)\nserver.test(1, arg2=2)\nserver.test(*[1,2])\nserver.test(**{'arg1':1, 'arg2':2})\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
]
| I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:
```
server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT))
service = Service()
server.register_instance(service)
server.serve_forever()
```
I then have a ServiceRemote class that looks like this:
```
def __init__(self,ip,port):
self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port))
def __getattr__(self, name):
# forward all calls to the rpc client
return getattr(self.rpcClient, name)
```
So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:
```
@useDb
def select(self, db, fields, **kwargs):
pass
```
The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.
When I call this method, I get the error "**call**() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.
---
Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments. | You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, example below:
Server
------
```
from SimpleXMLRPCServer import SimpleXMLRPCServer
class Server(object):
def __init__(self, hostport):
self.server = SimpleXMLRPCServer(hostport)
def register_function(self, function, name=None):
def _function(args, kwargs):
return function(*args, **kwargs)
_function.__name__ = function.__name__
self.server.register_function(_function, name)
def serve_forever(self):
self.server.serve_forever()
#example usage
server = Server(('localhost', 8000))
def test(arg1, arg2):
print 'arg1: %s arg2: %s' % (arg1, arg2)
return 0
server.register_function(test)
server.serve_forever()
```
Client
------
```
import xmlrpclib
class ServerProxy(object):
def __init__(self, url):
self._xmlrpc_server_proxy = xmlrpclib.ServerProxy(url)
def __getattr__(self, name):
call_proxy = getattr(self._xmlrpc_server_proxy, name)
def _call(*args, **kwargs):
return call_proxy(args, kwargs)
return _call
#example usage
server = ServerProxy('http://localhost:8000')
server.test(1, 2)
server.test(arg2=2, arg1=1)
server.test(1, arg2=2)
server.test(*[1,2])
server.test(**{'arg1':1, 'arg2':2})
``` |
119,818 | <p>I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side.</p>
| [
{
"answer_id": 119833,
"author": "convex hull",
"author_id": 10747,
"author_profile": "https://Stackoverflow.com/users/10747",
"pm_score": 0,
"selected": false,
"text": "<p>If it's your only checkbox you can do a getElementsByTagName() call to get all inputs and then iterate through the returned array looking for the appropriate type value (i.e. checkbox).</p>\n"
},
{
"answer_id": 119834,
"author": "yann.kmm",
"author_id": 15780,
"author_profile": "https://Stackoverflow.com/users/15780",
"pm_score": 1,
"selected": false,
"text": "<p>You have to generate your javascript too, or at least a javascript data structure (array) wich must contain the checkboxes you should control.</p>\n\n<p>Alternatively you can create a containing element, and cycle with js on every child input element of type checkbox.</p>\n"
},
{
"answer_id": 119907,
"author": "TheZenker",
"author_id": 10552,
"author_profile": "https://Stackoverflow.com/users/10552",
"pm_score": 2,
"selected": true,
"text": "<p>Here is a thought:</p>\n\n<p>As indicated by Anonymous you can generate javascript, if you are in ASP.NET you have some help with the RegisterClientScriptBlock() method. <a href=\"http://msdn.microsoft.com/en-us/library/aa478975.aspx\" rel=\"nofollow noreferrer\">MSDN on Injecting Client Side Script</a></p>\n\n<p>Also you could write, or generate, a javascript function that takes in a checkbox as a parameter and add an onClick attribute to your checkbox definition that calls your function and passes itself as the parameter</p>\n\n<pre><code>function TrackMyCheckbox(ck)\n{\n //keep track of state\n}\n\n<input type=\"checkbox\" onClick=\"TrackMyCheckbox(this);\".... />\n</code></pre>\n"
},
{
"answer_id": 120717,
"author": "Karl",
"author_id": 2932,
"author_profile": "https://Stackoverflow.com/users/2932",
"pm_score": 0,
"selected": false,
"text": "<p>There is not much detail in the question. But assuming the the HTML grid is generated on the server side (not in javascript). </p>\n\n<p>Then add classes to the checkboxes you want to ensure are checked. And loop through the DOM looking for all checkboxes with that class. In <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jQuery</a>:</p>\n\n<p>HTML:</p>\n\n<pre><code><html>\n...\n\n<div id=\"grid\">\n <input type=\"checkbox\" id=\"checkbox1\" class=\"must-be-checked\" />\n <input type=\"checkbox\" id=\"checkbox2\" class=\"not-validated\" />\n <input type=\"checkbox\" id=\"checkbox3\" class=\"must-be-checked\" />\n ... \n <input type=\"checkbox\" id=\"checkboxN\" class=\"must-be-checked\" />\n</div>\n\n...\n</html>\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code><script type=\"text/javascript\">\n\n // This will show an alert if any checkboxes with the class 'must-be-checked'\n // are not checked.\n // Checkboxes with any other class (or no class) are ignored\n if ($('#grid .must-be-checked:not(:checked)').length > 0) {\n alert('some checkboxes not checked!');\n }\n\n</script>\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
]
| I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side. | Here is a thought:
As indicated by Anonymous you can generate javascript, if you are in ASP.NET you have some help with the RegisterClientScriptBlock() method. [MSDN on Injecting Client Side Script](http://msdn.microsoft.com/en-us/library/aa478975.aspx)
Also you could write, or generate, a javascript function that takes in a checkbox as a parameter and add an onClick attribute to your checkbox definition that calls your function and passes itself as the parameter
```
function TrackMyCheckbox(ck)
{
//keep track of state
}
<input type="checkbox" onClick="TrackMyCheckbox(this);".... />
``` |
119,819 | <p>I need to cleanup the HTML of pasted text into TinyMCE by passing it to a webservice and then getting it back into the textarea.
So I need to override the Ctrl+V in TinyMCE to caputre the text, do a background request, and on return continue with whatever the paste handler was for TinyMCE.
First off, where is TinyMCE's Ctrl+V handler, and is there a non-destructive way to override it? (instead of changing the source code)</p>
| [
{
"answer_id": 119901,
"author": "Aleksi Yrttiaho",
"author_id": 11427,
"author_profile": "https://Stackoverflow.com/users/11427",
"pm_score": 2,
"selected": false,
"text": "<p>You could write a plug-in that handles the ctrl+v event and passes it through or modify the paste plug-in. The following code is found at <a href=\"http://source.ibiblio.org/trac/lyceum/browser/vendor/wordpress/trunk/wp-includes/js/tinymce/plugins/paste/editor_plugin.js?rev=1241\" rel=\"nofollow noreferrer\">plugins/paste/editor_plugin.js</a> and it handles the ctrl+v event.</p>\n\n<pre><code> handleEvent : function(e) {\n // Force paste dialog if non IE browser\n if (!tinyMCE.isRealIE && tinyMCE.getParam(\"paste_auto_cleanup_on_paste\", false) && e.ctrlKey && e.keyCode == 86 && e.type == \"keydown\") {\n window.setTimeout('tinyMCE.selectedInstance.execCommand(\"mcePasteText\",true)', 1);\n return tinyMCE.cancelEvent(e);\n }\n\n return true;\n },\n</code></pre>\n\n<p>Here is some <a href=\"http://wiki.moxiecode.com/index.php/TinyMCE:Creating_Plugin\" rel=\"nofollow noreferrer\">more information about creating plug-ins for tinyMCE</a>.</p>\n"
},
{
"answer_id": 53214903,
"author": "Wolfgang Blessen",
"author_id": 2239334,
"author_profile": "https://Stackoverflow.com/users/2239334",
"pm_score": 0,
"selected": false,
"text": "<p>Tiny Editor has a plugin called \"paste\".</p>\n\n<p>When using it, you can define two functions in the init-section</p>\n\n<pre><code>/**\n * This option enables you to modify the pasted content BEFORE it gets\n * inserted into the editor.\n */\npaste_preprocess : function(plugin, args)\n{\n //Replace empty styles\n args.content = args.content.replace(/<style><\\/style>/gi, \"\");\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>/**\n * This option enables you to modify the pasted content before it gets inserted\n * into the editor ,but after it's been parsed into a DOM structure.\n *\n * @param plugin\n * @param args\n */\npaste_postprocess : function(plugin, args) {\n var paste_content= args.node.innerHTML;\n console.log('Node:');\n console.log(args.node);\n\n}\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I need to cleanup the HTML of pasted text into TinyMCE by passing it to a webservice and then getting it back into the textarea.
So I need to override the Ctrl+V in TinyMCE to caputre the text, do a background request, and on return continue with whatever the paste handler was for TinyMCE.
First off, where is TinyMCE's Ctrl+V handler, and is there a non-destructive way to override it? (instead of changing the source code) | You could write a plug-in that handles the ctrl+v event and passes it through or modify the paste plug-in. The following code is found at [plugins/paste/editor\_plugin.js](http://source.ibiblio.org/trac/lyceum/browser/vendor/wordpress/trunk/wp-includes/js/tinymce/plugins/paste/editor_plugin.js?rev=1241) and it handles the ctrl+v event.
```
handleEvent : function(e) {
// Force paste dialog if non IE browser
if (!tinyMCE.isRealIE && tinyMCE.getParam("paste_auto_cleanup_on_paste", false) && e.ctrlKey && e.keyCode == 86 && e.type == "keydown") {
window.setTimeout('tinyMCE.selectedInstance.execCommand("mcePasteText",true)', 1);
return tinyMCE.cancelEvent(e);
}
return true;
},
```
Here is some [more information about creating plug-ins for tinyMCE](http://wiki.moxiecode.com/index.php/TinyMCE:Creating_Plugin). |
119,857 | <p>I am reading image files in Java using</p>
<pre><code>java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath);
</code></pre>
<p>On some systems this doesn't work, it instead throws an AWTError complaining about sun/awt/motif/MToolkit.</p>
<p>How else can you create a java.awt.Image object from an image file?</p>
| [
{
"answer_id": 119864,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 4,
"selected": true,
"text": "<p>I read images using <a href=\"http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html\" rel=\"noreferrer\">ImageIO</a>.</p>\n\n<pre><code>Image i = ImageIO.read(InputStream in);\n</code></pre>\n\n<p>The javadoc will offer more info as well.</p>\n"
},
{
"answer_id": 119906,
"author": "Mario Ortegón",
"author_id": 2309,
"author_profile": "https://Stackoverflow.com/users/2309",
"pm_score": 2,
"selected": false,
"text": "<p>There is several static methods in ImageIO that allow to read images from different sources. The most interesting in your case are:</p>\n\n<pre><code>BufferedImage read(ImageInputStream stream) \nBufferedImage read(File input)\nBufferedImage read(InputStream input)\n</code></pre>\n\n<p>I checked inside in the code. It uses the ImageReader abstract class, and there is three implementors: JPEGReader. PNGReader and GIFReader. These classes and BufferedImage do not use any native methods apparently, so it should always work.</p>\n\n<p>It seems that the AWTError you have is because you are running java in a headless configuration, or that the windows toolkit has some kind of problem. Without looking at the specific error is hard to say though. This solution will allow you to read the image (probably), but depending on what you want to do with it, the AWTError might be thrown later as you try to display it.</p>\n"
},
{
"answer_id": 120120,
"author": "Vilmantas Baranauskas",
"author_id": 11662,
"author_profile": "https://Stackoverflow.com/users/11662",
"pm_score": 0,
"selected": false,
"text": "<p>On some systems adding \"-Djava.awt.headless=true\" as java parameter may help.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119/"
]
| I am reading image files in Java using
```
java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath);
```
On some systems this doesn't work, it instead throws an AWTError complaining about sun/awt/motif/MToolkit.
How else can you create a java.awt.Image object from an image file? | I read images using [ImageIO](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html).
```
Image i = ImageIO.read(InputStream in);
```
The javadoc will offer more info as well. |
119,860 | <p>Using Visual Studio 2008 Team Edition, is it possible to assign a shortcut key that switches between markup and code? If not, is it possible to assign a shortcut key that goes from code to markup?</p>
| [
{
"answer_id": 119883,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 3,
"selected": true,
"text": "<p>The following is a macro taken from a comment by Lozza on <a href=\"https://blog.codinghorror.com/visual-studio-net-2003-and-2005-keyboard-shortcuts/\" rel=\"nofollow noreferrer\">https://blog.codinghorror.com/visual-studio-net-2003-and-2005-keyboard-shortcuts/</a>. You just need to bind it to a shortcut of your choice:</p>\n\n<pre><code>Sub SwitchToMarkup()\n Dim FileName\n\n If (DTE.ActiveWindow.Caption().EndsWith(\".cs\")) Then\n ' swith from .aspx.cs to .aspx\n FileName = DTE.ActiveWindow.Document.FullName.Replace(\".cs\", \"\")\n If System.IO.File.Exists(FileName) Then\n DTE.ItemOperations.OpenFile(FileName)\n End If\n ElseIf (DTE.ActiveWindow.Caption().EndsWith(\".aspx\")) Then\n ' swith from .aspx to .aspx.cs\n FileName = DTE.ActiveWindow.Document.FullName.Replace(\".aspx\", \".aspx.cs\")\n If System.IO.File.Exists(FileName) Then\n DTE.ItemOperations.OpenFile(FileName)\n End If\n ElseIf (DTE.ActiveWindow.Caption().EndsWith(\".ascx\")) Then\n FileName = DTE.ActiveWindow.Document.FullName.Replace(\".ascx\", \".ascx.cs\")\n If System.IO.File.Exists(FileName) Then\n DTE.ItemOperations.OpenFile(FileName)\n End If\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 3466688,
"author": "peSHIr",
"author_id": 50846,
"author_profile": "https://Stackoverflow.com/users/50846",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if this is what you mean, as I don't do ASPX development myself, but don't the F7 (show code) and Shift-F7 (show designer) default key bindings switch between code and design? They do in my VS2008 (on WinForms designable items) with the largely default C# key bindings I use.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
]
| Using Visual Studio 2008 Team Edition, is it possible to assign a shortcut key that switches between markup and code? If not, is it possible to assign a shortcut key that goes from code to markup? | The following is a macro taken from a comment by Lozza on <https://blog.codinghorror.com/visual-studio-net-2003-and-2005-keyboard-shortcuts/>. You just need to bind it to a shortcut of your choice:
```
Sub SwitchToMarkup()
Dim FileName
If (DTE.ActiveWindow.Caption().EndsWith(".cs")) Then
' swith from .aspx.cs to .aspx
FileName = DTE.ActiveWindow.Document.FullName.Replace(".cs", "")
If System.IO.File.Exists(FileName) Then
DTE.ItemOperations.OpenFile(FileName)
End If
ElseIf (DTE.ActiveWindow.Caption().EndsWith(".aspx")) Then
' swith from .aspx to .aspx.cs
FileName = DTE.ActiveWindow.Document.FullName.Replace(".aspx", ".aspx.cs")
If System.IO.File.Exists(FileName) Then
DTE.ItemOperations.OpenFile(FileName)
End If
ElseIf (DTE.ActiveWindow.Caption().EndsWith(".ascx")) Then
FileName = DTE.ActiveWindow.Document.FullName.Replace(".ascx", ".ascx.cs")
If System.IO.File.Exists(FileName) Then
DTE.ItemOperations.OpenFile(FileName)
End If
End If
End Sub
``` |
119,869 | <p>Can someone give me some working examples of how you can create, add messages, read from, and destroy a private message queue from C++ APIs? I tried the MSDN pieces of code but i can't make them work properly.</p>
<p>Thanks</p>
| [
{
"answer_id": 120457,
"author": "Nevermind",
"author_id": 12366,
"author_profile": "https://Stackoverflow.com/users/12366",
"pm_score": -1,
"selected": false,
"text": "<p>Not quite sure how you'd go about creating or destroying message queues. Windows should create one per thread. </p>\n\n<p>If you're using MFC, any CWinThread and CWnd derived class has a message queue that's trivial to access (using PostMessage or PostThreadMessage and the ON_COMMAND macro). To do something similar with the windows API, I think you need to write your own message pump, something like CWinApp's run method.</p>\n\n<pre><code>MSG msg;\nBOOL bRet; \nwhile( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)\n{ \n if (bRet == -1)\n {\n // handle the error and possibly exit\n }\n else\n {\n TranslateMessage(&msg); \n DispatchMessage(&msg); \n }\n} \n</code></pre>\n\n<p>...is the example from the MSDN documentation. Is this what you're using? What doesn't work?</p>\n"
},
{
"answer_id": 120510,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Actualy this is the code i was interested in:</p>\n\n<pre><code>#include \"windows.h\"\n#include \"mq.h\"\n#include \"tchar.h\"\n\n\nHRESULT CreateMSMQQueue(\n LPWSTR wszPathName, \n PSECURITY_DESCRIPTOR pSecurityDescriptor,\n LPWSTR wszOutFormatName,\n DWORD *pdwOutFormatNameLength\n )\n{\n\n // Define the maximum number of queue properties.\n const int NUMBEROFPROPERTIES = 2;\n\n\n // Define a queue property structure and the structures needed to initialize it.\n MQQUEUEPROPS QueueProps;\n MQPROPVARIANT aQueuePropVar[NUMBEROFPROPERTIES];\n QUEUEPROPID aQueuePropId[NUMBEROFPROPERTIES];\n HRESULT aQueueStatus[NUMBEROFPROPERTIES];\n HRESULT hr = MQ_OK;\n\n\n // Validate the input parameters.\n if (wszPathName == NULL || wszOutFormatName == NULL || pdwOutFormatNameLength == NULL)\n {\n return MQ_ERROR_INVALID_PARAMETER;\n }\n\n\n\n DWORD cPropId = 0;\n aQueuePropId[cPropId] = PROPID_Q_PATHNAME;\n aQueuePropVar[cPropId].vt = VT_LPWSTR;\n aQueuePropVar[cPropId].pwszVal = wszPathName;\n cPropId++;\n\n WCHAR wszLabel[MQ_MAX_Q_LABEL_LEN] = L\"Test Queue\";\n aQueuePropId[cPropId] = PROPID_Q_LABEL;\n aQueuePropVar[cPropId].vt = VT_LPWSTR;\n aQueuePropVar[cPropId].pwszVal = wszLabel;\n cPropId++;\n\n\n\n QueueProps.cProp = cPropId; // Number of properties\n QueueProps.aPropID = aQueuePropId; // IDs of the queue properties\n QueueProps.aPropVar = aQueuePropVar; // Values of the queue properties\n QueueProps.aStatus = aQueueStatus; // Pointer to the return status\n\n\n\n WCHAR wszFormatNameBuffer[256];\n DWORD dwFormatNameBufferLength = sizeof(wszFormatNameBuffer)/sizeof(wszFormatNameBuffer[0]);\n hr = MQCreateQueue(pSecurityDescriptor, // Security descriptor\n &QueueProps, // Address of queue property structure\n wszFormatNameBuffer, // Pointer to format name buffer\n &dwFormatNameBufferLength); // Pointer to receive the queue's format name length\n\n\n\n if (hr == MQ_OK || hr == MQ_INFORMATION_PROPERTY)\n {\n if (*pdwOutFormatNameLength >= dwFormatNameBufferLength)\n {\n wcsncpy_s(wszOutFormatName, *pdwOutFormatNameLength - 1, wszFormatNameBuffer, _TRUNCATE);\n\n wszOutFormatName[*pdwOutFormatNameLength - 1] = L'\\0';\n *pdwOutFormatNameLength = dwFormatNameBufferLength;\n }\n else\n {\n wprintf(L\"The queue was created, but its format name cannot be returned.\\n\");\n }\n }\n return hr;\n}\n</code></pre>\n\n<p>This presumably creates a queue... but there are some parts missing for this to work, that's why i need a simple example that works.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Can someone give me some working examples of how you can create, add messages, read from, and destroy a private message queue from C++ APIs? I tried the MSDN pieces of code but i can't make them work properly.
Thanks | Actualy this is the code i was interested in:
```
#include "windows.h"
#include "mq.h"
#include "tchar.h"
HRESULT CreateMSMQQueue(
LPWSTR wszPathName,
PSECURITY_DESCRIPTOR pSecurityDescriptor,
LPWSTR wszOutFormatName,
DWORD *pdwOutFormatNameLength
)
{
// Define the maximum number of queue properties.
const int NUMBEROFPROPERTIES = 2;
// Define a queue property structure and the structures needed to initialize it.
MQQUEUEPROPS QueueProps;
MQPROPVARIANT aQueuePropVar[NUMBEROFPROPERTIES];
QUEUEPROPID aQueuePropId[NUMBEROFPROPERTIES];
HRESULT aQueueStatus[NUMBEROFPROPERTIES];
HRESULT hr = MQ_OK;
// Validate the input parameters.
if (wszPathName == NULL || wszOutFormatName == NULL || pdwOutFormatNameLength == NULL)
{
return MQ_ERROR_INVALID_PARAMETER;
}
DWORD cPropId = 0;
aQueuePropId[cPropId] = PROPID_Q_PATHNAME;
aQueuePropVar[cPropId].vt = VT_LPWSTR;
aQueuePropVar[cPropId].pwszVal = wszPathName;
cPropId++;
WCHAR wszLabel[MQ_MAX_Q_LABEL_LEN] = L"Test Queue";
aQueuePropId[cPropId] = PROPID_Q_LABEL;
aQueuePropVar[cPropId].vt = VT_LPWSTR;
aQueuePropVar[cPropId].pwszVal = wszLabel;
cPropId++;
QueueProps.cProp = cPropId; // Number of properties
QueueProps.aPropID = aQueuePropId; // IDs of the queue properties
QueueProps.aPropVar = aQueuePropVar; // Values of the queue properties
QueueProps.aStatus = aQueueStatus; // Pointer to the return status
WCHAR wszFormatNameBuffer[256];
DWORD dwFormatNameBufferLength = sizeof(wszFormatNameBuffer)/sizeof(wszFormatNameBuffer[0]);
hr = MQCreateQueue(pSecurityDescriptor, // Security descriptor
&QueueProps, // Address of queue property structure
wszFormatNameBuffer, // Pointer to format name buffer
&dwFormatNameBufferLength); // Pointer to receive the queue's format name length
if (hr == MQ_OK || hr == MQ_INFORMATION_PROPERTY)
{
if (*pdwOutFormatNameLength >= dwFormatNameBufferLength)
{
wcsncpy_s(wszOutFormatName, *pdwOutFormatNameLength - 1, wszFormatNameBuffer, _TRUNCATE);
wszOutFormatName[*pdwOutFormatNameLength - 1] = L'\0';
*pdwOutFormatNameLength = dwFormatNameBufferLength;
}
else
{
wprintf(L"The queue was created, but its format name cannot be returned.\n");
}
}
return hr;
}
```
This presumably creates a queue... but there are some parts missing for this to work, that's why i need a simple example that works. |
119,941 | <p>I want to create variables inside function from dictionary.</p>
<p>Lets say I have a dictionary</p>
<pre><code>bar = {'a': 1, 'b': 2, 'c': 3}
</code></pre>
<p>and function</p>
<pre><code>def foo():
pass
</code></pre>
<p>What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values</p>
<p>So in the end it should be similar to</p>
<pre><code>def foo():
a = 1
b = 2
c = 3
</code></pre>
<p>Is it possible at all? And if it does, how to do such thing?</p>
| [
{
"answer_id": 119964,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 1,
"selected": false,
"text": "<p>Why would you want to do such a thing? Unless you actually do anything with the variables inside the function, a function that just assigns several variables and then discards them is indistinguishable to def foo(): pass (An optimiser would be justified in generating exactly the same bytecode).</p>\n\n<p>If you also want to dynamically append code that uses the values, then you could do this by using exec (though unless this is really user-input code, there are almost certainly better ways to do what you want). eg:</p>\n\n<pre><code>some_code = ' return a+b+c'\nexec \"def foo():\\n \" + '\\n '.join('%s = %s' for k,v in bar.items()) + '\\n' + some_code\n</code></pre>\n\n<p>(Note that your code must be indented to the same level.)</p>\n\n<p>On the other hand, if you want to actually assign these values to the function <strong>object</strong> (so you can do foo.a and get 1 - note that your sample code doesn't do this), you can do this by:</p>\n\n<pre><code>for key, val in bar.items():\n setattr(foo, key, val)\n</code></pre>\n"
},
{
"answer_id": 119983,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": true,
"text": "<p>Your question is not clear.</p>\n\n<p>If you want to \"set\" said variables when foo is not running, no, you can't. There is no frame object yet to \"set\" the local variables in.</p>\n\n<p>If you want to do that in the function body, you shouldn't (check the <a href=\"http://docs.python.org/lib/built-in-funcs.html\" rel=\"nofollow noreferrer\">python documentation</a> for locals()).</p>\n\n<p>However, you <em>could</em> do a <code>foo.__dict__.update(bar)</code>, and then you could access those variables even from inside the function as foo.a, foo.b and foo.c. The question is: why do you want to do that, and why isn't a class more suitable for your purposes?</p>\n"
},
{
"answer_id": 120103,
"author": "user20955",
"author_id": 20955,
"author_profile": "https://Stackoverflow.com/users/20955",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks guys, I got the point. I should not do such thing. But if your curios what I tried to do is to somehow short number of lines in my view function in django. I have form with many fields, and instead of receive every field in form of:</p>\n\n<pre><code>first_name = form.cleaned_data['first_name']\nlast_name = form.cleaned_data['last_name'] ..\n</code></pre>\n\n<p>i was thinking to take every attribute name of my form class and loop over it. Like so:</p>\n\n<pre><code>for name in ProfileRegistration.base_fields.__dict__['keyOrder']:\n # and here the variables that i tried to assign\n</code></pre>\n"
},
{
"answer_id": 120214,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "<p>From your comment, perhaps what you're really looking for is something like a bunch object:</p>\n\n<pre><code>class Bunch(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\nb=Bunch(**form.cleaned_data)\n\nprint b.first_name, b.last_name\n</code></pre>\n\n<p>(The ** syntax is because Bunch-type objects are usually used like Bunch(foo=12, bar='blah') - not used in your case but I've left it for consistency with normal usage)</p>\n\n<p>This does require a \"b.\" prefix to access your variables, but if you think about it, this is no bad thing. Consider what would happen if someone crafted a POST request to overwrite variables you <em>aren't</em> expecting to be overwritten - it makes it easy to produce crashes and DOS attacks, and could easily introduce more serious security vulnerabilities.</p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20955/"
]
| I want to create variables inside function from dictionary.
Lets say I have a dictionary
```
bar = {'a': 1, 'b': 2, 'c': 3}
```
and function
```
def foo():
pass
```
What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values
So in the end it should be similar to
```
def foo():
a = 1
b = 2
c = 3
```
Is it possible at all? And if it does, how to do such thing? | Your question is not clear.
If you want to "set" said variables when foo is not running, no, you can't. There is no frame object yet to "set" the local variables in.
If you want to do that in the function body, you shouldn't (check the [python documentation](http://docs.python.org/lib/built-in-funcs.html) for locals()).
However, you *could* do a `foo.__dict__.update(bar)`, and then you could access those variables even from inside the function as foo.a, foo.b and foo.c. The question is: why do you want to do that, and why isn't a class more suitable for your purposes? |
119,961 | <p>Normally you can do this:</p>
<pre><code><select size="3">
<option>blah</option>
<option>blah</option>
<option>blah</option>
</select>
</code></pre>
<p>And it would render as a selectionbox where all three options are visible (without dropping down)<br>
I'm looking for a way to set this size attribute from css.</p>
| [
{
"answer_id": 119977,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": -1,
"selected": false,
"text": "<p>I do not believe this is possible no</p>\n"
},
{
"answer_id": 119988,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think that this is possible.</p>\n\n<p>CSS properties are very generic (applicable to any element) and are unable to alter the functionality of an element in any ways (only the looks).</p>\n\n<p>The size attribute is changing the functionality of the element at least in the case of size = 1 / size != 1.</p>\n"
},
{
"answer_id": 120062,
"author": "Sam Murray-Sutton",
"author_id": 2977,
"author_profile": "https://Stackoverflow.com/users/2977",
"pm_score": 0,
"selected": false,
"text": "<p>In general you can't add attributes set within html via CSS. You can add to the html using the pseudo selectors :before and :after, but that's about it, plus they still aren't compatible across all browsers. If you really need to do this, I think you'd have to resort to Javascript.</p>\n"
},
{
"answer_id": 122357,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 4,
"selected": true,
"text": "<p>There ins't an option for setting the size, but if you do set the size some browsers will let you set the width/height properties to whatever you want via CSS.</p>\n\n<p>Some = Firefox, Chrome, Safari, Opera.</p>\n\n<p>Not much works in IE though (no surprise)</p>\n\n<p>You could though, if you wanted, use CSS expressions in IE, to check if the size attribute is set, and if so, run JS to (re)set it to the size you want... e.g.</p>\n\n<pre><code>size = options.length;\n</code></pre>\n"
},
{
"answer_id": 971690,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I disagree, I have been able to set select width and height using CSS with something like this:</p>\n\n<pre><code>select { width: 5em; height: 5em; }\n</code></pre>\n\n<p>Works in IE(7) as well as I just tested it.</p>\n"
},
{
"answer_id": 22340882,
"author": "marco",
"author_id": 3408725,
"author_profile": "https://Stackoverflow.com/users/3408725",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>select[attr=size] {\n width:auto;\n height:auto;\n}\n</code></pre>\n"
},
{
"answer_id": 31245377,
"author": "kimomat",
"author_id": 1329470,
"author_profile": "https://Stackoverflow.com/users/1329470",
"pm_score": 1,
"selected": false,
"text": "<p>You can use following CSS selector to style select items with the size attribute:</p>\n\n<pre><code>select[size]{\n/*your style here */\n}\n</code></pre>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
]
| Normally you can do this:
```
<select size="3">
<option>blah</option>
<option>blah</option>
<option>blah</option>
</select>
```
And it would render as a selectionbox where all three options are visible (without dropping down)
I'm looking for a way to set this size attribute from css. | There ins't an option for setting the size, but if you do set the size some browsers will let you set the width/height properties to whatever you want via CSS.
Some = Firefox, Chrome, Safari, Opera.
Not much works in IE though (no surprise)
You could though, if you wanted, use CSS expressions in IE, to check if the size attribute is set, and if so, run JS to (re)set it to the size you want... e.g.
```
size = options.length;
``` |
119,971 | <p>I'm trying to run Selenium RC against my ASP.NET code running on a Cassini webserver.</p>
<p>The web application works when i browse it directly but when running through Selenium I get </p>
<p>HTTP ERROR: 403<br>
Forbidden for Proxy</p>
<hr>
<p>Running Selenium i interactive mode I start a new session with: </p>
<pre>cmd=getNewBrowserSession&1=*iexplore&2=http://localhost:81/
cmd=open&1=http://localhost:81/default.aspx&sessionId=199578
</pre>
<p>I get the above error in the Selenium browser, the command window tells me OK.</p>
<hr>
<p>Any input?</p>
| [
{
"answer_id": 121055,
"author": "HAXEN",
"author_id": 11434,
"author_profile": "https://Stackoverflow.com/users/11434",
"pm_score": 1,
"selected": false,
"text": "<p>I think the problem is that both Selenium and the webserver is running on localhost.<br>\nIt works if I run with the \"iehta\" instead of \"iexplore\".</p>\n"
},
{
"answer_id": 151992,
"author": "Ryan Guest",
"author_id": 1811,
"author_profile": "https://Stackoverflow.com/users/1811",
"pm_score": 1,
"selected": false,
"text": "<p>Your Selenium server and web server should run of different ports.</p>\n"
},
{
"answer_id": 170567,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried running RC with the -proxyInjection flag? </p>\n"
},
{
"answer_id": 212882,
"author": "Benjamin Lee",
"author_id": 29009,
"author_profile": "https://Stackoverflow.com/users/29009",
"pm_score": 1,
"selected": false,
"text": "<p>I am not sure if this is part of the issue but, cassini can not be accessed from another machine. It is meant for local development only. I ran into this problem today and am trying UltiDev (cassini wrapper) to get around it: <a href=\"http://www.ultidev.com/products/Cassini/index.htm\" rel=\"nofollow noreferrer\">http://www.ultidev.com/products/Cassini/index.htm</a></p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11434/"
]
| I'm trying to run Selenium RC against my ASP.NET code running on a Cassini webserver.
The web application works when i browse it directly but when running through Selenium I get
HTTP ERROR: 403
Forbidden for Proxy
---
Running Selenium i interactive mode I start a new session with:
```
cmd=getNewBrowserSession&1=*iexplore&2=http://localhost:81/
cmd=open&1=http://localhost:81/default.aspx&sessionId=199578
```
I get the above error in the Selenium browser, the command window tells me OK.
---
Any input? | I think the problem is that both Selenium and the webserver is running on localhost.
It works if I run with the "iehta" instead of "iexplore". |
119,980 | <p>Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?</p>
<p>I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.</p>
<p><strong>Edit:</strong> From link provided in accepted answer:</p>
<p>Include Silverlight.js (from Silverlight SDK)</p>
<pre><code>Silverlight.isInstalled("2.0");
</code></pre>
| [
{
"answer_id": 119992,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 5,
"selected": true,
"text": "<p>Include Silverlight.js (from Silverlight SDK)</p>\n\n<p><code>Silverlight.isInstalled(\"4.0\")</code></p>\n\n<hr>\n\n<p><strong>Resource:</strong></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx\" rel=\"nofollow noreferrer\"><a href=\"http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx</a></a></p>\n"
},
{
"answer_id": 120638,
"author": "pcorcoran",
"author_id": 15992,
"author_profile": "https://Stackoverflow.com/users/15992",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var hasSilverlight = Boolean(window.Silverlight);\n\nvar hasSilverlight2 = hasSilverlight && Silverlight.isInstalled('2.0');\n</code></pre>\n\n<p>Etc....</p>\n"
},
{
"answer_id": 121930,
"author": "Tim Heuer",
"author_id": 705,
"author_profile": "https://Stackoverflow.com/users/705",
"pm_score": 3,
"selected": false,
"text": "<p>Please actually use the latest script available at <a href=\"http://code.msdn.microsoft.com/silverlightjs\" rel=\"noreferrer\">http://code.msdn.microsoft.com/silverlightjs</a> for the latest updates. This has several fixes in it.</p>\n"
},
{
"answer_id": 3684918,
"author": "Deano",
"author_id": 335567,
"author_profile": "https://Stackoverflow.com/users/335567",
"pm_score": 0,
"selected": false,
"text": "<p>Download this script: <a href=\"http://code.msdn.microsoft.com/silverlightjs\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/silverlightjs</a></p>\n\n<p>And then you can use it like so:</p>\n\n<p><code>\n\nif (Silverlight.isInstalled)\n{\nalert (\"Congrats. Your web browser is enabled with Silverlight Runtime\");\n}\n\n</code></p>\n"
},
{
"answer_id": 4731064,
"author": "Hong",
"author_id": 355456,
"author_profile": "https://Stackoverflow.com/users/355456",
"pm_score": 0,
"selected": false,
"text": "<pre><code> if (Silverlight.isInstalled(\"1.0\")) {\n try {\n alert(\"Silverlight Version 1.0 or above is installed\");\n }\n catch (err) {\n alert(err.Description);\n }\n }\n else {\n alert(\"No Silverlight is installed\");\n }\n</code></pre>\n\n<p>from this <a href=\"http://www.silverlight.net/learn/videos/all/how-to-determine-if-silverlight-is-installed/\" rel=\"nofollow\">video</a>.</p>\n\n<p>Silverlight.isInstalled is always true so version string such as \"1.0\" must be provided to make it useful. </p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/119980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
]
| Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?
I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.
**Edit:** From link provided in accepted answer:
Include Silverlight.js (from Silverlight SDK)
```
Silverlight.isInstalled("2.0");
``` | Include Silverlight.js (from Silverlight SDK)
`Silverlight.isInstalled("4.0")`
---
**Resource:**
[<http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx>](http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx) |
120,001 | <p>I am looking for a free tool to load Excel data sheet into an Oracle database. I tried the Oracle SQL developer, but it keeps throwing a NullPointerException. Any ideas?</p>
| [
{
"answer_id": 120021,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 4,
"selected": false,
"text": "<p>Excel -> CSV -> Oracle</p>\n\n<p>Save the Excel spreadsheet as file type 'CSV' (Comma-Separated Values).</p>\n\n<p>Transfer the .csv file to the Oracle server.</p>\n\n<p>Create the Oracle table, using the SQL <code>CREATE TABLE</code> statement to define the table's column lengths and types. </p>\n\n<p>Use sqlload to load the .csv file into the Oracle table. Create a sqlload control file like this:</p>\n\n<pre><code>load data\ninfile theFile.csv\nreplace\ninto table theTable\nfields terminated by ','\n(x,y,z)\n</code></pre>\n\n<p>Invoke sqlload to read the .csv file into the new table, creating one row in the table for each line in the .csv file. This is done as a Unix command:</p>\n\n<pre><code>% sqlload userid=username/password control=<filename.ctl> log=<filename>.log\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<p>If you just want a tool, use <a href=\"http://sourceforge.net/projects/quickload\" rel=\"noreferrer\">QuickLoad</a></p>\n"
},
{
"answer_id": 120222,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://apex.oracle.com\" rel=\"nofollow noreferrer\">Oracle Application Express</a>, which comes free with Oracle, includes a \"Load Spreadsheet Data\" utility under:</p>\n\n<pre><code>Utilities > Data Load/Unload > Load > Load Spreadsheet Data\n</code></pre>\n\n<p>You need to save the spreadsheet as a CSV file first.</p>\n"
},
{
"answer_id": 122829,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If this is a one time process you may just want to copy and paste the data into a Microsoft access table and do an append query to the oracle table that you have setup through your odbc manager.</p>\n"
},
{
"answer_id": 123456,
"author": "jimmyorr",
"author_id": 19239,
"author_profile": "https://Stackoverflow.com/users/19239",
"pm_score": 2,
"selected": false,
"text": "<p>Another way to do Excel -> CSV -> Oracle is using External Tables, first introduced in 9i. External tables let you query a flat file as if it's a table. Behind the scenes Oracle is still using SQL*Loader. There's a solid tutorial here:</p>\n\n<p><a href=\"http://www.orafaq.com/node/848\" rel=\"nofollow noreferrer\">http://www.orafaq.com/node/848</a></p>\n"
},
{
"answer_id": 22924097,
"author": "Richard Briggs",
"author_id": 1158320,
"author_profile": "https://Stackoverflow.com/users/1158320",
"pm_score": -1,
"selected": false,
"text": "<p>As you mention you are looking for a tool - you might like to check out this Oracle specific video - you can load data from any source - </p>\n\n<p><a href=\"http://youtu.be/shYiN2pnPbA\" rel=\"nofollow\">http://youtu.be/shYiN2pnPbA</a></p>\n"
},
{
"answer_id": 43041857,
"author": "smshafiqulislam",
"author_id": 6275152,
"author_profile": "https://Stackoverflow.com/users/6275152",
"pm_score": 0,
"selected": false,
"text": "<p><br/>\nThere are different ways to load excel/csv to oracle database. I am giving those below: <br/>\n1. Use Toad. Toad gives very fexible option to upload excel. It gives column mapping window as well. Normally from Tools -> Import, you will find the option. For details I can provide full instruction manual. <br/>\n2. Load to Microsoft Access first and then pass it to Oracle from there. <br/>\nStep1: There is a tab in access named \"External Data\" which gives excel upload to access database. <br/>\nStep2: Once table is created, just click write mouse on the table and choose Export to ODBC DATABASE. It will ask for oracle database connection details. \nIt's is free. <br/>\n3. Use Oracle SQL Loader. It's a service which have datafile, control file. You need to write configuration. It is used as text/any file load which maintain one pattern. </p>\n\n<p>Hope it helps. If required, I can share more details. </p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/120001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1233512/"
]
| I am looking for a free tool to load Excel data sheet into an Oracle database. I tried the Oracle SQL developer, but it keeps throwing a NullPointerException. Any ideas? | Excel -> CSV -> Oracle
Save the Excel spreadsheet as file type 'CSV' (Comma-Separated Values).
Transfer the .csv file to the Oracle server.
Create the Oracle table, using the SQL `CREATE TABLE` statement to define the table's column lengths and types.
Use sqlload to load the .csv file into the Oracle table. Create a sqlload control file like this:
```
load data
infile theFile.csv
replace
into table theTable
fields terminated by ','
(x,y,z)
```
Invoke sqlload to read the .csv file into the new table, creating one row in the table for each line in the .csv file. This is done as a Unix command:
```
% sqlload userid=username/password control=<filename.ctl> log=<filename>.log
```
**OR**
If you just want a tool, use [QuickLoad](http://sourceforge.net/projects/quickload) |
120,016 | <p>I have the following XML structure:</p>
<pre><code><?xml version="1.0" ?>
<course xml:lang="nl">
<body>
<item id="787900813228567" view="12000" title="0x|Beschrijving" engtitle="0x|Description"><![CDATA[Dit college leert studenten hoe ze een onderzoek kunn$
<item id="5453116633894965" view="12000" title="0x|Onderwijsvorm" engtitle="0x|Method of instruction"><![CDATA[instructiecollege]]></item>
<item id="7433550075448316" view="12000" title="0x|Toetsing" engtitle="0x|Examination"><![CDATA[Opdrachten/werkstuk]]></item>
<item id="015071401858970545" view="12000" title="0x|Literatuur" engtitle="0x|Required reading"><![CDATA[Wayne C. Booth, Gregory G. Colomb, Joseph M. Wi$
<item id="5960589172957031" view="12000" title="0x|Uitbreiding" engtitle="0x|Expansion"><![CDATA[]]></item>
<item id="3610066867901779" view="12000" title="0x|Aansluiting" engtitle="0x|Place in study program"><![CDATA[]]></item>
<item id="19232369892482925" view="12000" title="0x|Toegangseisen" engtitle="0x|Course requirements"><![CDATA[]]></item>
<item id="3332396346891524" view="12000" title="0x|Doelgroep" engtitle="0x|Target audience"><![CDATA[]]></item>
<item id="6606851872934866" view="12000" title="0x|Aanmelden bij" engtitle="0x|Enrollment at"><![CDATA[]]></item>
<item id="1478643580820973" view="12000" title="0x|Informatie bij" engtitle="0x|Information at"><![CDATA[Docent]]></item>
<item id="9710608434763993" view="12000" title="0x|Rooster" engtitle="0x|Schedule"><![CDATA[1e semester, maandag 15.00-17.00, zaal 1175/030]]></item>
</body>
</course>
</code></pre>
<p>I want to get the data from one of the item tags. To get to this tag, I use the following xpath:</p>
<pre><code>$description = $xml->xpath("//item[@title='0x|Beschrijving']");
</code></pre>
<p>This does indeed return an array in the form of:</p>
<pre><code>Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 787900813228567
[view] => 12000
[title] => 0x|Beschrijving
[engtitle] => 0x|Description
)
)
)
</code></pre>
<p>But where is the actual information (that is stored between the item tags) located? I must be doing something wrong, but I can't figure out what that might be... Probably something really simple... Help would be appreciated.</p>
| [
{
"answer_id": 120069,
"author": "Marc Gear",
"author_id": 6563,
"author_profile": "https://Stackoverflow.com/users/6563",
"pm_score": 2,
"selected": false,
"text": "<p>I believe its equivalent to the __toString() method on the object, so </p>\n\n<pre><code>echo $description[0];\n</code></pre>\n\n<p>Should display it, or you can cast it;</p>\n\n<pre><code>$str = (string) $description[0];\n</code></pre>\n"
},
{
"answer_id": 120070,
"author": "Eric_WVGG",
"author_id": 82944,
"author_profile": "https://Stackoverflow.com/users/82944",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$description = $xml->xpath(\"//item[@title='0x|Beschrijving']\");\n\nwhile(list( , $node) = each($description)) {\n\necho($node);\n\n}\n</code></pre>\n\n<p>dreamwerx's solution is better</p>\n"
},
{
"answer_id": 120072,
"author": "DreamWerx",
"author_id": 15487,
"author_profile": "https://Stackoverflow.com/users/15487",
"pm_score": 5,
"selected": true,
"text": "<p>When you load the XML file, you'll need to handle the CDATA.. This example works:</p>\n\n<pre><code><?php\n$xml = simplexml_load_file('file.xml', NULL, LIBXML_NOCDATA);\n$description = $xml->xpath(\"//item[@title='0x|Beschrijving']\");\nvar_dump($description);\n?>\n</code></pre>\n\n<p>Here's the output:</p>\n\n<pre><code>array(1) {\n [0]=>\n object(SimpleXMLElement)#2 (2) {\n [\"@attributes\"]=>\n array(4) {\n [\"id\"]=>\n string(15) \"787900813228567\"\n [\"view\"]=>\n string(5) \"12000\"\n [\"title\"]=>\n string(15) \"0x|Beschrijving\"\n [\"engtitle\"]=>\n string(14) \"0x|Description\"\n }\n [0]=>\n string(41) \"Dit college leert studenten hoe ze een on\"\n }\n}\n</code></pre>\n"
},
{
"answer_id": 120078,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at the PHP.net documentation for \"SimpleXMLElement\" (<a href=\"http://uk.php.net/manual/en/function.simplexml-element-children.php\" rel=\"nofollow noreferrer\">http://uk.php.net/manual/en/function.simplexml-element-children.php</a>) it looks like converting the node to a string \"(string)$value;\" does the trick.</p>\n\n<p>Failing that, there's plenty of examples on that page that should point you in the right direction! </p>\n"
}
]
| 2008/09/23 | [
"https://Stackoverflow.com/questions/120016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18922/"
]
| I have the following XML structure:
```
<?xml version="1.0" ?>
<course xml:lang="nl">
<body>
<item id="787900813228567" view="12000" title="0x|Beschrijving" engtitle="0x|Description"><![CDATA[Dit college leert studenten hoe ze een onderzoek kunn$
<item id="5453116633894965" view="12000" title="0x|Onderwijsvorm" engtitle="0x|Method of instruction"><![CDATA[instructiecollege]]></item>
<item id="7433550075448316" view="12000" title="0x|Toetsing" engtitle="0x|Examination"><![CDATA[Opdrachten/werkstuk]]></item>
<item id="015071401858970545" view="12000" title="0x|Literatuur" engtitle="0x|Required reading"><![CDATA[Wayne C. Booth, Gregory G. Colomb, Joseph M. Wi$
<item id="5960589172957031" view="12000" title="0x|Uitbreiding" engtitle="0x|Expansion"><![CDATA[]]></item>
<item id="3610066867901779" view="12000" title="0x|Aansluiting" engtitle="0x|Place in study program"><![CDATA[]]></item>
<item id="19232369892482925" view="12000" title="0x|Toegangseisen" engtitle="0x|Course requirements"><![CDATA[]]></item>
<item id="3332396346891524" view="12000" title="0x|Doelgroep" engtitle="0x|Target audience"><![CDATA[]]></item>
<item id="6606851872934866" view="12000" title="0x|Aanmelden bij" engtitle="0x|Enrollment at"><![CDATA[]]></item>
<item id="1478643580820973" view="12000" title="0x|Informatie bij" engtitle="0x|Information at"><![CDATA[Docent]]></item>
<item id="9710608434763993" view="12000" title="0x|Rooster" engtitle="0x|Schedule"><![CDATA[1e semester, maandag 15.00-17.00, zaal 1175/030]]></item>
</body>
</course>
```
I want to get the data from one of the item tags. To get to this tag, I use the following xpath:
```
$description = $xml->xpath("//item[@title='0x|Beschrijving']");
```
This does indeed return an array in the form of:
```
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 787900813228567
[view] => 12000
[title] => 0x|Beschrijving
[engtitle] => 0x|Description
)
)
)
```
But where is the actual information (that is stored between the item tags) located? I must be doing something wrong, but I can't figure out what that might be... Probably something really simple... Help would be appreciated. | When you load the XML file, you'll need to handle the CDATA.. This example works:
```
<?php
$xml = simplexml_load_file('file.xml', NULL, LIBXML_NOCDATA);
$description = $xml->xpath("//item[@title='0x|Beschrijving']");
var_dump($description);
?>
```
Here's the output:
```
array(1) {
[0]=>
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(4) {
["id"]=>
string(15) "787900813228567"
["view"]=>
string(5) "12000"
["title"]=>
string(15) "0x|Beschrijving"
["engtitle"]=>
string(14) "0x|Description"
}
[0]=>
string(41) "Dit college leert studenten hoe ze een on"
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.