qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
41,699 | <p>So creating a Windows service using Visual Studio is fairly trivial. My question goes a bit deeper as to what actually makes an executable installable as a service & how to write a service as a straight C application. I couldn't find a lot of references on this, but I'm presuming there has to be some interface I can implement so my .exe can be installed as a service.</p>
| [
{
"answer_id": 41706,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>Hope this helps:</p>\n<p><a href=\"http://support.microsoft.com/kb/251192\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/251192</a></p>\n<p>It would seem that you simple need to run this exe against a binary executable to register it as a service.</p>\n"
},
{
"answer_id": 41708,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "<p>Basically there are some registry settings you have to set as well as some interfaces to implement.</p>\n\n<p>Check out this: <a href=\"http://msdn.microsoft.com/en-us/library/ms685141.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms685141.aspx</a></p>\n\n<p>You are interested in the SCM (Service Control Manager).</p>\n"
},
{
"answer_id": 43161,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>Setting up your executable as a service is part of it, but realistically it's usually handled by whatever installation software you're using. You can use the command line SC tool while testing (or if you don't need an installer).</p>\n\n<p>The important thing is that your program has to call StartServiceCtrlDispatcher() upon startup. This connects your service to the service control manager and sets up a ServiceMain routine which is your services main entry point.</p>\n\n<p>ServiceMain (you can call it whatever you like actually, but it always seems to be ServiceMain) should then call RegisterServiceCtrlHandlerEx() to define a callback routine so that the OS can notify your service when certain events occur.</p>\n\n<p>Here are some snippets from a service I wrote a few years ago:</p>\n\n<p>set up as service:</p>\n\n<pre><code>SERVICE_TABLE_ENTRY ServiceStartTable[] =\n{\n { \"ServiceName\", ServiceMain },\n { 0, 0 }\n};\n\nif (!StartServiceCtrlDispatcher(ServiceStartTable))\n{\n DWORD err = GetLastError();\n if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)\n return false;\n}\n</code></pre>\n\n<p>ServiceMain:</p>\n\n<pre><code>void WINAPI ServiceMain(DWORD, LPTSTR*)\n{\n hServiceStatus = RegisterServiceCtrlHandlerEx(\"ServiceName\", ServiceHandlerProc, 0);\n</code></pre>\n\n<p>service handler:</p>\n\n<pre><code>DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*)\n{\n switch (ControlCode)\n {\n case SERVICE_CONTROL_INTERROGATE :\n // update OS about our status\n case SERVICE_CONTROL_STOP :\n // shut down service\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 1195001,
"author": "KevenK",
"author_id": 103825,
"author_profile": "https://Stackoverflow.com/users/103825",
"pm_score": 1,
"selected": false,
"text": "<p>I know I'm a bit late to the party, but I've recently had this same question, and had to struggle through the interwebs looking for answers.</p>\n\n<p>I managed to find this article in MSDN that does in fact lay the groundwork. I ended up combining many of the files here into a single exe that contains all of the commands I need, and added in my own \"void run()\" method that loops for the entirely life of the service for my own needs.</p>\n\n<p>This would be a great start to someone else with exactly this question, so for future searchers out there, check it out:</p>\n\n<p><strong>The Complete Service Sample</strong>\n<a href=\"http://msdn.microsoft.com/en-us/library/bb540476(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb540476(VS.85).aspx</a></p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/634/"
] | So creating a Windows service using Visual Studio is fairly trivial. My question goes a bit deeper as to what actually makes an executable installable as a service & how to write a service as a straight C application. I couldn't find a lot of references on this, but I'm presuming there has to be some interface I can implement so my .exe can be installed as a service. | Setting up your executable as a service is part of it, but realistically it's usually handled by whatever installation software you're using. You can use the command line SC tool while testing (or if you don't need an installer).
The important thing is that your program has to call StartServiceCtrlDispatcher() upon startup. This connects your service to the service control manager and sets up a ServiceMain routine which is your services main entry point.
ServiceMain (you can call it whatever you like actually, but it always seems to be ServiceMain) should then call RegisterServiceCtrlHandlerEx() to define a callback routine so that the OS can notify your service when certain events occur.
Here are some snippets from a service I wrote a few years ago:
set up as service:
```
SERVICE_TABLE_ENTRY ServiceStartTable[] =
{
{ "ServiceName", ServiceMain },
{ 0, 0 }
};
if (!StartServiceCtrlDispatcher(ServiceStartTable))
{
DWORD err = GetLastError();
if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
return false;
}
```
ServiceMain:
```
void WINAPI ServiceMain(DWORD, LPTSTR*)
{
hServiceStatus = RegisterServiceCtrlHandlerEx("ServiceName", ServiceHandlerProc, 0);
```
service handler:
```
DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*)
{
switch (ControlCode)
{
case SERVICE_CONTROL_INTERROGATE :
// update OS about our status
case SERVICE_CONTROL_STOP :
// shut down service
}
return 0;
}
``` |
41,701 | <p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p>
<p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this:
(jobId, label, username) = job</p>
<p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p>
<p>Here are my two best guesses:
(jobId, label, username) = (job[0], job[1], job[2])
...but that doesn't scale nicely when you have 15...20 fields</p>
<p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
| [
{
"answer_id": 41707,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 5,
"selected": true,
"text": "<p>I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.</p>\n\n<p>For example:</p>\n\n<pre><code>job={}\njob['jobid'], job['label'], job['username']=<querycode>\n</code></pre>\n"
},
{
"answer_id": 41709,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 0,
"selected": false,
"text": "<p>With a tuple it will always be a hassle to add or change fields. You're right that a dictionary will be much better. </p>\n\n<p>If you want something with slightly friendlier syntax you might want to take a look at the answers <a href=\"https://stackoverflow.com/questions/35988/c-like-structures-in-python\">this question</a> about a simple 'struct-like' object. That way you can pass around an object, say <code>job</code>, and access its fields even more easily than a tuple or dict:</p>\n\n<pre><code>job.jobId, job.username = jobId, username\n</code></pre>\n"
},
{
"answer_id": 41721,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps this is overkill for your case, but I would be tempted to create a \"Job\" class that takes the tuple as its constructor argument and has respective properties on it. I'd then pass instances of this class around instead.</p>\n"
},
{
"answer_id": 41723,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 2,
"selected": false,
"text": "<p>I would use a dictionary. You can convert the tuple to a dictionary this way:</p>\n\n<pre><code>values = <querycode>\nkeys = [\"jobid\", \"label\", \"username\"]\njob = dict([[keys[i], values [i]] for i in xrange(len(values ))])\n</code></pre>\n\n<p>This will first create an array [[\"jobid\", val1], [\"label\", val2], [\"username\", val3]] and then convert that to a dictionary. If the result order or count changes, you just need to change the list of keys to match the new result.</p>\n\n<p>PS still fresh on Python myself, so there might be better ways off doing this.</p>\n"
},
{
"answer_id": 41730,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": -1,
"selected": false,
"text": "<p>How about this:</p>\n\n<pre><code>class TypedTuple:\n def __init__(self, fieldlist, items):\n self.fieldlist = fieldlist\n self.items = items\n def __getattr__(self, field):\n return self.items[self.fieldlist.index(field)]\n</code></pre>\n\n<p>You could then do:</p>\n\n<pre><code>j = TypedTuple([\"jobid\", \"label\", \"username\"], job)\nprint j.jobid\n</code></pre>\n\n<p>It should be easy to swap <code>self.fieldlist.index(field)</code> with a dictionary lookup later on... just edit your <code>__init__</code> method! Something like Staale does.</p>\n"
},
{
"answer_id": 41846,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 4,
"selected": false,
"text": "<p>@Staale</p>\n\n<p>There is a better way:</p>\n\n<pre><code>job = dict(zip(keys, values))\n</code></pre>\n"
},
{
"answer_id": 387242,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 2,
"selected": false,
"text": "<p>An old question, but since no one mentioned it I'll add this from the Python Cookbook: </p>\n\n<p><a href=\"http://code.activestate.com/recipes/81252/\" rel=\"nofollow noreferrer\">Recipe 81252: Using dtuple for Flexible Query Result Access </a></p>\n\n<p>This recipe is specifically designed for dealing with database results, and the dtuple solution allows you to access the results by name OR index number. This avoids having to access everything by subscript which is very difficult to maintain, as noted in your question.</p>\n"
},
{
"answer_id": 1144246,
"author": "JAB",
"author_id": 138772,
"author_profile": "https://Stackoverflow.com/users/138772",
"pm_score": 3,
"selected": false,
"text": "<p>This is an old question, but...</p>\n\n<p>I'd suggest using a named tuple in this situation: <a href=\"http://docs.python.org/3.1/library/collections.html#collections.namedtuple\" rel=\"noreferrer\">collections.namedtuple</a></p>\n\n<p>This is the part, in particular, that you'd find useful:</p>\n\n<blockquote>\n <p>Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute.</p>\n</blockquote>\n"
},
{
"answer_id": 2609123,
"author": "jpkotta",
"author_id": 245173,
"author_profile": "https://Stackoverflow.com/users/245173",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using the MySQLdb package, you can set up your cursor objects to return dicts instead of tuples.</p>\n\n<pre><code>import MySQLdb, MySQLdb.cursors\nconn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor)\ncur = conn.cursor() # a DictCursor\ncur2 = conn.cursor(cursorclass=MySQLdb.cursors.Cursor) # a \"normal\" tuple cursor\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397/"
] | I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)
For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this:
(jobId, label, username) = job
I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?
Here are my two best guesses:
(jobId, label, username) = (job[0], job[1], job[2])
...but that doesn't scale nicely when you have 15...20 fields
or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me) | I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.
For example:
```
job={}
job['jobid'], job['label'], job['username']=<querycode>
``` |
41,717 | <p>Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff.</p>
<p>I'm wondering about how user controls work in ASP.NET MVC. We have tons of <code>.ASCX</code> controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer.</p>
<p>What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.</p>
| [
{
"answer_id": 41722,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 4,
"selected": true,
"text": "<p>To implement a user control you do the following call:</p>\n\n<pre><code><% Html.RenderPartial(\"~/Views/Shared/MyControl.ascx\", {data model object}) %>\n</code></pre>\n\n<p>You may also see the older syntax which as of PR5 is not valid anymore</p>\n\n<pre><code><%= Html.RenderUserControl(\"~/Views/Shared/MyControl.ascx\", {data model object}) %>\n</code></pre>\n\n<p>You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.</p>\n"
},
{
"answer_id": 41741,
"author": "LorenzCK",
"author_id": 3118,
"author_profile": "https://Stackoverflow.com/users/3118",
"pm_score": 1,
"selected": false,
"text": "<p>As Nick suggested, you will indeed be able to render your user controls, but obviously the page-cycle, pagestate and postback from traditional ASP Webforms won't work anymore, thus making your controls most likely useless.</p>\n\n<p>I think you'll have to rewrite most of your complex controls to port your website to MVC, while simple controls which, for instance, provide only formatting and have no postback status, should simply work.\nThe code provided by Nick will simply work in this case.</p>\n\n<p>And about sharing between more projects: I think controls will be more like \"reusable HTML-rendering components\" that can be shared across a website, rather than \"reusable code components\" with logic (like WebForms controls). Your web logic will/should be in the pages controllers and not in the HTML controls. Therefore sharing controls across more projects won't be so useful as in the WebForms case.</p>\n"
},
{
"answer_id": 45091,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 1,
"selected": false,
"text": "<p>Yeah, you can do RenderPartial. That's a good start. But eventually these guys will need logic and other controller type stuff. Be on the lookout for a subcontroller implementation from the framework team. There should also be something in MvcContrib soon. Or roll your own.</p>\n\n<p><strong>Edit:</strong> I just posted about this here: <a href=\"http://mhinze.com/subcontrollers-in-aspnet-mvc/\" rel=\"nofollow noreferrer\">http://mhinze.com/subcontrollers-in-aspnet-mvc/</a></p>\n"
},
{
"answer_id": 5192101,
"author": "Trevor",
"author_id": 644471,
"author_profile": "https://Stackoverflow.com/users/644471",
"pm_score": 1,
"selected": false,
"text": "<p>MVC has different page life cycle compare to your user control. </p>\n\n<p>You may consider this to re-write.</p>\n\n<p>The aspx is the <em>view</em>. You still need a re-write, the syntax is different.\nJavaScript will work. But I hardly find the WebControls will work. Because MVC does not have viewstate and postback anymore.</p>\n\n<p>For the code behind (aspx.cs) you need to convert that to be a <em>Controller</em> class.\n<code>Page_Load</code> method will no longer works. You probable leave it to <code>Index()</code> method.</p>\n\n<p><em>Model</em> is simply the entity classes that your code behind consume. </p>\n\n<p>Conclusion, it's a total rewrite. Cheers. Happy coding.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff.
I'm wondering about how user controls work in ASP.NET MVC. We have tons of `.ASCX` controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer.
What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration. | To implement a user control you do the following call:
```
<% Html.RenderPartial("~/Views/Shared/MyControl.ascx", {data model object}) %>
```
You may also see the older syntax which as of PR5 is not valid anymore
```
<%= Html.RenderUserControl("~/Views/Shared/MyControl.ascx", {data model object}) %>
```
You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems. |
41,724 | <p>I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen <a href="http://ayende.com/blog/tags/domain-specific-languages" rel="noreferrer">Ayende's blog posts</a> and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider.</p>
<p>If you've got some background using these things, any chance you could put it in real laymans terms:</p>
<ul>
<li>What exactly building DSLs means?</li>
<li>What languages are you using?</li>
<li>Where using a DSL makes sense?</li>
<li>What is the benefit of using DSLs?</li>
</ul>
| [
{
"answer_id": 41735,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": false,
"text": "<p><strong>DSL</strong> stands for <em>Domain Specific Language</em> i.e. language designed specifically for solving problems in given area.<br>\nFor example, Markdown (markup language used to edit posts on SO) can be considered as a DSL.</p>\n\n<p>Personally I find a place for DSL almost in every large project I'm working on. Most often I need some kind of SQL-like query language. Another common usage is rule-based systems, you need some kind of language to specify rules\\conditions.</p>\n\n<p>DSL makes sense in context where it's difficult to describe\\solve problem by traditional means.</p>\n"
},
{
"answer_id": 41742,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 1,
"selected": false,
"text": "<p>DSL is basically creating your own small sublanguage to solve a specific domain problem. This is solved using method chaining. Languages where dots and parentheses are optional help make these expression seem more natural. It can also be similar to a builder pattern.\nDSL aren't languages themselves, but rather a pattern that you apply to your API to make the calls be more self explanatory.</p>\n\n<p>One example is Guice, <a href=\"http://docs.google.com/View?docid=dd2fhx4z_5df5hw8\" rel=\"nofollow noreferrer\">Guice Users Guide http://docs.google.com/View?docid=dd2fhx4z_5df5hw8</a> has some description further down of how interfaces are bound to implementations, and in what contexts.</p>\n\n<p>Another common example is for query languages. For example:</p>\n\n<pre><code>NewsDAO.writtenBy(\"someUser\").before(\"someDate\").updateStatus(\"Deleted\")\n</code></pre>\n\n<p>In the implementation, imagine each method returning either a new Query object, or just this updating itself internally. At any point you can terminate the chain by using for example rows() to get all the rows, or updateSomeField as I have done above here. Both will return a result object.</p>\n\n<p>I would recommend taking a look at the Guice example above as well, as each call there returns a new type with new options on them. A good IDE will allow you to complete, making it clear which options you have at each point. </p>\n\n<p>Edit: seems many consider DSLs as new, simple, single purpose languages with their own parsers. I always associate DSL as using method chaining as a convention to express operations.</p>\n"
},
{
"answer_id": 41743,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 5,
"selected": true,
"text": "<p>DSL's are good in situations where you need to give some aspect of the system's control over to someone else. I've used them in Rules Engines, where you create a simple language that is easier for less-technical folks to use to express themselves- particularly in workflows.</p>\n\n<p>In other words, instead of making them learn java:</p>\n\n<pre><code>DocumentDAO myDocumentDAO = ServiceLocator.getDocumentDAO();\nfor (int id : documentIDS) {\nDocument myDoc = MyDocumentDAO.loadDoc(id);\nif (myDoc.getDocumentStatus().equals(DocumentStatus.UNREAD)) {\n ReminderService.sendUnreadReminder(myDoc)\n}\n</code></pre>\n\n<p>I can write a DSL that lets me say:</p>\n\n<pre><code>for (document : documents) {\nif (document is unread) {\n document.sendReminder\n}\n</code></pre>\n\n<p>There are other situations, but basically, anywhere you might want to use a macro language, script a workflow, or allow after-market customization- these are all candidates for DSL's.</p>\n"
},
{
"answer_id": 41751,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "<p>DSL is just a fancy name and can mean different things:</p>\n\n<ul>\n<li><p>Rails (the Ruby thing) is sometimes called a DSL because it adds special methods (and overwrites some built-in ones too) for talking about web applications</p></li>\n<li><p>ANT, Makefile syntax etc. are also DSLs, but have their own syntax. This is what I would call a DSL.</p></li>\n</ul>\n\n<p>One important aspect of this hype: It does make sense to think of your application in terms of a language. What do you want to talk about in your app? These should then be your classes and methods:</p>\n\n<ol>\n<li>Define a \"language\" (either a real syntax as proposed by others on this page or a class hierarchy for your favorite language) that is capable of expressing your problem. </li>\n<li>Solve your problem in terms of that language.</li>\n</ol>\n"
},
{
"answer_id": 41759,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 3,
"selected": false,
"text": "<p>If you use Microsoft Visual Studio, you are already using multiple DSLs -- the design surface for web forms, winforms, etc. is a DSL. The Class Designer is another example.</p>\n\n<p>A DSL is just a set of tools that (at least in theory) make development in a specific \"domain\" (i.e. visual layout) easier, more intuitive, and more productive.</p>\n\n<p>As far as building a DSL, some of the stuff people like Ayende have written about is related to \"text parsing\" dsls, letting developers (or end users) enter \"natural text\" into an application, which parses the text and generates some sort of code or output based on it.</p>\n\n<p>You could use any language to build your own DSL. Microsoft Visual Studio has a lot of extensibility points, and the patterns & practices <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=E3D101DB-6EE1-4EC5-884E-97B27E49EAAE&displaylang=en\" rel=\"nofollow noreferrer\">\"Guidance Automation Toolkit\"</a> and <a href=\"http://msdn.microsoft.com/en-us/vsx/default.aspx\" rel=\"nofollow noreferrer\">Visual Studio SDK</a> can assist you in adding DSL functionality to Visual Studio.</p>\n"
},
{
"answer_id": 41768,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 2,
"selected": false,
"text": "<p>DSL are basic compilers for custom languages. A good 'free and open' tool to develop them is available at <a href=\"http://antlr.org/\" rel=\"nofollow noreferrer\">ANTLR</a>. Recently, I've been looking at this DSL for a <a href=\"http://www.codeplex.com/SimpleStateMachine/SourceControl/DownloadSourceCode.aspx?changeSetId=10958\" rel=\"nofollow noreferrer\">state machine language</a> use on a new project . I agree with Tim Howland above, that they can be a good way to let someone else customize your application. </p>\n"
},
{
"answer_id": 41861,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "<p>FYI, a book on DSLs is in the pipeline as part of Martin Fowler's signature series.</p>\n\n<p>If its of the same standard as the other books in the series, it should be a good read.</p>\n\n<p>More information <a href=\"http://martinfowler.com/dslwip/\" rel=\"nofollow noreferrer\">here</a></p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen [Ayende's blog posts](http://ayende.com/blog/tags/domain-specific-languages) and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider.
If you've got some background using these things, any chance you could put it in real laymans terms:
* What exactly building DSLs means?
* What languages are you using?
* Where using a DSL makes sense?
* What is the benefit of using DSLs? | DSL's are good in situations where you need to give some aspect of the system's control over to someone else. I've used them in Rules Engines, where you create a simple language that is easier for less-technical folks to use to express themselves- particularly in workflows.
In other words, instead of making them learn java:
```
DocumentDAO myDocumentDAO = ServiceLocator.getDocumentDAO();
for (int id : documentIDS) {
Document myDoc = MyDocumentDAO.loadDoc(id);
if (myDoc.getDocumentStatus().equals(DocumentStatus.UNREAD)) {
ReminderService.sendUnreadReminder(myDoc)
}
```
I can write a DSL that lets me say:
```
for (document : documents) {
if (document is unread) {
document.sendReminder
}
```
There are other situations, but basically, anywhere you might want to use a macro language, script a workflow, or allow after-market customization- these are all candidates for DSL's. |
41,733 | <p>Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this?</p>
<pre><code>TExample = record
SortOrder : integer;
SomethingElse : string;
end;
var SomeVar : array of TExample;
</code></pre>
| [
{
"answer_id": 41809,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 0,
"selected": false,
"text": "<p>Use one of the sort alorithms propose by <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm\" rel=\"nofollow noreferrer\">Wikipedia</a>. The Swap function should swap array elements using a temporary variable of the same type as the array elements. Use a stable sort if you want entries with the same SortOrder integer value to stay in the order they were in the first place.</p>\n"
},
{
"answer_id": 41951,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 6,
"selected": true,
"text": "<p>You can add pointers to the elements of the array to a <code>TList</code>, then call <code>TList.Sort</code> with a comparison function, and finally create a new array and copy the values out of the TList in the desired order.</p>\n\n<p>However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional <code>IComparer<TExample></code> implementation for custom sorting orders. Here it is in action for your specific case:</p>\n\n<pre><code>TArray.Sort<TExample>(SomeVar , TDelegatedComparer<TExample>.Construct(\n function(const Left, Right: TExample): Integer\n begin\n Result := TComparer<Integer>.Default.Compare(Left.SortOrder, Right.SortOrder);\n end));\n</code></pre>\n"
},
{
"answer_id": 49702,
"author": "ddowns",
"author_id": 5201,
"author_profile": "https://Stackoverflow.com/users/5201",
"pm_score": 1,
"selected": false,
"text": "<p>With an array, I'd use either <code>quicksort</code> or possibly <code>heapsort</code>, and just change the comparison to use <code>TExample.SortOrder</code>, the swap part is still going to just act on the array and swap pointers. If the array is very large then you may want a linked list structure if there's a lot of insertion and deletion.</p>\n\n<p>C based routines, there are several here\n<a href=\"http://www.yendor.com/programming/sort/\" rel=\"nofollow noreferrer\">http://www.yendor.com/programming/sort/</a></p>\n\n<p>Another site, but has pascal source\n<a href=\"http://www.dcc.uchile.cl/~rbaeza/handbook/sort_a.html\" rel=\"nofollow noreferrer\">http://www.dcc.uchile.cl/~rbaeza/handbook/sort_a.html</a></p>\n"
},
{
"answer_id": 161661,
"author": "CoolMagic",
"author_id": 22641,
"author_profile": "https://Stackoverflow.com/users/22641",
"pm_score": 2,
"selected": false,
"text": "<p>If your need sorted by string then use sorted <code>TStringList</code> and \nadd record by <code>TString.AddObject(string, Pointer(int_val))</code>.</p>\n\n<p>But If need sort by integer field and string - use <code>TObjectList</code> and after adding all records call <code>TObjectList.Sort</code> with necessary sorted functions as parameter.</p>\n"
},
{
"answer_id": 161880,
"author": "Germán Estévez -Neftalí-",
"author_id": 17487,
"author_profile": "https://Stackoverflow.com/users/17487",
"pm_score": 0,
"selected": false,
"text": "<p><code>TStringList</code> have efficient Sort Method.<br>\nIf you want Sort use a <code>TStringList</code> object with <code>Sorted</code> property to True. </p>\n\n<p>NOTE: For more speed, add objects in a not Sorted <code>TStringList</code> and at the end change the property to True.<br>\nNOTE: For sort by integer Field, convert to String.<br>\nNOTE: If there are duplicate values, this method not is Valid. </p>\n\n<p>Regards.</p>\n"
},
{
"answer_id": 162850,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 2,
"selected": false,
"text": "<p>This all depends on the number of records you are sorting. If you are only sorting less than a few hundred then the other sort methods work fine, if you are going to be sorting more, then take a good look at the old trusty Turbo Power <a href=\"http://sourceforge.net/projects/tpsystools/\" rel=\"nofollow noreferrer\">SysTools</a> project. There is a very good sort algorithm included in the source. One that does a very good job sorting millions of records in a efficient manner.</p>\n\n<p>If you are going to use the tStringList method of sorting a list of records, make sure that your integer is padded to the right before inserting it into the list. You can use the <strong>format('%.10d',[rec.sortorder])</strong> to right align to 10 digits for example.</p>\n"
},
{
"answer_id": 1381865,
"author": "Guy Gordon",
"author_id": 652328,
"author_profile": "https://Stackoverflow.com/users/652328",
"pm_score": 4,
"selected": false,
"text": "<p>(I know this is a year later, but still useful stuff.)</p>\n<p>Skamradt's suggestion to pad integer values assumes you are going to sort using a string compare. This would be slow. Calling format() for each insert, slower still. Instead, you want to do an integer compare.</p>\n<p>You start with a record type:</p>\n<pre><code>TExample = record\n SortOrder : integer;\n SomethingElse : string;\nend;\n</code></pre>\n<p>You didn't state how the records were stored, or how you wanted to access them once sorted. So let's assume you put them in a Dynamic Array:</p>\n<pre><code>var MyDA: Array of TExample; \n...\n SetLength(MyDA,NewSize); //allocate memory for the dynamic array\n for i:=0 to NewSize-1 do begin //fill the array with records\n MyDA[i].SortOrder := SomeInteger;\n MyDA[i].SomethingElse := SomeString;\n end;\n</code></pre>\n<p>Now you want to sort this array by the integer value SortOrder. If what you want out is a TStringList (so you can use the ts.Find method) then you should add each string to the list and add the SortOrder as a pointer. Then sort on the pointer:</p>\n<pre><code>var tsExamples: TStringList; //declare it somewhere (global or local)\n...\n tsExamples := tStringList.create; //allocate it somewhere (and free it later!)\n...\n tsExamples.Clear; //now let's use it\n tsExamples.sorted := False; //don't want to sort after every add\n tsExamples.Capacity := High(MyDA)+1; //don't want to increase size with every add\n //an empty dynamic array has High() = -1\n for i:=0 to High(MyDA) do begin\n tsExamples.AddObject(MyDA[i].SomethingElse,TObject(MyDA[i].SortOrder));\n end;\n</code></pre>\n<p>Note the trick of casting the Integer SortOrder into a TObject pointer, which is stored in the TStringList.Object property. (This depends upon the fact that Integer and Pointer are the same size.) Somewhere we must define a function to compare the TObject pointers:</p>\n<pre><code>function CompareObjects(ts:tStringList; Item1,Item2: integer): Integer;\nbegin\n Result := CompareValue(Integer(ts.Objects[Item1]), Integer(ts.Objects[Item2]))\nend;\n</code></pre>\n<p>Now, we can sort the tsList on .Object by calling .CustomSort instead of .Sort (which would sort on the string value.)</p>\n<pre><code>tsExamples.CustomSort(@CompareObjects); //Sort the list\n</code></pre>\n<p>The TStringList is now sorted, so you can iterate over it from 0 to .Count-1 and read the strings in sorted order.</p>\n<p>But suppose you didn't want a TStringList, just an array in sorted order. Or the records contain more data than just the one string in this example, and your sort order is more complex. You can skip the step of adding every string, and just add the array index as Items in a TList. Do everything above the same way, except use a TList instead of TStringList:</p>\n<pre><code>var Mlist: TList; //a list of Pointers\n...\n for i:=0 to High(MyDA) do\n Mlist.add(Pointer(i)); //cast the array index as a Pointer\n Mlist.Sort(@CompareRecords); //using the compare function below\n\nfunction CompareRecords(Item1, Item2: Integer): Integer;\nvar i,j: integer;\nbegin\n i := integer(item1); //recover the index into MyDA\n j := integer(item2); // and use it to access any field\n Result := SomeFunctionOf(MyDA[i].SomeField) - SomeFunctionOf(MyDA[j].SomeField);\nend;\n</code></pre>\n<p>Now that Mlist is sorted, use it as a lookup table to access the array in sorted order:</p>\n<pre><code> for i:=0 to Mlist.Count-1 do begin\n Something := MyDA[integer(Mlist[i])].SomeField;\n end;\n</code></pre>\n<p>As i iterates over the TList, we get back the array indexes in sorted order. We just need to cast them back to integers, since the TList thinks they're pointers.</p>\n<p>I like doing it this way, but you could also put real pointers to array elements in the TList by adding the Address of the array element instead of it's index. Then to use them you would cast them as pointers to TExample records. This is what Barry Kelly and CoolMagic said to do in their answers.</p>\n"
},
{
"answer_id": 9001207,
"author": "rt15",
"author_id": 1168949,
"author_profile": "https://Stackoverflow.com/users/1168949",
"pm_score": 1,
"selected": false,
"text": "<p>The quicksort algorithm is often used when fast sorting is required. Delphi is (Or was) using it for List.Sort for example.\nDelphi List can be used to sort anything, but it is an heavyweight container, which is supposed to look like an array of pointers on structures. It is heavyweight even if we use tricks like Guy Gordon in this thread (Putting index or anything in place of pointers, or putting directly values if they are smaller than 32 bits): we need to construct a list and so on...</p>\n\n<p>Consequently, an alternative to easily and fastly sort an array of struct might be to use <a href=\"http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/\" rel=\"nofollow\">qsort C runtime function</a> from msvcrt.dll.</p>\n\n<p>Here is a declaration that might be good (Warning: code portable on windows only).</p>\n\n<pre><code>type TComparatorFunction = function(lpItem1: Pointer; lpItem2: Pointer): Integer; cdecl;\nprocedure qsort(base: Pointer; num: Cardinal; size: Cardinal; lpComparatorFunction: TComparatorFunction) cdecl; external 'msvcrt.dll';\n</code></pre>\n\n<p>Full example <a href=\"http://www.delphifr.com/forum/sujet-COLOR-IMAGE_1567766.aspx#3\" rel=\"nofollow\">here</a>.</p>\n\n<p>Notice that directly sorting the array of records can be slow if the records are big. In that case, sorting an array of pointer to the records can be faster (Somehow like List approach).</p>\n"
},
{
"answer_id": 28460112,
"author": "David Miró",
"author_id": 2270217,
"author_profile": "https://Stackoverflow.com/users/2270217",
"pm_score": -1,
"selected": false,
"text": "<p>I created a very simple example that works correctly if the sort field is a string.</p>\n\n<pre><code>Type\n THuman = Class\n Public\n Name: String;\n Age: Byte;\n Constructor Create(Name: String; Age: Integer);\n End;\n\nConstructor THuman.Create(Name: String; Age: Integer);\nBegin\n Self.Name:= Name;\n Self.Age:= Age;\nEnd;\n\nProcedure Test();\nVar\n Human: THuman;\n Humans: Array Of THuman;\n List: TStringList;\nBegin\n\n SetLength(Humans, 3);\n Humans[0]:= THuman.Create('David', 41);\n Humans[1]:= THuman.Create('Brian', 50);\n Humans[2]:= THuman.Create('Alex', 20);\n\n List:= TStringList.Create;\n List.AddObject(Humans[0].Name, TObject(Humans[0]));\n List.AddObject(Humans[1].Name, TObject(Humans[1]));\n List.AddObject(Humans[2].Name, TObject(Humans[2]));\n List.Sort;\n\n Human:= THuman(List.Objects[0]);\n Showmessage('The first person on the list is the human ' + Human.name + '!');\n\n List.Free;\nEnd;\n</code></pre>\n"
},
{
"answer_id": 47884859,
"author": "Jacek Krawczyk",
"author_id": 1960514,
"author_profile": "https://Stackoverflow.com/users/1960514",
"pm_score": 0,
"selected": false,
"text": "<p>If you have Delphi XE2 or newer, you can try:</p>\n\n<pre><code>var \n someVar: array of TExample;\n list: TList<TExample>;\n sortedVar: array of TExample;\nbegin\n list := TList<TExample>.Create(someVar);\n try\n list.Sort;\n sortedVar := list.ToArray;\n finally\n list.Free;\n end;\nend;\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
] | Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this?
```
TExample = record
SortOrder : integer;
SomethingElse : string;
end;
var SomeVar : array of TExample;
``` | You can add pointers to the elements of the array to a `TList`, then call `TList.Sort` with a comparison function, and finally create a new array and copy the values out of the TList in the desired order.
However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional `IComparer<TExample>` implementation for custom sorting orders. Here it is in action for your specific case:
```
TArray.Sort<TExample>(SomeVar , TDelegatedComparer<TExample>.Construct(
function(const Left, Right: TExample): Integer
begin
Result := TComparer<Integer>.Default.Compare(Left.SortOrder, Right.SortOrder);
end));
``` |
41,763 | <p>What is the best way to calculate Age using Flex?</p>
| [
{
"answer_id": 41845,
"author": "Richard Braxton",
"author_id": 4393,
"author_profile": "https://Stackoverflow.com/users/4393",
"pm_score": 4,
"selected": false,
"text": "<p>I found an answer at <a href=\"http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=08_Dates_and_times_164_2.html\" rel=\"nofollow noreferrer\">the bottom of this page in comments section (which is now offline)</a>. </p>\n\n<blockquote>\n <p><strong>jpwrunyan said on Apr 30, 2007 at 10:10 PM :</strong></p>\n \n <blockquote>\n <p>By the way, here is how to calculate age in years (only) from DOB without needing to account for leap years:</p>\n </blockquote>\n</blockquote>\n\n<p>With a slight correction by <a href=\"https://stackoverflow.com/users/210612/fine-wei-lin\">Fine-Wei Lin</a>, the code reads</p>\n\n<pre><code>private function getYearsOld(dob:Date):uint { \n var now:Date = new Date(); \n var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear); \n if (dob.month > now.month || (dob.month == now.month && dob.date > now.date)) \n {\n yearsOld--;\n }\n return yearsOld; \n}\n</code></pre>\n\n<blockquote>\n <blockquote>\n <p>This handles most situations where you need to calculate age. </p>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 43789,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 1,
"selected": false,
"text": "<p>You could also do it roughly the same as discussed <a href=\"https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c\" title=\"Jeff Atwodd's Question about calculating age in C#\">here</a>: (translated to AS3)</p>\n\n<pre><code>var age:int = (new Date()).fullYear - bDay.fullYear;\nif ((new Date()) < (new Date((bDay.fullYear + age), bDay.month, bDay.date))) age--;\n</code></pre>\n"
},
{
"answer_id": 542129,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a little more complex calculation, this calculates age in years and months. Example: User is 3 years 2 months old.</p>\n\n<pre><code>private function calculateAge(dob:Date):String { \n var now:Date = new Date();\n\n var ageDays:int = 0;\n var ageYears:int = 0;\n var ageRmdr:int = 0;\n\n var diff:Number = now.getTime()-dob.getTime();\n ageDays = diff / 86400000;\n ageYears = Math.floor(ageDays / 365.24);\n ageRmdr = Math.floor( (ageDays - (ageYears*365.24)) / 30.4375 );\n\n if ( ageRmdr == 12 ) {\n ageRmdr = 11;\n }\n\n return ageYears + \" years \" + ageRmdr + \" months\";\n}\n</code></pre>\n"
},
{
"answer_id": 542592,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var userDOB : Date = new Date(year,month-1,day);\nvar today : Date = new Date();\n\nvar diff : Date = new Date();\ndiff.setTime( today.getTime() - userDOB.getTime() );\n\nvar userAge : int = diff.getFullYear() - 1970;\n</code></pre>\n"
},
{
"answer_id": 1269238,
"author": "datico",
"author_id": 127105,
"author_profile": "https://Stackoverflow.com/users/127105",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a one-liner:</p>\n\n<pre><code>int( now.getFullYear() - dob.getFullYear() + (now.getMonth() - dob.getMonth())*.01 + (now.getDate() - dob.getDate())*.0001 );\n</code></pre>\n"
},
{
"answer_id": 2791649,
"author": "jowie",
"author_id": 190657,
"author_profile": "https://Stackoverflow.com/users/190657",
"pm_score": 1,
"selected": false,
"text": "<p>I found a few problems with the top answer here. I used a couple of answers here to cobble together something which was accurate (for me anyway, hope for you too!)</p>\n\n<pre><code>private function getYearsOld(dob:Date):uint\n{\n var now:Date = new Date();\n var age:Date = new Date(now.getTime() - dob.getTime());\n var yearsOld:uint = age.getFullYear() - 1970;\n return yearsOld;\n}\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4393/"
] | What is the best way to calculate Age using Flex? | I found an answer at [the bottom of this page in comments section (which is now offline)](http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=08_Dates_and_times_164_2.html).
>
> **jpwrunyan said on Apr 30, 2007 at 10:10 PM :**
>
>
>
> >
> > By the way, here is how to calculate age in years (only) from DOB without needing to account for leap years:
> >
> >
> >
>
>
>
With a slight correction by [Fine-Wei Lin](https://stackoverflow.com/users/210612/fine-wei-lin), the code reads
```
private function getYearsOld(dob:Date):uint {
var now:Date = new Date();
var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear);
if (dob.month > now.month || (dob.month == now.month && dob.date > now.date))
{
yearsOld--;
}
return yearsOld;
}
```
>
>
> >
> > This handles most situations where you need to calculate age.
> >
> >
> >
>
>
> |
41,792 | <p>I am re-factoring some code and am wondering about the use of a <code>lock</code> in the instance constructor.</p>
<pre><code>public class MyClass {
private static Int32 counter = 0;
private Int32 myCount;
public MyClass() {
lock(this) {
counter++;
myCount = counter;
}
}
}
</code></pre>
<p>Please confirm</p>
<ol>
<li>Instance constructors are thread-safe.</li>
<li>The lock statement prevents access to that code block, not to the static 'counter' member.</li>
</ol>
<p>If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a <code>MyClass</code> and changing the count before this one sets its count?</p>
<p><em>FYI - This class is not a singleton. Instances must simply be aware of their number.</em></p>
| [
{
"answer_id": 41801,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>I'm guessing this is for a singleton pattern or something like it. What you want to do is not lock your object, but lock the counter while your are modifying it. </p>\n\n<pre><code>private static int counter = 0;\nprivate static object counterLock = new Object();\n\nlock(counterLock) {\n counter++;\n myCounter = counter;\n}\n</code></pre>\n\n<p>Because your current code is sort of redundant. Especially being in the constructor where there is only one thread that can call a constructor, unlike with methods where it could be shared across threads and be accessed from any thread that is shared.</p>\n\n<p>From the little I can tell from you code, you are trying to give the object the current count at the time of it being created. So with the above code the counter will be locked while the counter is updated and set locally. So all other constructors will have to wait for the counter to be released.</p>\n"
},
{
"answer_id": 41804,
"author": "hakan",
"author_id": 3993,
"author_profile": "https://Stackoverflow.com/users/3993",
"pm_score": 2,
"selected": false,
"text": "<p>You can use another static object to lock on it. </p>\n\n<pre><code>private static Object lockObj = new Object();\n</code></pre>\n\n<p>and lock this object in the constructor.</p>\n\n<pre><code>lock(lockObj){}\n</code></pre>\n\n<p>However, I'm not sure if there are situations that should be handled because of compiler optimization in <code>.NET</code> like in the case of java</p>\n"
},
{
"answer_id": 41813,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>I think if you modify the <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern#C.23\" rel=\"nofollow noreferrer\">Singleton Pattern</a> to include a count (obviously using the thread-safe method), you will be fine :)</p>\n<h3>Edit</h3>\n<p>Crap I accidentally deleted!</p>\n<p>I am not sure if instance constructors <em>ARE</em> thread safe, I remember reading about this in a design patterns book, you need to ensure that locks are in place during the instantiation process, purely because of this..</p>\n"
},
{
"answer_id": 41816,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 0,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/41792/instance-constructor-sets-a-static-member-is-it-thread-safe#41795\">Rob</a></p>\n\n<p>FYI, This class may not be a singleton, I need access to different instances. They must simply maintain a count. What part of the singleton pattern would you change to perform 'counter' incrementing?</p>\n\n<p>Or are you suggesting that I expose a static method for construction blocking access to the code that increments and reads the counter with a lock.</p>\n\n<pre><code>public MyClass {\n\n private static Int32 counter = 0;\n public static MyClass GetAnInstance() {\n\n lock(MyClass) {\n counter++;\n return new MyClass();\n }\n }\n\n private Int32 myCount;\n private MyClass() {\n myCount = counter;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 41820,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": true,
"text": "<p>@ajmastrean</p>\n<p>I am not saying you should use the singleton pattern itself, but adopt its method of encapsulating the instantiation process.</p>\n<p>i.e.</p>\n<ul>\n<li>Make the constructor private.</li>\n<li>Create a static instance method that returns the type.</li>\n<li>In the static instance method, use the lock keyword before instantiating.</li>\n<li>Instantiate a new instance of the type.</li>\n<li>Increment the count.</li>\n<li>Unlock and return the new instance.</li>\n</ul>\n<h3>EDIT</h3>\n<p>One problem that has occurred to me, if how would you know when the count has gone down? ;)</p>\n<h3>EDIT AGAIN</h3>\n<p>Thinking about it, you could add code to the destructor that calls another static method to decrement the counter :D</p>\n"
},
{
"answer_id": 41852,
"author": "Mike Schall",
"author_id": 4231,
"author_profile": "https://Stackoverflow.com/users/4231",
"pm_score": 4,
"selected": false,
"text": "<p>If you are only incrementing a number, there is a special class (Interlocked) for just that...</p>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment.aspx</a></p>\n<blockquote>\n<p>Interlocked.Increment Method</p>\n<p>Increments a specified variable and stores the result, as an atomic operation.</p>\n</blockquote>\n<pre><code>System.Threading.Interlocked.Increment(myField);\n</code></pre>\n<p>More information about threading best practices...</p>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/1c9txz50.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/1c9txz50.aspx</a></p>\n"
},
{
"answer_id": 41961,
"author": "Andrew",
"author_id": 1948,
"author_profile": "https://Stackoverflow.com/users/1948",
"pm_score": 2,
"selected": false,
"text": "<p>The most efficient way to do this would be to use the Interlocked increment operation. It will increment the counter and return the newly set value of the static counter all at once (atomically)</p>\n\n<pre><code>class MyClass {\n\n static int _LastInstanceId = 0;\n private readonly int instanceId; \n\n public MyClass() { \n this.instanceId = Interlocked.Increment(ref _LastInstanceId); \n }\n}\n</code></pre>\n\n<p>In your original example, the lock(this) statement will not have the desired effect because each individual instance will have a different \"this\" reference, and multiple instances could thus be updating the static member at the same time.</p>\n\n<p>In a sense, constructors can be considered to be thread safe because the reference to the object being constructed is not visible until the constructor has completed, but this doesn't do any good for protecting a static variable.</p>\n\n<p>(Mike Schall had the interlocked bit first)</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
] | I am re-factoring some code and am wondering about the use of a `lock` in the instance constructor.
```
public class MyClass {
private static Int32 counter = 0;
private Int32 myCount;
public MyClass() {
lock(this) {
counter++;
myCount = counter;
}
}
}
```
Please confirm
1. Instance constructors are thread-safe.
2. The lock statement prevents access to that code block, not to the static 'counter' member.
If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a `MyClass` and changing the count before this one sets its count?
*FYI - This class is not a singleton. Instances must simply be aware of their number.* | @ajmastrean
I am not saying you should use the singleton pattern itself, but adopt its method of encapsulating the instantiation process.
i.e.
* Make the constructor private.
* Create a static instance method that returns the type.
* In the static instance method, use the lock keyword before instantiating.
* Instantiate a new instance of the type.
* Increment the count.
* Unlock and return the new instance.
### EDIT
One problem that has occurred to me, if how would you know when the count has gone down? ;)
### EDIT AGAIN
Thinking about it, you could add code to the destructor that calls another static method to decrement the counter :D |
41,824 | <p>I'm using Microsoft AjaxControlToolkit for modal popup window.</p>
<p>And on a modal popup window, when a postback occurred, the window was closing. How do I prevent from the closing action of the modal popup?</p>
| [
{
"answer_id": 41910,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 3,
"selected": false,
"text": "<p>You can call <code>Show()</code> method during postback to prevent the modal popup window from closing</p>\n\n<pre><code>MyModalPopoupExtender.Show()\n</code></pre>\n"
},
{
"answer_id": 42188,
"author": "Jon Erickson",
"author_id": 1950,
"author_profile": "https://Stackoverflow.com/users/1950",
"pm_score": 2,
"selected": false,
"text": "<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if (Page.IsPostBack)\n {\n // reshow\n MyModalPopup.Show()\n }\n}\n</code></pre>\n"
},
{
"answer_id": 42798,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 2,
"selected": false,
"text": "<p>I guess that works but not in my case. I've a user control that opened in a modal popup and this user control makes postback itself. So in that user control I've no modal popup property.</p>\n\n<p>I guess, I've to create an event for my user control, and the page that opens the modal popup have to reopen it in this event.</p>\n"
},
{
"answer_id": 542842,
"author": "ForceMagic",
"author_id": 62921,
"author_profile": "https://Stackoverflow.com/users/62921",
"pm_score": 1,
"selected": false,
"text": "<p>Like you prolly already know, the modal popup is clientside only, yeah you can gather informations in it during the postback, but if you do a postback he will hide 100% of the time. </p>\n\n<p>Of course, like other proposed, you can do a .show during the postback, but it depends on what you need to do.</p>\n\n<p>Actually, I don't know why you need a postback, if it's for some validations try to do them clientside.</p>\n\n<p>Could you tell us why you need to do a postback, maybe we could help you better ! :)</p>\n"
},
{
"answer_id": 4292954,
"author": "JuanKo",
"author_id": 522419,
"author_profile": "https://Stackoverflow.com/users/522419",
"pm_score": 1,
"selected": false,
"text": "<p>Following previous case... </p>\n\n<p>In Simple.aspx, user has to enter the name of a company. If user don't remember name of the company, he can click a button which will open a pop up modal window.</p>\n\n<p>what I want to do in the modal window is permit the user to do a search of a list of companies. He can enter a partial name and click search. Matches will be shown in a list below. He can click in an item of the list and return. If company does not exist, he can click a button 'New' to create a new company.</p>\n\n<p>So, as you can see, I want a lot of functionality in this modal window. </p>\n\n<p>Thanks!</p>\n\n<p>JC</p>\n"
},
{
"answer_id": 8576317,
"author": "Gregor Primar",
"author_id": 1107945,
"author_profile": "https://Stackoverflow.com/users/1107945",
"pm_score": 4,
"selected": false,
"text": "<p>Put you controls inside the update panel. Please see my sample code, pnlControls is control that holds controls that will be displayed on popup:</p>\n\n<pre><code><asp:Panel ID=\"pnlControls\" runat=\"server\">\n\n <asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\">\n <ContentTemplate>\n <asp:Button ID=\"TestButton\" runat=\"server\" Text=\"Test Button\" onclick=\"TestButton_Click\" />\n <asp:Label ID=\"Label1\" runat=\"server\" Text=\"Label\"></asp:Label> \n </ContentTemplate>\n\n </asp:UpdatePanel>\n</code></pre>\n\n<p></p>\n\n<p>This will do the job for you :)</p>\n\n<p>Best regards,\nGregor Primar</p>\n"
},
{
"answer_id": 27068727,
"author": "Darrel Lee",
"author_id": 307968,
"author_profile": "https://Stackoverflow.com/users/307968",
"pm_score": 2,
"selected": false,
"text": "<p>Was having this same problem keeping a modal open during postbacks.</p>\n\n<p>My solution:</p>\n\n<p>Use EventTarget to determine if the postback is coming from a control in the modal and keep the model open if it is. The postback can come from a control in the modal iff the modal is open.</p>\n\n<p>In the load event for the page control containing the modal. Determine if the postback is from\na child of mine. Determine if it is from the control that is in the modal panel.</p>\n\n<pre><code> Protected Sub Control_Load(sende As Object, e As EventArgs) Handles Me.Load\n If IsPostBack Then\n Dim eventTarget As String = Page.Request.Params.Get(\"__EventTarget\")\n Dim eventArgs As String = Page.Request.Params.Get(\"__EventArgument\")\n\n If Not String.IsNullOrEmpty(eventTarget) AndAlso eventTarget.StartsWith(Me.UniqueID) Then\n If eventTarget.Contains(\"$\" + _credentialBuilder.ID + \"$\") Then\n ' Postback from credential builder modal. Keep it open.\n showCredentialBuilder = True\n End If\n End If\n End If\n End Sub\n</code></pre>\n\n<p>In prerender check my flag and manually show the modal</p>\n\n<pre><code> Protected Sub Control_PreRender(ByVal sende As Object, ByVal e As EventArgs) Handles Me.PreRender\n If showCredentialBuilder Then\n _mpeCredentialEditor.Show()\n End If\n End Sub\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4215/"
] | I'm using Microsoft AjaxControlToolkit for modal popup window.
And on a modal popup window, when a postback occurred, the window was closing. How do I prevent from the closing action of the modal popup? | Put you controls inside the update panel. Please see my sample code, pnlControls is control that holds controls that will be displayed on popup:
```
<asp:Panel ID="pnlControls" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="TestButton" runat="server" Text="Test Button" onclick="TestButton_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
```
This will do the job for you :)
Best regards,
Gregor Primar |
41,836 | <p>I have tried both of :</p>
<pre><code>ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes');
</code></pre>
<p>and also :</p>
<pre><code>php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes"
</code></pre>
<p>in the .htaccess file.</p>
<p>Both methods actually <strong>do work</strong> but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site.</p>
<p>I'm not even sure where to begin trying to find out what is going on!</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/41836/setting-include-path-in-php-intermittently-fails-why#41877">cnote</a></p>
<blockquote>
<p>Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.</p>
</blockquote>
<p>The in script version was originally </p>
<pre><code>ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
</code></pre>
<p>and thus the .:.: was coming from the existing path:</p>
<pre><code>ini_get('include_path')
</code></pre>
<p>I tried removing it anyway and the problem persists.</p>
| [
{
"answer_id": 41877,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.</p>\n"
},
{
"answer_id": 42336,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried <a href=\"http://www.php.net/manual/en/function.set-include-path.php\" rel=\"nofollow noreferrer\">set_include_path()</a>?. As a benefit this returns false on failure, allowing you to at least catch the occurence and generate some meaningful debug data.\nAdditionally, you should be using the constant <code>PATH_SEPARATOR</code> as it differs between windows / *nix.</p>\n\n<p>As a specific example:</p>\n\n<pre><code>set_include_path('.' . PATH_SEPARATOR . './app/lib' . PATH_SEPARATOR . get_include_path());\n</code></pre>\n\n<p>(the get_include_path() on the end means whatever your ini / htaccess path is set to will remain)</p>\n"
},
{
"answer_id": 2227991,
"author": "Ramon de la Fuente",
"author_id": 227941,
"author_profile": "https://Stackoverflow.com/users/227941",
"pm_score": 3,
"selected": true,
"text": "<p>It turned out the issue was related to a PHP bug in 5.2.5</p>\n\n<p>Setting an \"admin_flag\" for include_path caused the include path to be empty in some requests, and Plesk sets an admin_flag in the default config for something or other. An update of PHP solved the issue.</p>\n\n<p><a href=\"http://bugs.php.net/bug.php?id=43677\" rel=\"nofollow noreferrer\">http://bugs.php.net/bug.php?id=43677</a></p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/319/"
] | I have tried both of :
```
ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes');
```
and also :
```
php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes"
```
in the .htaccess file.
Both methods actually **do work** but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site.
I'm not even sure where to begin trying to find out what is going on!
---
@[cnote](https://stackoverflow.com/questions/41836/setting-include-path-in-php-intermittently-fails-why#41877)
>
> Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.
>
>
>
The in script version was originally
```
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
```
and thus the .:.: was coming from the existing path:
```
ini_get('include_path')
```
I tried removing it anyway and the problem persists. | It turned out the issue was related to a PHP bug in 5.2.5
Setting an "admin\_flag" for include\_path caused the include path to be empty in some requests, and Plesk sets an admin\_flag in the default config for something or other. An update of PHP solved the issue.
<http://bugs.php.net/bug.php?id=43677> |
41,839 | <p>I'm writing a tool to run a series of integration tests on my product. It will install it and then run a bunch of commands against it to make sure its doing what it is supposed to. I'm exploring different options for how to markup the commands for each test case and wondering if folks had insight to share on this. I'm thinking of using YAML and doing something like this (kinda adapted from rails fixtures): </p>
<pre><code>case:
name: caseN
description: this tests foo to make sure bar happens
expected_results: bar should happen
commands: |
command to run
next command to run
verification: command to see if it worked
</code></pre>
<p>Does anyone have another, or better idea? Or is there a domain specific language I'm unaware of? </p>
| [
{
"answer_id": 41848,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to check out <a href=\"http://www.cpan.org/\" rel=\"nofollow noreferrer\">CPAN</a>. It does for Perl scripts exactly what it sounds like your utility will do for your app.</p>\n"
},
{
"answer_id": 41947,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 3,
"selected": true,
"text": "<p>Go and have a look at the XUnit suite of test tools. This framework was originally designed for Smalltalk by Kent Beck and, I think, Erich Gamma, and it has now been ported to a whole stack of other languages, e.g. <a href=\"http://cunit.sourceforge.net/\" rel=\"nofollow noreferrer\">CUnit</a></p>\n"
},
{
"answer_id": 82285,
"author": "Željko Filipin",
"author_id": 17469,
"author_profile": "https://Stackoverflow.com/users/17469",
"pm_score": 1,
"selected": false,
"text": "<p>Did you take a look at <a href=\"http://rspec.info/\" rel=\"nofollow noreferrer\">RSpec</a>?</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/511/"
] | I'm writing a tool to run a series of integration tests on my product. It will install it and then run a bunch of commands against it to make sure its doing what it is supposed to. I'm exploring different options for how to markup the commands for each test case and wondering if folks had insight to share on this. I'm thinking of using YAML and doing something like this (kinda adapted from rails fixtures):
```
case:
name: caseN
description: this tests foo to make sure bar happens
expected_results: bar should happen
commands: |
command to run
next command to run
verification: command to see if it worked
```
Does anyone have another, or better idea? Or is there a domain specific language I'm unaware of? | Go and have a look at the XUnit suite of test tools. This framework was originally designed for Smalltalk by Kent Beck and, I think, Erich Gamma, and it has now been ported to a whole stack of other languages, e.g. [CUnit](http://cunit.sourceforge.net/) |
41,869 | <p>If I run the following query in SQL Server 2000 Query Analyzer:</p>
<pre><code>BULK INSERT OurTable
FROM 'c:\OurTable.txt'
WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK)
</code></pre>
<p>On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure?</p>
| [
{
"answer_id": 41942,
"author": "kaiz.net",
"author_id": 3714,
"author_profile": "https://Stackoverflow.com/users/3714",
"pm_score": 0,
"selected": false,
"text": "<p>Try to put it inside user-defined transaction and see what happens. Actually it should roll-back as you described it.</p>\n"
},
{
"answer_id": 152695,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 6,
"selected": true,
"text": "<p><code>BULK INSERT</code> acts as a series of individual <code>INSERT</code> statements and thus, if the job fails, it doesn't roll back all of the committed inserts.</p>\n\n<p>It can, however, be placed within a transaction so you could do something like this:</p>\n\n<pre><code>BEGIN TRANSACTION\nBEGIN TRY\nBULK INSERT OurTable \nFROM 'c:\\OurTable.txt' \nWITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\\t', \n ROWS_PER_BATCH = 10000, TABLOCK)\nCOMMIT TRANSACTION\nEND TRY\nBEGIN CATCH\nROLLBACK TRANSACTION\nEND CATCH\n</code></pre>\n"
},
{
"answer_id": 9520696,
"author": "Guillermo Garcia",
"author_id": 247684,
"author_profile": "https://Stackoverflow.com/users/247684",
"pm_score": 1,
"selected": false,
"text": "<p>As stated in the <code>BATCHSIZE</code> definition for BULK INSERT in MSDN Library (<a href=\"http://msdn.microsoft.com/en-us/library/ms188365(v=sql.105).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms188365(v=sql.105).aspx</a>) :</p>\n\n<p>\"If this fails, SQL Server commits or rolls back the transaction for every batch...\"</p>\n\n<p>In conclusion is not necessary to add transactionality to Bulk Insert.</p>\n"
},
{
"answer_id": 41284802,
"author": "Sai Bhasker Raju",
"author_id": 2431980,
"author_profile": "https://Stackoverflow.com/users/2431980",
"pm_score": 2,
"selected": false,
"text": "<p>You can rollback the inserts . To do that we need to understand two things first</p>\n\n<blockquote>\n <p><code>BatchSize</code></p>\n \n <p>: No of rows to be inserted per transaction . The Default is entire\n Data File. So a data file is in transaction</p>\n</blockquote>\n\n<p>Say you have a text file which has 10 rows and row 8 and Row 7 has some invalid details . When you Bulk Insert the file without specifying or with specifying batch Size , 8 out of 10 get inserted into the table. The Invalid Row's i.e. 8th and 7th gets failed and doesn't get inserted.</p>\n\n<p>This Happens because the Default <code>MAXERRORS</code> count is 10 per transaction.</p>\n\n<p><strong>As Per MSDN :</strong></p>\n\n<blockquote>\n <p>MAXERRORS :</p>\n \n <p>Specifies the maximum number of syntax errors allowed in the data\n before the bulk-import operation is canceled. Each row that cannot be\n imported by the bulk-import operation is ignored and counted as one\n error. If max_errors is not specified, the default is 10.</p>\n</blockquote>\n\n<p>So Inorder to fail all the 10 rows even if one is invalid we need to set <code>MAXERRORS=1</code> and <code>BatchSize=1</code> Here the number of BatchSize also matters. </p>\n\n<p>If you specify BatchSize and the invalid row is inside the particular batch , it will rollback the particular batch only ,not the entire data set.\nSo be careful while choosing this option </p>\n\n<p>Hope this solves the issue.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831/"
] | If I run the following query in SQL Server 2000 Query Analyzer:
```
BULK INSERT OurTable
FROM 'c:\OurTable.txt'
WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK)
```
On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure? | `BULK INSERT` acts as a series of individual `INSERT` statements and thus, if the job fails, it doesn't roll back all of the committed inserts.
It can, however, be placed within a transaction so you could do something like this:
```
BEGIN TRANSACTION
BEGIN TRY
BULK INSERT OurTable
FROM 'c:\OurTable.txt'
WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t',
ROWS_PER_BATCH = 10000, TABLOCK)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH
``` |
41,894 | <p>Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.</p>
| [
{
"answer_id": 41904,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 7,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code> StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();\n StackTraceElement main = stack[stack.length - 1];\n String mainClass = main.getClassName ();\n</code></pre>\n\n<p>Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out.</p>\n\n<p><strong>Edit:</strong> Pulling in @John Meagher's comment, which is a great idea:</p>\n\n<blockquote>\n <p>To expand on @jodonnell you can also\n get all stack traces in the system\n using Thread.getAllStackTraces(). From\n this you can search all the stack\n traces for the \"main\" Thread to\n determine what the main class is. This\n will work even if your class is not\n running in the main thread.</p>\n</blockquote>\n"
},
{
"answer_id": 42082,
"author": "polarbear",
"author_id": 3636,
"author_profile": "https://Stackoverflow.com/users/3636",
"pm_score": 2,
"selected": false,
"text": "<p>Also from the command line you could run the <a href=\"http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jps.html\" rel=\"nofollow noreferrer\">jps</a> tool. Sounds like a </p>\n\n<pre><code>jps -l \n</code></pre>\n\n<p>will get you what you want.</p>\n"
},
{
"answer_id": 42938,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 4,
"selected": false,
"text": "<p>To expand on @jodonnell you can also get all stack traces in the system using <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getAllStackTraces%28%29\" rel=\"nofollow noreferrer\">Thread.getAllStackTraces()</a>. From this you can search all the stack traces for the <code>main</code> Thread to determine what the main class is. This will work even if your class is not running in the main thread. </p>\n"
},
{
"answer_id": 2421152,
"author": "Adam",
"author_id": 291006,
"author_profile": "https://Stackoverflow.com/users/291006",
"pm_score": -1,
"selected": false,
"text": "<p>Or you could just use getClass(). You can do something like:</p>\n\n<pre><code>public class Foo\n{\n public static final String PROGNAME = new Foo().getClass().getName();\n}\n</code></pre>\n\n<p>And then PROGNAME will be available anywhere inside Foo. If you're not in a static context, it gets easier as you could use this:</p>\n\n<pre><code>String myProgramName = this.getClass().getName();\n</code></pre>\n"
},
{
"answer_id": 7201901,
"author": "color",
"author_id": 913678,
"author_profile": "https://Stackoverflow.com/users/913678",
"pm_score": -1,
"selected": false,
"text": "<p>Try this :</p>\n\n<p>Java classes have static instance of their own class (java.lang.Class type).</p>\n\n<p>That means if we have a class named Main.\nThen we can get its class instance by\nMain.class</p>\n\n<p>If you're interested in name only then,</p>\n\n<p>String className = Main.class.getName();</p>\n"
},
{
"answer_id": 8883260,
"author": "tschodt",
"author_id": 1069589,
"author_profile": "https://Stackoverflow.com/users/1069589",
"pm_score": 2,
"selected": false,
"text": "<p>For access to the class objects when you are in a static context</p>\n\n<pre><code>public final class ClassUtils {\n public static final Class[] getClassContext() {\n return new SecurityManager() { \n protected Class[] getClassContext(){return super.getClassContext();}\n }.getClassContext(); \n };\n private ClassUtils() {};\n public static final Class getMyClass() { return getClassContext()[2];}\n public static final Class getCallingClass() { return getClassContext()[3];}\n public static final Class getMainClass() { \n Class[] c = getClassContext();\n return c[c.length-1];\n }\n public static final void main(final String[] arg) {\n System.out.println(getMyClass());\n System.out.println(getCallingClass());\n System.out.println(getMainClass());\n }\n}\n</code></pre>\n\n<p>Obviously here all 3 calls will return </p>\n\n<pre><code>class ClassUtils\n</code></pre>\n\n<p>but you get the picture;</p>\n\n<pre><code>classcontext[0] is the securitymanager\nclasscontext[1] is the anonymous securitymanager\nclasscontext[2] is the class with this funky getclasscontext method\nclasscontext[3] is the calling class\nclasscontext[last entry] is the root class of this thread.\n</code></pre>\n"
},
{
"answer_id": 12031392,
"author": "Andrew Taylor",
"author_id": 303442,
"author_profile": "https://Stackoverflow.com/users/303442",
"pm_score": 3,
"selected": false,
"text": "<p>This is the code I came up with when using the combined responses of jodonnell and John Meagher. It stores the main class in a static variable to reduce overhead of repeated calls:</p>\n\n<pre><code>private static Class<?> mainClass;\n\npublic static Class<?> getMainClass() {\n if (mainClass != null)\n return mainClass;\n\n Collection<StackTraceElement[]> stacks = Thread.getAllStackTraces().values();\n for (StackTraceElement[] currStack : stacks) {\n if (currStack.length==0)\n continue;\n StackTraceElement lastElem = currStack[currStack.length - 1];\n if (lastElem.getMethodName().equals(\"main\")) {\n try {\n String mainClassName = lastElem.getClassName();\n mainClass = Class.forName(mainClassName);\n return mainClass;\n } catch (ClassNotFoundException e) {\n // bad class name in line containing main?! \n // shouldn't happen\n e.printStackTrace();\n }\n }\n }\n return null;\n}\n</code></pre>\n"
},
{
"answer_id": 12989117,
"author": "Nadav Brandes",
"author_id": 1622468,
"author_profile": "https://Stackoverflow.com/users/1622468",
"pm_score": 4,
"selected": false,
"text": "<pre><code>System.getProperty(\"sun.java.command\")\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823/"
] | Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough. | Try this:
```
StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName ();
```
Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out.
**Edit:** Pulling in @John Meagher's comment, which is a great idea:
>
> To expand on @jodonnell you can also
> get all stack traces in the system
> using Thread.getAllStackTraces(). From
> this you can search all the stack
> traces for the "main" Thread to
> determine what the main class is. This
> will work even if your class is not
> running in the main thread.
>
>
> |
41,925 | <p>What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently.</p>
<p><strong>Edit:</strong> Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like</p>
<pre><code>where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2)
</code></pre>
<p>which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field.</p>
<p><strong>[Edit]</strong></p>
<p>People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.</p>
| [
{
"answer_id": 41929,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps storing the phone number sections in different columns, allowing for blank or null entries?</p>\n"
},
{
"answer_id": 41938,
"author": "Don",
"author_id": 1989,
"author_profile": "https://Stackoverflow.com/users/1989",
"pm_score": 1,
"selected": false,
"text": "<p>I think free text (maybe varchar(25)) is the most widely used standard. This will allow for any format, either domestic or international.</p>\n\n<p>I guess the main driving factor may be how exactly you're querying these numbers and what you're doing with them.</p>\n"
},
{
"answer_id": 41946,
"author": "Bjorn Reppen",
"author_id": 1324220,
"author_profile": "https://Stackoverflow.com/users/1324220",
"pm_score": 6,
"selected": false,
"text": "<p>KISS - I'm getting tired of many of the US web sites. They have some cleverly written code to validate postal codes and phone numbers. When I type my perfectly valid Norwegian contact info I find that quite often it gets rejected.</p>\n\n<p>Leave it a string, unless you have some specific need for something more advanced.</p>\n"
},
{
"answer_id": 41949,
"author": "ColinYounger",
"author_id": 1223,
"author_profile": "https://Stackoverflow.com/users/1223",
"pm_score": 1,
"selected": false,
"text": "<p>What about storing a freetext column that shows a user-friendly version of the telephone number, then a normalised version that removes spaces, brackets and expands '+'. For example:</p>\n\n<p><strong>User friendly:</strong> +44 (0)181 4642542</p>\n\n<p><strong>Normalized:</strong> 00441814642542</p>\n"
},
{
"answer_id": 41955,
"author": "Aaron",
"author_id": 2628,
"author_profile": "https://Stackoverflow.com/users/2628",
"pm_score": 1,
"selected": false,
"text": "<p>I find most web forms correctly allow for the country code, area code, then the remaining 7 digits but almost always forget to allow entry of an extension. This almost always ends up making me utter angry words, since at work we don't have a receptionist, and my ext.# is needed to reach me.</p>\n"
},
{
"answer_id": 41956,
"author": "Mike Fielden",
"author_id": 4144,
"author_profile": "https://Stackoverflow.com/users/4144",
"pm_score": 3,
"selected": false,
"text": "<p>I personally like the idea of storing a normalized varchar phone number (e.g. 9991234567) then, of course, formatting that phone number inline as you display it. </p>\n\n<p>This way all the data in your database is \"clean\" and free of formatting</p>\n"
},
{
"answer_id": 41964,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I find most web forms correctly allow for the country code, area code, then the remaining 7 digits but almost always forget to allow entry of an extension. This almost always ends up making me utter angry words, since at work we don't have a receptionist, and my ext.# is needed to reach me.</p>\n</blockquote>\n\n<p>I would have to check, but I think our DB schema is similar. We hold a country code (it might default to the US, not sure), area code, 7 digits, and extension.</p>\n"
},
{
"answer_id": 41982,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 7,
"selected": true,
"text": "<p>First, beyond the country code, there is no real standard. About the best you can do is recognize, by the country code, which nation a particular phone number belongs to and deal with the rest of the number according to that nation's format.</p>\n\n<p>Generally, however, phone equipment and such is standardized so you can almost always break a given phone number into the following components</p>\n\n<ul>\n<li>C Country code 1-10 digits (right now 4 or less, but that may change)</li>\n<li>A Area code (Province/state/region) code 0-10 digits (may actually want a region field and an area field separately, rather than one area code)</li>\n<li>E Exchange (prefix, or switch) code 0-10 digits</li>\n<li>L Line number 1-10 digits</li>\n</ul>\n\n<p>With this method you can potentially separate numbers such that you can find, for instance, people that might be close to each other because they have the same country, area, and exchange codes. With cell phones that is no longer something you can count on though.</p>\n\n<p>Further, inside each country there are differing standards. You can always depend on a (AAA) EEE-LLLL in the US, but in another country you may have exchanges in the cities (AAA) EE-LLL, and simply line numbers in the rural areas (AAA) LLLL. You will have to start at the top in a tree of some form, and format them as you have information. For example, country code 0 has a known format for the rest of the number, but for country code 5432 you might need to examine the area code before you understand the rest of the number.</p>\n\n<p>You may also want to handle <code>vanity</code> numbers such as <code>(800) Lucky-Guy</code>, which requires recognizing that, if it's a US number, there's one too many digits (and you may need to full representation for advertising or other purposes) and that in the US the letters map to the numbers differently than in Germany.</p>\n\n<p>You may also want to store the entire number separately as a text field (with internationalization) so you can go back later and re-parse numbers as things change, or as a backup in case someone submits a bad method to parse a particular country's format and loses information.</p>\n"
},
{
"answer_id": 42028,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 3,
"selected": false,
"text": "<p>Look up E.164. Basically, you store the phone number as a code starting with the country prefix and an optional pbx suffix. Display is then a localization issue. Validation can also be done, but it's also a localization issue (based on the country prefix).</p>\n\n<p>For example, +12125551212+202 would be formatted in the en_US locale as (212) 555-1212 x202. It would have a different format in <code>en_GB</code> or <code>de_DE</code>. </p>\n\n<p>There is quite a bit of info out there about ITU-T E.164, but it's pretty cryptic. </p>\n"
},
{
"answer_id": 46596,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I would go for a freetext field and a field that contains a purely numeric version of the phone number. I would leave the representation of the phone number to the user and use the normalized field specifically for phone number comparisons in TAPI-based applications or when trying to find double entries in a phone directory. \nOf course it does not hurt providing the user with an entry scheme that adds intelligence like separate fields for country code (if necessary), area code, base number and extension.</p>\n"
},
{
"answer_id": 170898,
"author": "cmcculloh",
"author_id": 58,
"author_profile": "https://Stackoverflow.com/users/58",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, so based on the info on this page, here is a start on an international phone number validator:</p>\n\n<pre><code>function validatePhone(phoneNumber) {\n var valid = true;\n var stripped = phoneNumber.replace(/[\\(\\)\\.\\-\\ \\+\\x]/g, ''); \n\n if(phoneNumber == \"\"){\n valid = false;\n }else if (isNaN(parseInt(stripped))) {\n valid = false;\n }else if (stripped.length > 40) {\n valid = false;\n }\n return valid;\n}\n</code></pre>\n\n<p>Loosely based on a script from this page: <a href=\"http://www.webcheatsheet.com/javascript/form_validation.php\" rel=\"nofollow noreferrer\">http://www.webcheatsheet.com/javascript/form_validation.php</a></p>\n"
},
{
"answer_id": 170899,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/E.164\" rel=\"noreferrer\">Wikipedia page on E.164</a> should tell you everything you need to know.</p>\n"
},
{
"answer_id": 170919,
"author": "Jimoc",
"author_id": 24079,
"author_profile": "https://Stackoverflow.com/users/24079",
"pm_score": 0,
"selected": false,
"text": "<p>I've used 3 different ways to store phone numbers depending on the usage requirements.</p>\n\n<ol>\n<li>If the number is being stored just for human retrieval and won't be used for searching its stored in a string type field exactly as the user entered it.</li>\n<li>If the field is going to be searched on then any extra characters, such as +, spaces and brackets etc are removed and the remaining number stored in a string type field.</li>\n<li>Finally, if the phone number is going to be used by a computer/phone application, then in this case it would need to be entered and stored as a valid phone number usable by the system, this option of course, being the hardest to code for.</li>\n</ol>\n"
},
{
"answer_id": 262346,
"author": "unintentionally left blank",
"author_id": 13231,
"author_profile": "https://Stackoverflow.com/users/13231",
"pm_score": 3,
"selected": false,
"text": "<p>Here's my proposed structure, I'd appreciate feedback:</p>\n\n<p>The phone database field should be a varchar(42) with the following format:</p>\n\n<p>CountryCode - Number x Extension</p>\n\n<p>So, for example, in the US, we could have:</p>\n\n<p>1-2125551234x1234</p>\n\n<p>This would represent a US number (country code 1) with area-code/number (212) 555 1234 and extension 1234.</p>\n\n<p>Separating out the country code with a dash makes the country code clear to someone who is perusing the data. This is not <em>strictly</em> necessary because country codes are \"<a href=\"http://en.wikipedia.org/wiki/Prefix_code\" rel=\"noreferrer\">prefix codes</a>\" (you can read them left to right and you will always be able to unambiguously determine the country). But, since country codes have varying lengths (between 1 and 4 characters at the moment) you can't easily tell at a glance the country code unless you use some sort of separator. </p>\n\n<p>I use an \"x\" to separate the extension because otherwise it really wouldn't be possible (in many cases) to figure out which was the number and which was the extension.</p>\n\n<p>In this way you can store the entire number, including country code and extension, in a single database field, that you can then use to speed up your queries, instead of joining on a user-defined function as you have been painfully doing so far.</p>\n\n<p>Why did I pick a varchar(42)? Well, first off, international phone numbers will be of varied lengths, hence the \"var\". I am storing a dash and an \"x\", so that explains the \"char\", and anyway, you won't be doing integer arithmetic on the phone numbers (I guess) so it makes little sense to try to use a numeric type. As for the length of 42, I used the maximum possible length of all the fields added up, based on Adam Davis' answer, and added 2 for the dash and the 'x\". </p>\n"
},
{
"answer_id": 262382,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 0,
"selected": false,
"text": "<p>Where are you getting the phone numbers from? If you're getting them from part of the phone network, you'll get a string of digits and a number type and plan, eg</p>\n\n<p>441234567890 type/plan 0x11 (which means international E.164)</p>\n\n<p>In most cases the best thing to do is to store all of these as they are, and normalise for display, though storing normalised numbers can be useful if you want to use them as a unique key or similar. </p>\n"
},
{
"answer_id": 7567049,
"author": "dave singer",
"author_id": 966509,
"author_profile": "https://Stackoverflow.com/users/966509",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>User friendly: +44 (0)181 464 2542 normalised: 00441814642542</p>\n</blockquote>\n\n<p>The (0) is not valid in the international format. See the ITU-T E.123 standard.</p>\n\n<p>The \"normalised\" format would not be useful to US readers as they use 011 for international access.</p>\n"
},
{
"answer_id": 42857695,
"author": "Brian West",
"author_id": 1260514,
"author_profile": "https://Stackoverflow.com/users/1260514",
"pm_score": 2,
"selected": false,
"text": "<p>The standard for formatting numbers is <a href=\"https://en.wikipedia.org/wiki/E.164\" rel=\"nofollow noreferrer\">e.164</a>, You should always store numbers in this format. You should never allow the extension number in the same field with the phone number, those should be stored separately. As for numeric vs alphanumeric, It depends on what you're going to be doing with that data.</p>\n"
},
{
"answer_id": 51761170,
"author": "Alex Klaus",
"author_id": 968003,
"author_profile": "https://Stackoverflow.com/users/968003",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Storage</strong></p>\n<p>Store phones in <a href=\"https://www.ietf.org/rfc/rfc3966.txt\" rel=\"nofollow noreferrer\">RFC 3966</a> (like <code>+1-202-555-0252</code>, <code>+1-202-555-7166;ext=22</code>). The main differences from <a href=\"https://en.wikipedia.org/wiki/E.164\" rel=\"nofollow noreferrer\">E.164</a> are</p>\n<ul>\n<li>No limit on the length</li>\n<li>Support of extensions</li>\n</ul>\n<p>To optimise speed of fetching the data, also store the phone number in the National/International format, in addition to the RFC 3966 field.</p>\n<p>Don't store the country code in a separate field unless you have a serious reason for that. Why? Because you shouldn't ask for the country code on the UI.</p>\n<p>Mostly, people enter the phones as they hear them. E.g. if the local format starts with <code>0</code> or <code>8</code>, it'd be annoying for the user to do a transformation on the fly (like, "<em>OK, don't type '0', choose the country and type the rest of what the person said in this field</em>").</p>\n<p><strong>Parsing</strong></p>\n<p>Google has your back here. Their <a href=\"https://github.com/googlei18n/libphonenumber\" rel=\"nofollow noreferrer\">libphonenumber</a> library can validate and parse any phone number. There are ports to almost any language.</p>\n<p>So let the user just enter "<code>0449053501</code>" or "<code>04 4905 3501</code>" or "<code>(04) 4905 3501</code>". The tool will figure out the rest for you.</p>\n<p>See the <a href=\"https://rawgit.com/googlei18n/libphonenumber/master/javascript/i18n/phonenumbers/demo-compiled.html\" rel=\"nofollow noreferrer\">official demo</a>, to get a feeling of how much does it help.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently.
**Edit:** Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like
```
where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2)
```
which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field.
**[Edit]**
People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster. | First, beyond the country code, there is no real standard. About the best you can do is recognize, by the country code, which nation a particular phone number belongs to and deal with the rest of the number according to that nation's format.
Generally, however, phone equipment and such is standardized so you can almost always break a given phone number into the following components
* C Country code 1-10 digits (right now 4 or less, but that may change)
* A Area code (Province/state/region) code 0-10 digits (may actually want a region field and an area field separately, rather than one area code)
* E Exchange (prefix, or switch) code 0-10 digits
* L Line number 1-10 digits
With this method you can potentially separate numbers such that you can find, for instance, people that might be close to each other because they have the same country, area, and exchange codes. With cell phones that is no longer something you can count on though.
Further, inside each country there are differing standards. You can always depend on a (AAA) EEE-LLLL in the US, but in another country you may have exchanges in the cities (AAA) EE-LLL, and simply line numbers in the rural areas (AAA) LLLL. You will have to start at the top in a tree of some form, and format them as you have information. For example, country code 0 has a known format for the rest of the number, but for country code 5432 you might need to examine the area code before you understand the rest of the number.
You may also want to handle `vanity` numbers such as `(800) Lucky-Guy`, which requires recognizing that, if it's a US number, there's one too many digits (and you may need to full representation for advertising or other purposes) and that in the US the letters map to the numbers differently than in Germany.
You may also want to store the entire number separately as a text field (with internationalization) so you can go back later and re-parse numbers as things change, or as a backup in case someone submits a bad method to parse a particular country's format and loses information. |
41,928 | <p>I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of <code>lightwindow.js</code>, claiming that the <code>object does not support this property or method</code>. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later.</p>
<p>Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow).</p>
<p>These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue:</p>
<ol>
<li>Moved the call to lightwindow.js to the bottom of the page.</li>
<li>Changed line 444 to: <code>if (this._getGalleryInfo(link.rel)) {</code></li>
<li>Changed line 1157 to: <code>if (this._getGalleryInfo(this.element.rel)) {</code></li>
<li>Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a <code>try/catch</code> block, swallowing the exception.</li>
</ol>
<p><strong>EDIT:</strong> </p>
<p>I realised that this broke Firefox. Adding the following as line 445 now makes it work - <code>try { gallery = this._getGalleryInfo(link.rel); } catch (e) { }</code></p>
<p>It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution.</p>
| [
{
"answer_id": 47224,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of the try..catch maybe you could try using </p>\n\n<pre><code>if( this && this._getGalleryInfo )\n{\n //use the function\n\n}\n</code></pre>\n\n<p>you could also check in the same way <strong>this.element.rel</strong> ( <code>if(this && this.element && this.element.rel)</code> ... ) before using it.</p>\n\n<p>It looks like there's a case that the <code>_getGalleryInfo</code> or <code>this.element.rel</code> has not yet been initialized so it wouldn't exist yet. Check if it exists then if I does use it.</p>\n\n<p>of course i could be completely wrong, the only way to know is by testing it out.</p>\n"
},
{
"answer_id": 595214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem with Lightwindow 2.0, IE6, IE7, IE8 (beta); I resolved in the following way for IE6, IE7, IE8 (beta).</p>\n\n<p>Instead of:<br/>\n <code>if(gallery = this._getGalleryInfo(link.rel))</code><br/>\nI put on lines 443 and 1157:<br/>\n <code>gallery = this._getGalleryInfo(link.rel)</code><br/>\n <code>if(gallery)</code><br/></p>\n\n<p>Hope this will help!</p>\n"
},
{
"answer_id": 627554,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": true,
"text": "<p>I fixed this by changing line 444 to:</p>\n\n<pre><code>var gallery = this._getGalleryInfo(link.rel)\n</code></pre>\n\n<p>Then changing the subsequent comparison statement to: </p>\n\n<pre><code>if(gallery.length > 0)\n{\n // Rest of code here...\n</code></pre>\n\n<p>...which seems to have sorted it in IE6+ and kept it working in Firefox etc.</p>\n\n<p>I didn't change line 1157 at all, but I haven't read the code to see what I actually does so I can't comment on its relevance? </p>\n\n<p>I suspect the ? used in the example rel attribute (Evoution?[man]) may be causing the problem with IE but without spending some time testing a few things, I can't be sure?</p>\n\n<p>HTH. </p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] | I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of `lightwindow.js`, claiming that the `object does not support this property or method`. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later.
Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow).
These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue:
1. Moved the call to lightwindow.js to the bottom of the page.
2. Changed line 444 to: `if (this._getGalleryInfo(link.rel)) {`
3. Changed line 1157 to: `if (this._getGalleryInfo(this.element.rel)) {`
4. Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a `try/catch` block, swallowing the exception.
**EDIT:**
I realised that this broke Firefox. Adding the following as line 445 now makes it work - `try { gallery = this._getGalleryInfo(link.rel); } catch (e) { }`
It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution. | I fixed this by changing line 444 to:
```
var gallery = this._getGalleryInfo(link.rel)
```
Then changing the subsequent comparison statement to:
```
if(gallery.length > 0)
{
// Rest of code here...
```
...which seems to have sorted it in IE6+ and kept it working in Firefox etc.
I didn't change line 1157 at all, but I haven't read the code to see what I actually does so I can't comment on its relevance?
I suspect the ? used in the example rel attribute (Evoution?[man]) may be causing the problem with IE but without spending some time testing a few things, I can't be sure?
HTH. |
41,948 | <p>I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.</p>
| [
{
"answer_id": 41960,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 7,
"selected": true,
"text": "<p>In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the <code>getTime()</code> method <strong>or</strong> just using the date in a numeric expression.</p>\n\n<p>So to get the difference, just subtract the two dates.</p>\n\n<p>To create a new date based on the difference, just pass the number of milliseconds in the constructor.</p>\n\n<pre><code>var oldBegin = ...\nvar oldEnd = ...\nvar newBegin = ...\n\nvar newEnd = new Date(newBegin + oldEnd - oldBegin);\n</code></pre>\n\n<p>This should just work</p>\n\n<p><strong>EDIT</strong>: Fixed bug pointed by @bdukes</p>\n\n<p><strong>EDIT</strong>: </p>\n\n<p>For an explanation of the behavior, <code>oldBegin</code>, <code>oldEnd</code>, and <code>newBegin</code> are <code>Date</code> instances. Calling operators <code>+</code> and <code>-</code> will trigger Javascript auto casting and will automatically call the <code>valueOf()</code> prototype method of those objects. It happens that the <code>valueOf()</code> method is implemented in the <code>Date</code> object as a call to <code>getTime()</code>.</p>\n\n<p>So basically: <code>date.getTime() === date.valueOf() === (0 + date) === (+date)</code></p>\n"
},
{
"answer_id": 41966,
"author": "Aaron",
"author_id": 2628,
"author_profile": "https://Stackoverflow.com/users/2628",
"pm_score": 0,
"selected": false,
"text": "<p>If you use Date objects and then use the <code>getTime()</code> function for both dates it will give you their respective times since Jan 1, 1970 in a number value. You can then get the difference between these numbers. </p>\n\n<p>If that doesn't help you out, check out the complete documentation: <a href=\"http://www.w3schools.com/jsref/jsref_obj_date.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/jsref/jsref_obj_date.asp</a></p>\n"
},
{
"answer_id": 41974,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't care about the time component, you can use <code>.getDate()</code> and <code>.setDate()</code> to just set the date part.</p>\n\n<p>So to set your end date to 2 weeks after your start date, do something like this:</p>\n\n<pre><code>function GetEndDate(startDate)\n{\n var endDate = new Date(startDate.getTime());\n endDate.setDate(endDate.getDate()+14);\n return endDate;\n}\n</code></pre>\n\n<p>To return the difference (in days) between two dates, do this:</p>\n\n<pre><code>function GetDateDiff(startDate, endDate)\n{\n return endDate.getDate() - startDate.getDate();\n}\n</code></pre>\n\n<p>Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:</p>\n\n<pre><code>function GetEndDate(startDate, days)\n{\n var endDate = new Date(startDate.getTime());\n endDate.setDate(endDate.getDate() + days);\n return endDate;\n}\n</code></pre>\n"
},
{
"answer_id": 42086,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks @<a href=\"https://stackoverflow.com/questions/41948/how-do-i-get-the-difference-between-two-dates-in-javascript#41960\">Vincent Robert</a>, I ended up using your basic example, though it's actually <code>newBegin + oldEnd - oldBegin</code>. Here's the simplified end solution:</p>\n\n<pre><code> // don't update end date if there's already an end date but not an old start date\n if (!oldEnd || oldBegin) {\n var selectedDateSpan = 1800000; // 30 minutes\n if (oldEnd) {\n selectedDateSpan = oldEnd - oldBegin;\n }\n\n newEnd = new Date(newBegin.getTime() + selectedDateSpan));\n }\n</code></pre>\n"
},
{
"answer_id": 5056705,
"author": "hiren gamit",
"author_id": 625179,
"author_profile": "https://Stackoverflow.com/users/625179",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function checkdate() {\n var indate = new Date()\n indate.setDate(dat)\n indate.setMonth(mon - 1)\n indate.setFullYear(year)\n\n var one_day = 1000 * 60 * 60 * 24\n var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))\n var str = diff + \" days are remaining..\"\n document.getElementById('print').innerHTML = str.fontcolor('blue')\n}\n</code></pre>\n"
},
{
"answer_id": 10409160,
"author": "shareef",
"author_id": 944593,
"author_profile": "https://Stackoverflow.com/users/944593",
"pm_score": 0,
"selected": false,
"text": "<p>this code fills the duration of study years when you input the start date and end date(qualify accured date) of study and check if the duration less than a year if yes the alert a message \ntake in mind there are three input elements the first <code>txtFromQualifDate</code> and second <code>txtQualifDate</code> and third <code>txtStudyYears</code></p>\n\n<p>it will show result of number of years with fraction</p>\n\n<pre><code>function getStudyYears()\n {\n if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')\n {\n var d1 = document.getElementById('txtFromQualifDate').value;\n\n var d2 = document.getElementById('txtQualifDate').value;\n\n var one_day=1000*60*60*24;\n\n var x = d1.split(\"/\");\n var y = d2.split(\"/\");\n\n var date1=new Date(x[2],(x[1]-1),x[0]);\n\n var date2=new Date(y[2],(y[1]-1),y[0])\n\n var dDays = (date2.getTime()-date1.getTime())/one_day;\n\n if(dDays < 365)\n {\n alert(\"the date between start study and graduate must not be less than a year !\");\n\n document.getElementById('txtQualifDate').value = \"\";\n document.getElementById('txtStudyYears').value = \"\";\n\n return ;\n }\n\n var dMonths = Math.ceil(dDays / 30);\n\n var dYears = Math.floor(dMonths /12) + \".\" + dMonths % 12;\n\n document.getElementById('txtStudyYears').value = dYears;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 10536394,
"author": "sparkyspider",
"author_id": 578318,
"author_profile": "https://Stackoverflow.com/users/578318",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.</p>\n\n<pre><code>// This one returns a signed decimal. The sign indicates past or future.\n\nthis.getDateDiff = function(date1, date2) {\n return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);\n}\n\n// This one always returns a positive decimal. (Suggested by Koen below)\n\nthis.getDateDiff = function(date1, date2) {\n return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));\n}\n</code></pre>\n"
},
{
"answer_id": 15810692,
"author": "Dan",
"author_id": 139361,
"author_profile": "https://Stackoverflow.com/users/139361",
"pm_score": 5,
"selected": false,
"text": "<p>JavaScript perfectly supports date difference out of the box</p>\n<p><a href=\"https://jsfiddle.net/b9chris/v5twbe3h/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/b9chris/v5twbe3h/</a></p>\n<pre><code>var msMinute = 60*1000, \n msDay = 60*60*24*1000,\n a = new Date(2012, 2, 12, 23, 59, 59),\n b = new Date("2013 march 12");\n\n\nconsole.log(Math.floor((b - a) / msDay) + ' full days between'); // 364\nconsole.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0\n</code></pre>\n<hr />\n<p>Now some pitfalls. Try this:</p>\n<pre><code>console.log(a - 10); // 1331614798990\nconsole.log(a + 10); // mixed string\n</code></pre>\n<p>So if you have risk of adding a number and Date, convert Date to <code>number</code> directly.</p>\n<pre><code>console.log(a.getTime() - 10); // 1331614798990\nconsole.log(a.getTime() + 10); // 1331614799010\n</code></pre>\n<p>My fist example demonstrates the power of Date object but it actually appears to be a time bomb</p>\n"
},
{
"answer_id": 20002054,
"author": "dheerendra",
"author_id": 2927163,
"author_profile": "https://Stackoverflow.com/users/2927163",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function compare()\n{\n var end_actual_time = $('#date3').val();\n\n start_actual_time = new Date();\n end_actual_time = new Date(end_actual_time);\n\n var diff = end_actual_time-start_actual_time;\n\n var diffSeconds = diff/1000;\n var HH = Math.floor(diffSeconds/3600);\n var MM = Math.floor(diffSeconds%3600)/60;\n\n var formatted = ((HH < 10)?(\"0\" + HH):HH) + \":\" + ((MM < 10)?(\"0\" + MM):MM)\n getTime(diffSeconds);\n}\nfunction getTime(seconds) {\n var days = Math.floor(leftover / 86400);\n\n //how many seconds are left\n leftover = leftover - (days * 86400);\n\n //how many full hours fits in the amount of leftover seconds\n var hours = Math.floor(leftover / 3600);\n\n //how many seconds are left\n leftover = leftover - (hours * 3600);\n\n //how many minutes fits in the amount of leftover seconds\n var minutes = leftover / 60;\n\n //how many seconds are left\n //leftover = leftover - (minutes * 60);\n alert(days + ':' + hours + ':' + minutes);\n}\n</code></pre>\n"
},
{
"answer_id": 25042075,
"author": "tika",
"author_id": 2988919,
"author_profile": "https://Stackoverflow.com/users/2988919",
"pm_score": 3,
"selected": false,
"text": "<p><strong><em><a href=\"http://jsfiddle.net/vvGPQ/1/\" rel=\"noreferrer\">See JsFiddle DEMO</a></em></strong></p>\n\n<pre><code> var date1 = new Date(); \n var date2 = new Date(\"2025/07/30 21:59:00\");\n //Customise date2 for your required future time\n\n showDiff();\n\nfunction showDiff(date1, date2){\n\n var diff = (date2 - date1)/1000;\n diff = Math.abs(Math.floor(diff));\n\n var days = Math.floor(diff/(24*60*60));\n var leftSec = diff - days * 24*60*60;\n\n var hrs = Math.floor(leftSec/(60*60));\n var leftSec = leftSec - hrs * 60*60;\n\n var min = Math.floor(leftSec/(60));\n var leftSec = leftSec - min * 60;\n\n document.getElementById(\"showTime\").innerHTML = \"You have \" + days + \" days \" + hrs + \" hours \" + min + \" minutes and \" + leftSec + \" seconds before death.\";\n\nsetTimeout(showDiff,1000);\n}\n</code></pre>\n\n<p>for your HTML Code:</p>\n\n<pre><code><div id=\"showTime\"></div>\n</code></pre>\n"
},
{
"answer_id": 28616175,
"author": "NovaYear",
"author_id": 556986,
"author_profile": "https://Stackoverflow.com/users/556986",
"pm_score": 1,
"selected": false,
"text": "<p>alternative modificitaion extended code..</p>\n\n<p><a href=\"http://jsfiddle.net/vvGPQ/48/\" rel=\"nofollow\">http://jsfiddle.net/vvGPQ/48/</a></p>\n\n<pre><code>showDiff();\n\nfunction showDiff(){\nvar date1 = new Date(\"2013/01/18 06:59:00\"); \nvar date2 = new Date();\n//Customise date2 for your required future time\n\nvar diff = (date2 - date1)/1000;\nvar diff = Math.abs(Math.floor(diff));\n\nvar years = Math.floor(diff/(365*24*60*60));\nvar leftSec = diff - years * 365*24*60*60;\n\nvar month = Math.floor(leftSec/((365/12)*24*60*60));\nvar leftSec = leftSec - month * (365/12)*24*60*60; \n\nvar days = Math.floor(leftSec/(24*60*60));\nvar leftSec = leftSec - days * 24*60*60;\n\nvar hrs = Math.floor(leftSec/(60*60));\nvar leftSec = leftSec - hrs * 60*60;\n\nvar min = Math.floor(leftSec/(60));\nvar leftSec = leftSec - min * 60;\n\n\n\n\ndocument.getElementById(\"showTime\").innerHTML = \"You have \" + years + \" years \"+ month + \" month \" + days + \" days \" + hrs + \" hours \" + min + \" minutes and \" + leftSec + \" seconds the life time has passed.\";\n\nsetTimeout(showDiff,1000);\n}\n</code></pre>\n"
},
{
"answer_id": 34782685,
"author": "Sukanya Suku",
"author_id": 5681934,
"author_profile": "https://Stackoverflow.com/users/5681934",
"pm_score": 0,
"selected": false,
"text": "<pre><code><html>\n<head>\n<script>\nfunction dayDiff()\n{\n var start = document.getElementById(\"datepicker\").value;\n var end= document.getElementById(\"date_picker\").value;\n var oneDay = 24*60*60*1000; \n var firstDate = new Date(start);\n var secondDate = new Date(end); \n var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));\n document.getElementById(\"leave\").value =diffDays ;\n }\n</script>\n</head>\n<body>\n<input type=\"text\" name=\"datepicker\"value=\"\"/>\n<input type=\"text\" name=\"date_picker\" onclick=\"function dayDiff()\" value=\"\"/>\n<input type=\"text\" name=\"leave\" value=\"\"/>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 37532797,
"author": "Miguel Guardo",
"author_id": 5739841,
"author_profile": "https://Stackoverflow.com/users/5739841",
"pm_score": 2,
"selected": false,
"text": "<p>If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.</p>\n\n<pre><code>moment(endDate).diff(moment(beginDate), 'days');\n</code></pre>\n\n<p>Additional details can be found in the <a href=\"http://momentjs.com/docs/#/displaying/difference/\" rel=\"nofollow\">moment.js page</a></p>\n\n<p>Cheers,\nMiguel</p>\n"
},
{
"answer_id": 49576078,
"author": "Vin S",
"author_id": 9573544,
"author_profile": "https://Stackoverflow.com/users/9573544",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Below code will return the days left from today to futures date.</strong></p>\n\n<p>Dependencies: <strong>jQuery and MomentJs.</strong></p>\n\n<pre><code>var getDaysLeft = function (date) {\n var today = new Date();\n var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));\n var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24); \n return daysLeft;\n};\n\ngetDaysLeft('YYYY-MM-DD');\n</code></pre>\n"
},
{
"answer_id": 50414819,
"author": "Vin S",
"author_id": 9573544,
"author_profile": "https://Stackoverflow.com/users/9573544",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var getDaysLeft = function (date1, date2) {\n var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));\n var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24); \n return daysLeft;\n};\nvar date1='2018-05-18';\nvar date2='2018-05-25';\nvar dateDiff = getDaysLeft(date1, date2);\nconsole.log(dateDiff);\n</code></pre>\n"
},
{
"answer_id": 50508313,
"author": "Sean Cortez",
"author_id": 8750004,
"author_profile": "https://Stackoverflow.com/users/8750004",
"pm_score": -1,
"selected": false,
"text": "<p>THIS IS WHAT I DID ON MY SYSTEM. </p>\n\n<pre><code>var startTime=(\"08:00:00\").split(\":\");\nvar endTime=(\"16:00:00\").split(\":\");\nvar HoursInMinutes=((parseInt(endTime[0])*60)+parseInt(endTime[1]))-((parseInt(startTime[0])*60)+parseInt(startTime[1]));\nconsole.log(HoursInMinutes/60);\n</code></pre>\n"
},
{
"answer_id": 72967699,
"author": "Liam Pillay",
"author_id": 11404295,
"author_profile": "https://Stackoverflow.com/users/11404295",
"pm_score": 0,
"selected": false,
"text": "<p>To get the date difference in milliseconds between two dates:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var diff = Math.abs(date1 - date2);\n</code></pre>\n<p>I'm not sure what you mean by converting the difference back into a date though.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688/"
] | I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference. | In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the `getTime()` method **or** just using the date in a numeric expression.
So to get the difference, just subtract the two dates.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
```
var oldBegin = ...
var oldEnd = ...
var newBegin = ...
var newEnd = new Date(newBegin + oldEnd - oldBegin);
```
This should just work
**EDIT**: Fixed bug pointed by @bdukes
**EDIT**:
For an explanation of the behavior, `oldBegin`, `oldEnd`, and `newBegin` are `Date` instances. Calling operators `+` and `-` will trigger Javascript auto casting and will automatically call the `valueOf()` prototype method of those objects. It happens that the `valueOf()` method is implemented in the `Date` object as a call to `getTime()`.
So basically: `date.getTime() === date.valueOf() === (0 + date) === (+date)` |
41,969 | <p>I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.</p>
<p>On OSX, I can open a window in the finder with</p>
<pre><code>os.system('open "%s"' % foldername)
</code></pre>
<p>and on Windows with</p>
<pre><code>os.startfile(foldername)
</code></pre>
<p>What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?</p>
<p>This looks like something that could be specified by the <a href="http://freedesktop.org" rel="noreferrer">freedesktop.org</a> folks (a python module, similar to <code>webbrowser</code>, would also be nice!).</p>
| [
{
"answer_id": 41999,
"author": "Tanj",
"author_id": 4275,
"author_profile": "https://Stackoverflow.com/users/4275",
"pm_score": 0,
"selected": false,
"text": "<p>this would probably have to be done manually, or have as a config item since there are many file managers that users may want to use. Providing a way for command options as well.</p>\n\n<p>There might be an function that launches the defaults for kde or gnome in their respective toolkits but I haven't had reason to look for them.</p>\n"
},
{
"answer_id": 42039,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 0,
"selected": false,
"text": "<p>You're going to have to do this based on the running window manager. OSX and Windows have a (defacto) standard way because there is only one choice.</p>\n\n<p>You shouldn't need to specify the exact filemanager application, though, this should be possible to do through the wm. I know Gnome does, and it's important to do this in KDE since there are two possible file managers (Konqueror/Dolphin) that may be in use.</p>\n\n<p>I agree that this would be a good thing for freedesktop.org to standardize, although I doubt it will happen unless someone steps up and volunteers to do it.</p>\n\n<hr>\n\n<p>EDIT: I wasn't aware of xdg-open. Good to know!</p>\n"
},
{
"answer_id": 42046,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 5,
"selected": true,
"text": "<pre><code>os.system('xdg-open \"%s\"' % foldername)\n</code></pre>\n\n<p><code>xdg-open</code> can be used for files/urls also</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002/"
] | I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.
On OSX, I can open a window in the finder with
```
os.system('open "%s"' % foldername)
```
and on Windows with
```
os.startfile(foldername)
```
What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?
This looks like something that could be specified by the [freedesktop.org](http://freedesktop.org) folks (a python module, similar to `webbrowser`, would also be nice!). | ```
os.system('xdg-open "%s"' % foldername)
```
`xdg-open` can be used for files/urls also |
42,017 | <p>I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net. Does anybody has experience with this?</p>
| [
{
"answer_id": 42058,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I like <a href=\"http://www.atalasoft.com/products/dotimage/photo/default.aspx\" rel=\"nofollow noreferrer\">Atalasoft's DotImage Photo</a>, but its a closed source solution and costs about 600 per dev license. </p>\n\n<p>You can also check out <a href=\"http://www.codeplex.com/DTools\" rel=\"nofollow noreferrer\">DTools at Codeplex</a>, which is an open source framework designed to supplement the standard Fx. It includes some Exif related classes.</p>\n"
},
{
"answer_id": 42084,
"author": "MikeScott8",
"author_id": 1889,
"author_profile": "https://Stackoverflow.com/users/1889",
"pm_score": 2,
"selected": false,
"text": "<p>the one I have saved in feeddemon for me to check out more when I have time (when is that for a programmer? LOL) is below</p>\n\n<p><a href=\"http://www.codeproject.com/KB/graphics/exiftagcol.aspx\" rel=\"nofollow noreferrer\" title=\"The Code Project\">ExifTagCollection - EXIF Metadata extraction library</a></p>\n\n<p>Mike</p>\n"
},
{
"answer_id": 156621,
"author": "Dave Griffiths",
"author_id": 15379,
"author_profile": "https://Stackoverflow.com/users/15379",
"pm_score": 2,
"selected": false,
"text": "<p>Check out this <a href=\"http://www.drewnoakes.com/code/exif/\" rel=\"nofollow noreferrer\">metadata extractor</a>. It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.</p>\n"
},
{
"answer_id": 2510863,
"author": "richardtallent",
"author_id": 16306,
"author_profile": "https://Stackoverflow.com/users/16306",
"pm_score": 0,
"selected": false,
"text": "<p>Several years ago, I started a little JPEG EXIF app with Omar Shahine to work on JPEG EXIF files, called JpegHammer.</p>\n\n<p>He extracted from that project a library and called it PhotoLibrary, it was an easy .NET wrapper for the EXIF 2.2 tags. Unfortunately, the GotDotNet site is gone, CodePlex doesn't have it, Omar's web site links don't work, and I don't have a copy anymore.</p>\n\n<p>But, if you can dig around Google, maybe you'll find it and it'll do the trick for you.</p>\n"
},
{
"answer_id": 2707506,
"author": "Rowland Shaw",
"author_id": 50447,
"author_profile": "https://Stackoverflow.com/users/50447",
"pm_score": 3,
"selected": false,
"text": "<p>If you're compiling against v3 of the Framework (or later), then you can load the images using the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx\" rel=\"noreferrer\"><code>BitmapSource</code> class</a>, which exposes the EXIF metadata through the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.metadata.aspx\" rel=\"noreferrer\"><code>Metadata</code> property</a></p>\n"
},
{
"answer_id": 8588615,
"author": "David Pierson",
"author_id": 1109677,
"author_profile": "https://Stackoverflow.com/users/1109677",
"pm_score": 3,
"selected": false,
"text": "<p>A new and very fast library is <a href=\"http://www.codeproject.com/KB/graphics/exiflib.aspx\">ExifLib - A Fast Exif Data Extractor for .NET 2.0</a> by Simon McKenzie. I ended up using this one and the code is easy to use and understand. I used it for an app to rename according to the date taken. I wonder how many times such an app has been written.</p>\n\n<p>My tip: Make sure to call Dispose on the ExifReader objects once you've finished with them or the files remain open. </p>\n"
},
{
"answer_id": 31329551,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 4,
"selected": false,
"text": "<p>If you're willing to use an open-source library, may I humbly suggest one of my own creation?</p>\n\n<p>The <em>metadata-extractor</em> project has been alive and well since 2002 for Java, and is now available for .NET.</p>\n\n<ul>\n<li>Open source (Apache 2.0)</li>\n<li>Heavily tested and widely used</li>\n<li>Supports many image types (JPEG, TIFF, PNG, WebP, GIF, BMP, ICO, PCX...)</li>\n<li>Supports many metadata types (Exif, IPTC, XMP, JFIF, ...)</li>\n<li>Supports many manufacturer-specific fields (Canon, Nikon, ...)</li>\n<li>Very fast (fully processes ~400 images totalling 1.33GB in ~3 seconds) with low memory consumption</li>\n<li>Builds for .NET 3.5, .NET 4.0+ and PCL</li>\n</ul>\n\n<p>It's available via <a href=\"https://www.nuget.org/packages/MetadataExtractor/\" rel=\"noreferrer\">NuGet</a> or <a href=\"https://github.com/drewnoakes/metadata-extractor-dotnet\" rel=\"noreferrer\">GitHub</a>.</p>\n\n<p>Sample usage:</p>\n\n<pre><code>IEnumerable<Directory> directories = ImageMetadataReader.ReadMetadata(path);\n\nforeach (var directory in directories)\nforeach (var tag in directory.Tags)\n Console.WriteLine($\"{directory.Name} - {tag.TagName} = {tag.Description}\");\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] | I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net. Does anybody has experience with this? | If you're willing to use an open-source library, may I humbly suggest one of my own creation?
The *metadata-extractor* project has been alive and well since 2002 for Java, and is now available for .NET.
* Open source (Apache 2.0)
* Heavily tested and widely used
* Supports many image types (JPEG, TIFF, PNG, WebP, GIF, BMP, ICO, PCX...)
* Supports many metadata types (Exif, IPTC, XMP, JFIF, ...)
* Supports many manufacturer-specific fields (Canon, Nikon, ...)
* Very fast (fully processes ~400 images totalling 1.33GB in ~3 seconds) with low memory consumption
* Builds for .NET 3.5, .NET 4.0+ and PCL
It's available via [NuGet](https://www.nuget.org/packages/MetadataExtractor/) or [GitHub](https://github.com/drewnoakes/metadata-extractor-dotnet).
Sample usage:
```
IEnumerable<Directory> directories = ImageMetadataReader.ReadMetadata(path);
foreach (var directory in directories)
foreach (var tag in directory.Tags)
Console.WriteLine($"{directory.Name} - {tag.TagName} = {tag.Description}");
``` |
42,068 | <p>I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:</p>
<pre><code>var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');
</code></pre>
<p>This gives me an error: </p>
<pre><code>unterminated string literal
</code></pre>
<p>With <code>JSON.parse(data)</code>, I see similar error messages: "<code>Unexpected token ↵</code>" in Chrome, and "<code>unterminated string literal</code>" in Firefox and IE.</p>
<p>When I take out the <code>\n</code> after <code>sometext</code> the error goes away in both cases. I can't seem to figure out why the <code>\n</code> makes <code>eval</code> and <code>JSON.parse</code> fail. </p>
| [
{
"answer_id": 42073,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 10,
"selected": true,
"text": "<p>This is what you want:</p>\n<pre><code>var data = '{"count" : 1, "stack" : "sometext\\\\n\\\\n"}';\n</code></pre>\n<p>You need to escape the <code>\\</code> in your string (turning it into a double-<code>\\</code>), otherwise it will become a newline in the JSON source, not the JSON data.</p>\n"
},
{
"answer_id": 1111538,
"author": "Ron",
"author_id": 2293628,
"author_profile": "https://Stackoverflow.com/users/2293628",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to look into this C# function to escape the string:</p>\n\n<p><a href=\"http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx\" rel=\"nofollow noreferrer\">http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx</a></p>\n\n<pre><code>public static string Enquote(string s) \n{ \n if (s == null || s.Length == 0) \n { \n return \"\\\"\\\"\"; \n } \n char c; \n int i; \n int len = s.Length; \n StringBuilder sb = new StringBuilder(len + 4); \n string t; \n\n sb.Append('\"'); \n for (i = 0; i < len; i += 1) \n { \n c = s[i]; \n if ((c == '\\\\') || (c == '\"') || (c == '>')) \n { \n sb.Append('\\\\'); \n sb.Append(c); \n } \n else if (c == '\\b') \n sb.Append(\"\\\\b\"); \n else if (c == '\\t') \n sb.Append(\"\\\\t\"); \n else if (c == '\\n') \n sb.Append(\"\\\\n\"); \n else if (c == '\\f') \n sb.Append(\"\\\\f\"); \n else if (c == '\\r') \n sb.Append(\"\\\\r\"); \n else \n { \n if (c < ' ') \n { \n //t = \"000\" + Integer.toHexString(c); \n string t = new string(c,1); \n t = \"000\" + int.Parse(tmp,System.Globalization.NumberStyles.HexNumber); \n sb.Append(\"\\\\u\" + t.Substring(t.Length - 4)); \n } \n else \n { \n sb.Append(c); \n } \n } \n } \n sb.Append('\"'); \n return sb.ToString(); \n} \n</code></pre>\n"
},
{
"answer_id": 5191059,
"author": "Manish Singh",
"author_id": 518493,
"author_profile": "https://Stackoverflow.com/users/518493",
"pm_score": 6,
"selected": false,
"text": "<p>You will need to have a function which replaces <code>\\n</code> to <code>\\\\n</code> in case <code>data</code> is not a string literal.</p>\n\n<pre><code>function jsonEscape(str) {\n return str.replace(/\\n/g, \"\\\\\\\\n\").replace(/\\r/g, \"\\\\\\\\r\").replace(/\\t/g, \"\\\\\\\\t\");\n}\n\nvar data = '{\"count\" : 1, \"stack\" : \"sometext\\n\\n\"}';\nvar dataObj = JSON.parse(jsonEscape(data));\n</code></pre>\n\n<p>Resulting <code>dataObj</code> will be</p>\n\n<pre><code>Object {count: 1, stack: \"sometext\\n\\n\"}\n</code></pre>\n"
},
{
"answer_id": 6156153,
"author": "GabrielP",
"author_id": 773563,
"author_profile": "https://Stackoverflow.com/users/773563",
"pm_score": -1,
"selected": false,
"text": "<p>I encountered that problem while making a class in PHP 4 to emulate json_encode (available in PHP 5). Here's what I came up with:</p>\n\n<pre><code>class jsonResponse {\n var $response;\n\n function jsonResponse() {\n $this->response = array('isOK'=>'KO', 'msg'=>'Undefined');\n }\n\n function set($isOK, $msg) {\n $this->response['isOK'] = ($isOK) ? 'OK' : 'KO';\n $this->response['msg'] = htmlentities($msg);\n }\n\n function setData($data=null) {\n if(!is_null($data))\n $this->response['data'] = $data;\n elseif(isset($this->response['data']))\n unset($this->response['data']);\n }\n\n function send() {\n header('Content-type: application/json');\n echo '{\"isOK\":\"' . $this->response['isOK'] . '\",\"msg\":' . $this->parseString($this->response['msg']);\n if(isset($this->response['data']))\n echo ',\"data\":' . $this->parseData($this->response['data']);\n echo '}';\n }\n\n function parseData($data) {\n if(is_array($data)) {\n $parsed = array();\n foreach ($data as $key=>$value)\n array_push($parsed, $this->parseString($key) . ':' . $this->parseData($value));\n return '{' . implode(',', $parsed) . '}';\n }\n else\n return $this->parseString($data);\n }\n\n function parseString($string) {\n $string = str_replace(\"\\\\\", \"\\\\\\\\\", $string);\n $string = str_replace('/', \"\\\\/\", $string);\n $string = str_replace('\"', \"\\\\\".'\"', $string);\n $string = str_replace(\"\\b\", \"\\\\b\", $string);\n $string = str_replace(\"\\t\", \"\\\\t\", $string);\n $string = str_replace(\"\\n\", \"\\\\n\", $string);\n $string = str_replace(\"\\f\", \"\\\\f\", $string);\n $string = str_replace(\"\\r\", \"\\\\r\", $string);\n $string = str_replace(\"\\u\", \"\\\\u\", $string);\n return '\"'.$string.'\"';\n }\n}\n</code></pre>\n\n<p>I followed the rules mentioned <a href=\"http://www.json.org/fatfree.html\" rel=\"nofollow noreferrer\">here</a>. I only used what I needed, but I figure that you can adapt it to your needs in the language your are using. The problem in my case wasn't about newlines as I originally thought, but about the / not being escaped. I hope this prevent someone else from the little headache I had figuring out what I did wrong.</p>\n"
},
{
"answer_id": 13493212,
"author": "ShivarajRH",
"author_id": 903527,
"author_profile": "https://Stackoverflow.com/users/903527",
"pm_score": 0,
"selected": false,
"text": "<p>I used this function to strip newline or other characters in data to parse JSON data:</p>\n\n<pre><code>function normalize_str($str) {\n\n $invalid = array(\n 'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z',\n 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A',\n 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E',\n 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',\n 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y',\n 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a',\n 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i',\n 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',\n 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',\n 'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',\n \"`\" => \"'\", \"´\" => \"'\", '\"' => ',', '`' => \"'\",\n '´' => \"'\", '\"' => '\\\"', '\"' => \"\\\"\", '´' => \"'\",\n \"&acirc;€™\" => \"'\",\n \"{\" => \"\",\n \"~\" => \"\", \"–\" => \"-\", \"'\" => \"'\", \" \" => \" \");\n\n $str = str_replace(array_keys($invalid), array_values($invalid), $str);\n\n $remove = array(\"\\n\", \"\\r\\n\", \"\\r\");\n $str = str_replace($remove, \"\\\\n\", trim($str));\n\n //$str = htmlentities($str, ENT_QUOTES);\n\n return htmlspecialchars($str);\n}\n\necho normalize_str($lst['address']);\n</code></pre>\n"
},
{
"answer_id": 16700486,
"author": "Victor_Magalhaes",
"author_id": 751147,
"author_profile": "https://Stackoverflow.com/users/751147",
"pm_score": 2,
"selected": false,
"text": "<p>You could just escape your string on the server when writing the value of the JSON field and unescape it when retrieving the value in the client browser, for instance.</p>\n\n<p>The JavaScript implementation of all major browsers have the unescape command.</p>\n\n<p>Example:</p>\n\n<p>On the server:</p>\n\n<pre><code>response.write \"{\"\"field1\"\":\"\"\" & escape(RS_Temp(\"textField\")) & \"\"\"}\"\n</code></pre>\n\n<p>In the browser: </p>\n\n<pre><code>document.getElementById(\"text1\").value = unescape(jsonObject.field1)\n</code></pre>\n"
},
{
"answer_id": 42899451,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 4,
"selected": false,
"text": "<p>According to the specification, <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf\" rel=\"noreferrer\">http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf</a>:</p>\n\n<blockquote>\n <p>A string is a sequence of Unicode code points wrapped with quotation marks\n (<code>U+0022</code>). All characters may be placed within the quotation marks except for the\n characters that must be escaped: quotation mark (<code>U+0022</code>), reverse solidus\n (<code>U+005C</code>), and the control characters <code>U+0000</code> to <code>U+001F</code>. There are two-character\n escape sequence representations of some characters.</p>\n</blockquote>\n\n<p>So you can't pass <code>0x0A</code> or <code>0x0C</code> codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from <code>U+0000</code> to <code>U+001F</code>:</p>\n\n<ul>\n<li><code>\\f</code> represents the form feed character (<code>U+000C</code>).</li>\n<li><code>\\n</code> represents the line feed character (<code>U+000A</code>).</li>\n</ul>\n\n<p>As most of programming languages uses <code>\\</code> for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):</p>\n\n<pre><code>jsonStr = \"{ \\\"name\\\": \\\"Multi\\\\nline.\\\" }\";\n</code></pre>\n"
},
{
"answer_id": 55850752,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": -1,
"selected": false,
"text": "<p>As I understand you question, it is not about parsing JSON because you can copy-paste your JSON into your code directly - so if this is the case then just copy your JSON direct to <code>dataObj</code> variable without wrapping it with single quotes (tip: <code>eval==evil</code>) </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>var dataObj = {\"count\" : 1, \"stack\" : \"sometext\\n\\n\"};\r\n\r\nconsole.log(dataObj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 63137400,
"author": "jerryurenaa",
"author_id": 11611288,
"author_profile": "https://Stackoverflow.com/users/11611288",
"pm_score": 2,
"selected": false,
"text": "<p>well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.</p>\n<p>just wrap your text around this class and see the magic :D</p>\n<pre><code> <p style={{whiteSpace: 'pre-line'}}>my json text goes here \\n\\n</p>\n</code></pre>\n<p>note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.</p>\n"
},
{
"answer_id": 66531090,
"author": "Marinos An",
"author_id": 1555615,
"author_profile": "https://Stackoverflow.com/users/1555615",
"pm_score": 5,
"selected": false,
"text": "<p><strong>TLDR: A solution to the author's problem.</strong></p>\n<p><strong>Use <code>String.raw</code> literal:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>var data = String.raw`{"count" : 1, "stack" : "sometext\\n\\n"}`;\n</code></pre>\n<hr />\n<p>For some reason all answers inside here focus on how to parse a JSON string representation in JavaScript, which may cause confusion regarding how to represent newlines on actual JSON. The latter is not language-dependent.</p>\n<p><strong>Strictly based on the question title :</strong></p>\n<h2>How do I handle newlines in JSON?</h2>\n<p>Let's say you parse a JSON file using the following code in <code>node</code> (it could be any language though):</p>\n<pre class=\"lang-js prettyprint-override\"><code>\nlet obj = JSON.parse(fs.readFileSync('file.json'));\nconsole.log(obj.mykey)\n</code></pre>\n<p>Below is the output for each of the possible contents of <code>file.json</code>:</p>\n<p><strong>Input 1:</strong></p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n "mykey": "my multiline\n value"\n}\n</code></pre>\n<p><strong>Output 1:</strong></p>\n<pre><code>SyntaxError: Unexpected token\n</code></pre>\n<p><strong>Input 2:</strong></p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n "mykey": "my multiline\\nvalue"\n}\n</code></pre>\n<p><strong>Output 2:</strong></p>\n<pre><code>my multiline\nvalue\n</code></pre>\n<p><strong>Input 3:</strong></p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n "mykey": "my multiline\\\\nvalue"\n}\n</code></pre>\n<p><strong>Output 3:</strong></p>\n<pre><code>my multiline\\nvalue\n</code></pre>\n<h3>Conclusion 1:</h3>\n<p><strong>To represent a newline inside a <code>json</code> file we should use the <code>\\n</code> character</strong>. To represent the <code>\\n</code> we should use <code>\\\\n</code>.</p>\n<hr />\n<h2>How would we define each of the above inputs using JavaScript (instead of input file):</h2>\n<p>When we need to define a string containing JSON in JavaScript, things change a bit because of the special meaning that <code>\\n</code> has also for JavaScript. <strong>But also notice how <code>String.raw</code> literal fixes this</strong>.</p>\n<p><strong>Input1:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>let input1 = '{"mykey": "my multiline\\nvalue"}'\n\n//OR\nlet input1 = `{\n "mykey": "my multiline\n value"\n}`;\n//(or even)\nlet input1 = `{\n "mykey": "my multiline\\nvalue"\n}`;\n\n//OR\nlet input1 = String.raw`{\n "mykey": "my multiline\n value"\n}`;\n\nconsole.log(JSON.parse(input1).mykey);\n\n//SyntaxError: Unexpected token\n//in JSON at position [..]\n</code></pre>\n<p><strong>Input 2:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>let input2 = '{"mykey": "my multiline\\\\nvalue"}'\n\n//OR\nlet input2 = `{\n "mykey": "my multiline\\\\nvalue"\n}`;\n\n//OR (Notice the difference from default literal)\nlet input2 = String.raw`{\n "mykey": "my multiline\\nvalue"\n}`;\n\nconsole.log(JSON.parse(input2).mykey);\n\n//my multiline\n//value\n\n</code></pre>\n<p><strong>Input 3</strong>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let input3 = '{"mykey": "my multiline\\\\\\\\nvalue"}'\n\n//OR\nlet input3 = `{\n "mykey": "my multiline\\\\\\\\nvalue"\n}`;\n\n//OR (Notice the difference from default literal)\nlet input3 = String.raw`{\n "mykey": "my multiline\\\\nvalue"\n}`;\n\nconsole.log(JSON.parse(input3).mykey);\n\n//my multiline\\nvalue\n</code></pre>\n<h3>Conclusion 2:</h3>\n<p>To define a <code>json</code> string in javascript the <strong>easiest way would be to use <code>String.raw</code></strong>, because it does not require any escaping (Well apart from backtick which is escaped like this <code>String.raw`abc${"`"}def` </code> ).</p>\n<p>Of course, the easiest way to create <code>json</code> in javascript, in general, is to convert a javascript object to json (using <code>JSON.stringify</code>).</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3636/"
] | I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:
```
var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');
```
This gives me an error:
```
unterminated string literal
```
With `JSON.parse(data)`, I see similar error messages: "`Unexpected token ↵`" in Chrome, and "`unterminated string literal`" in Firefox and IE.
When I take out the `\n` after `sometext` the error goes away in both cases. I can't seem to figure out why the `\n` makes `eval` and `JSON.parse` fail. | This is what you want:
```
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
```
You need to escape the `\` in your string (turning it into a double-`\`), otherwise it will become a newline in the JSON source, not the JSON data. |
42,070 | <p>What's going on here?</p>
<p>printf.sh:</p>
<pre><code>#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" $NAME
</code></pre>
<p>Command line session:</p>
<pre><code>$ ./printf.sh
Hello, George
Hello, W.
Hello, Bush
</code></pre>
<p>UPDATE: <code>printf "Hello, %s\n" "$NAME"</code> works. For why I'm not using <code>echo</code>, consider</p>
<p>echo.sh:</p>
<pre><code>#! /bin/sh
FILE="C:\tmp"
echo "Filename: $FILE"
</code></pre>
<p>Command-line:</p>
<pre><code>$ ./echo.sh
Filename: C: mp
</code></pre>
<p>The <a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="noreferrer">POSIX spec for <code>echo</code></a> says, "New applications are encouraged to use <code>printf</code> instead of <code>echo</code>" (for this and other reasons). </p>
| [
{
"answer_id": 42087,
"author": "Redbaron",
"author_id": 41,
"author_profile": "https://Stackoverflow.com/users/41",
"pm_score": 0,
"selected": false,
"text": "<p>If you want all of those words to be printed out on their own, use <strong>print</strong> instead of <strong>printf</strong> </p>\n\n<p><strong>printf</strong> takes the formatting specification and applies it to each argument that you pass in. Since you have three arguments {George, W., Bush}, it outputs the string three times using the different arguments.</p>\n"
},
{
"answer_id": 42089,
"author": "Tanj",
"author_id": 4275,
"author_profile": "https://Stackoverflow.com/users/4275",
"pm_score": 1,
"selected": false,
"text": "<p>is there a specific reason you are using printf or would echo work for you as well?</p>\n\n<pre><code>NAME=\"George W. Bush\"\necho \"Hello, \"$NAME\n</code></pre>\n\n<p>results in </p>\n\n<pre><code>Hello, George W. Bush\n</code></pre>\n\n<p>edit:\nThe reason it is iterating over \"George W. Bush\" is because the bourne shell is space delimitted. To keep using printf you have to put $NAME in double quotes</p>\n\n<pre><code>printf \"Hello, %s\\n\" \"$NAME\"\n</code></pre>\n"
},
{
"answer_id": 42092,
"author": "ColinYounger",
"author_id": 1223,
"author_profile": "https://Stackoverflow.com/users/1223",
"pm_score": 4,
"selected": true,
"text": "<p>Your NAME variable is being substituted like this:</p>\n\n<pre><code>printf \"Hello, %s\\n\" George W. Bush\n</code></pre>\n\n<p>Use this:</p>\n\n<pre><code>#! /bin/sh\nNAME=\"George W. Bush\"\nprintf \"Hello, %s\\n\" \"$NAME\"\n</code></pre>\n"
},
{
"answer_id": 42103,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 1,
"selected": false,
"text": "<p>The way I interpret the <a href=\"http://www.ss64.com/bash/printf.html\" rel=\"nofollow noreferrer\">man page</a> is it considers the string you pass it to be an argument; if your string has spaces it thinks you are passing multiple arguments. I believe ColinYounger is correct by surrounding the variable with quotes, which forces the shell to interpret the string as a single argument.</p>\n\n<p>An alternative might be to let printf expand the variable:</p>\n\n<pre><code>printf \"Hello, $NAME.\"\n</code></pre>\n\n<p>The links are for bash, but I am pretty sure the same holds for sh.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | What's going on here?
printf.sh:
```
#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" $NAME
```
Command line session:
```
$ ./printf.sh
Hello, George
Hello, W.
Hello, Bush
```
UPDATE: `printf "Hello, %s\n" "$NAME"` works. For why I'm not using `echo`, consider
echo.sh:
```
#! /bin/sh
FILE="C:\tmp"
echo "Filename: $FILE"
```
Command-line:
```
$ ./echo.sh
Filename: C: mp
```
The [POSIX spec for `echo`](http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html) says, "New applications are encouraged to use `printf` instead of `echo`" (for this and other reasons). | Your NAME variable is being substituted like this:
```
printf "Hello, %s\n" George W. Bush
```
Use this:
```
#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" "$NAME"
``` |
42,102 | <p>I have a Singleton/Factory object that I'd like to write a JUnit test for. The Factory method decides which implementing class to instantiate based upon a classname in a properties file on the classpath. If no properties file is found, or the properties file does not contain the classname key, then the class will instantiate a default implementing class.</p>
<p>Since the factory keeps a static instance of the Singleton to use once it has been instantiated, to be able to test the "failover" logic in the Factory method I would need to run each test method in a different classloader. </p>
<p>Is there any way with JUnit (or with another unit testing package) to do this?</p>
<p>edit: here is some of the Factory code that is in use:</p>
<pre><code>private static MyClass myClassImpl = instantiateMyClass();
private static MyClass instantiateMyClass() {
MyClass newMyClass = null;
String className = null;
try {
Properties props = getProperties();
className = props.getProperty(PROPERTY_CLASSNAME_KEY);
if (className == null) {
log.warn("instantiateMyClass: Property [" + PROPERTY_CLASSNAME_KEY
+ "] not found in properties, using default MyClass class [" + DEFAULT_CLASSNAME + "]");
className = DEFAULT_CLASSNAME;
}
Class MyClassClass = Class.forName(className);
Object MyClassObj = MyClassClass.newInstance();
if (MyClassObj instanceof MyClass) {
newMyClass = (MyClass) MyClassObj;
}
}
catch (...) {
...
}
return newMyClass;
}
private static Properties getProperties() throws IOException {
Properties props = new Properties();
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
if (stream != null) {
props.load(stream);
}
else {
log.error("getProperties: could not load properties file [" + PROPERTIES_FILENAME + "] from classpath, file not found");
}
return props;
}
</code></pre>
| [
{
"answer_id": 42108,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>When I run into these sort of situations I prefer to use what is a bit of a hack. I might instead expose a protected method such as reinitialize(), then invoke this from the test to effectively set the factory back to its initial state. This method only exists for the test cases, and I document it as such.</p>\n\n<p>It is a bit of a hack, but it's a lot easier than other options and you won't need a 3rd party lib to do it (though if you prefer a cleaner solution, there probably are some kind of 3rd party tools out there you could use).</p>\n"
},
{
"answer_id": 42130,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 2,
"selected": false,
"text": "<p>You can use Reflection to set <code>myClassImpl</code> by calling <code>instantiateMyClass()</code> again. Take a look at <a href=\"https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods#34658\">this answer</a> to see example patterns for playing around with private methods and variables.</p>\n"
},
{
"answer_id": 9192126,
"author": "AutomatedMike",
"author_id": 352035,
"author_profile": "https://Stackoverflow.com/users/352035",
"pm_score": 5,
"selected": false,
"text": "<p>This question might be old but since this was the nearest answer I found when I had this problem I though I'd describe my solution.</p>\n\n<p><strong>Using JUnit 4</strong></p>\n\n<p>Split your tests up so that there is one test method per class (this solution only changes classloaders between classes, not between methods as the parent runner gathers all the methods once per class)</p>\n\n<p>Add the <code>@RunWith(SeparateClassloaderTestRunner.class)</code> annotation to your test classes.</p>\n\n<p>Create the <code>SeparateClassloaderTestRunner</code> to look like this:</p>\n\n<pre><code>public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner {\n\n public SeparateClassloaderTestRunner(Class<?> clazz) throws InitializationError {\n super(getFromTestClassloader(clazz));\n }\n\n private static Class<?> getFromTestClassloader(Class<?> clazz) throws InitializationError {\n try {\n ClassLoader testClassLoader = new TestClassLoader();\n return Class.forName(clazz.getName(), true, testClassLoader);\n } catch (ClassNotFoundException e) {\n throw new InitializationError(e);\n }\n }\n\n public static class TestClassLoader extends URLClassLoader {\n public TestClassLoader() {\n super(((URLClassLoader)getSystemClassLoader()).getURLs());\n }\n\n @Override\n public Class<?> loadClass(String name) throws ClassNotFoundException {\n if (name.startsWith(\"org.mypackages.\")) {\n return super.findClass(name);\n }\n return super.loadClass(name);\n }\n }\n}\n</code></pre>\n\n<p>Note I had to do this to test code running in a legacy framework which I couldn't change. Given the choice I'd reduce the use of statics and/or put test hooks in to allow the system to be reset. It may not be pretty but it allows me to test an awful lot of code that would be difficult otherwise.</p>\n\n<p>Also this solution breaks anything else that relies on classloading tricks such as Mockito.</p>\n"
},
{
"answer_id": 17805809,
"author": "barclar",
"author_id": 329736,
"author_profile": "https://Stackoverflow.com/users/329736",
"pm_score": 2,
"selected": false,
"text": "<p>If executing Junit via the <a href=\"http://ant.apache.org/manual/Tasks/junit.html\" rel=\"nofollow\">Ant task</a> you can set <strong><code>fork=true</code></strong> to execute every class of tests in it's own JVM. Also put each test method in its own class and they will each load and initialise their own version of <code>MyClass</code>. It's extreme but very effective.</p>\n"
},
{
"answer_id": 34154189,
"author": "Neeme Praks",
"author_id": 74694,
"author_profile": "https://Stackoverflow.com/users/74694",
"pm_score": 1,
"selected": false,
"text": "<p>Below you can find a sample that does not need a separate JUnit test runner and works also with classloading tricks such as Mockito.</p>\n\n<pre><code>package com.mycompany.app;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\n\nimport java.net.URLClassLoader;\n\nimport org.junit.Test;\n\npublic class ApplicationInSeparateClassLoaderTest {\n\n @Test\n public void testApplicationInSeparateClassLoader1() throws Exception {\n testApplicationInSeparateClassLoader();\n }\n\n @Test\n public void testApplicationInSeparateClassLoader2() throws Exception {\n testApplicationInSeparateClassLoader();\n }\n\n private void testApplicationInSeparateClassLoader() throws Exception {\n //run application code in separate class loader in order to isolate static state between test runs\n Runnable runnable = mock(Runnable.class);\n //set up your mock object expectations here, if needed\n InterfaceToApplicationDependentCode tester = makeCodeToRunInSeparateClassLoader(\n \"com.mycompany.app\", InterfaceToApplicationDependentCode.class, CodeToRunInApplicationClassLoader.class);\n //if you want to try the code without class loader isolation, comment out above line and comment in the line below\n //CodeToRunInApplicationClassLoader tester = new CodeToRunInApplicationClassLoaderImpl();\n tester.testTheCode(runnable);\n verify(runnable).run();\n assertEquals(\"should be one invocation!\", 1, tester.getNumOfInvocations());\n }\n\n /**\n * Create a new class loader for loading application-dependent code and return an instance of that.\n */\n @SuppressWarnings(\"unchecked\")\n private <I, T> I makeCodeToRunInSeparateClassLoader(\n String packageName, Class<I> testCodeInterfaceClass, Class<T> testCodeImplClass) throws Exception {\n TestApplicationClassLoader cl = new TestApplicationClassLoader(\n packageName, getClass(), testCodeInterfaceClass);\n Class<?> testerClass = cl.loadClass(testCodeImplClass.getName());\n return (I) testerClass.newInstance();\n }\n\n /**\n * Bridge interface, implemented by code that should be run in application class loader.\n * This interface is loaded by the same class loader as the unit test class, so\n * we can call the application-dependent code without need for reflection.\n */\n public static interface InterfaceToApplicationDependentCode {\n void testTheCode(Runnable run);\n int getNumOfInvocations();\n }\n\n /**\n * Test-specific code to call application-dependent code. This class is loaded by \n * the same class loader as the application code.\n */\n public static class CodeToRunInApplicationClassLoader implements InterfaceToApplicationDependentCode {\n private static int numOfInvocations = 0;\n\n @Override\n public void testTheCode(Runnable runnable) {\n numOfInvocations++;\n runnable.run();\n }\n\n @Override\n public int getNumOfInvocations() {\n return numOfInvocations;\n }\n }\n\n /**\n * Loads application classes in separate class loader from test classes.\n */\n private static class TestApplicationClassLoader extends URLClassLoader {\n\n private final String appPackage;\n private final String mainTestClassName;\n private final String[] testSupportClassNames;\n\n public TestApplicationClassLoader(String appPackage, Class<?> mainTestClass, Class<?>... testSupportClasses) {\n super(((URLClassLoader) getSystemClassLoader()).getURLs());\n this.appPackage = appPackage;\n this.mainTestClassName = mainTestClass.getName();\n this.testSupportClassNames = convertClassesToStrings(testSupportClasses);\n }\n\n private String[] convertClassesToStrings(Class<?>[] classes) {\n String[] results = new String[classes.length];\n for (int i = 0; i < classes.length; i++) {\n results[i] = classes[i].getName();\n }\n return results;\n }\n\n @Override\n public Class<?> loadClass(String className) throws ClassNotFoundException {\n if (isApplicationClass(className)) {\n //look for class only in local class loader\n return super.findClass(className);\n }\n //look for class in parent class loader first and only then in local class loader\n return super.loadClass(className);\n }\n\n private boolean isApplicationClass(String className) {\n if (mainTestClassName.equals(className)) {\n return false;\n }\n for (int i = 0; i < testSupportClassNames.length; i++) {\n if (testSupportClassNames[i].equals(className)) {\n return false;\n }\n }\n return className.startsWith(appPackage);\n }\n\n }\n\n}\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] | I have a Singleton/Factory object that I'd like to write a JUnit test for. The Factory method decides which implementing class to instantiate based upon a classname in a properties file on the classpath. If no properties file is found, or the properties file does not contain the classname key, then the class will instantiate a default implementing class.
Since the factory keeps a static instance of the Singleton to use once it has been instantiated, to be able to test the "failover" logic in the Factory method I would need to run each test method in a different classloader.
Is there any way with JUnit (or with another unit testing package) to do this?
edit: here is some of the Factory code that is in use:
```
private static MyClass myClassImpl = instantiateMyClass();
private static MyClass instantiateMyClass() {
MyClass newMyClass = null;
String className = null;
try {
Properties props = getProperties();
className = props.getProperty(PROPERTY_CLASSNAME_KEY);
if (className == null) {
log.warn("instantiateMyClass: Property [" + PROPERTY_CLASSNAME_KEY
+ "] not found in properties, using default MyClass class [" + DEFAULT_CLASSNAME + "]");
className = DEFAULT_CLASSNAME;
}
Class MyClassClass = Class.forName(className);
Object MyClassObj = MyClassClass.newInstance();
if (MyClassObj instanceof MyClass) {
newMyClass = (MyClass) MyClassObj;
}
}
catch (...) {
...
}
return newMyClass;
}
private static Properties getProperties() throws IOException {
Properties props = new Properties();
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
if (stream != null) {
props.load(stream);
}
else {
log.error("getProperties: could not load properties file [" + PROPERTIES_FILENAME + "] from classpath, file not found");
}
return props;
}
``` | This question might be old but since this was the nearest answer I found when I had this problem I though I'd describe my solution.
**Using JUnit 4**
Split your tests up so that there is one test method per class (this solution only changes classloaders between classes, not between methods as the parent runner gathers all the methods once per class)
Add the `@RunWith(SeparateClassloaderTestRunner.class)` annotation to your test classes.
Create the `SeparateClassloaderTestRunner` to look like this:
```
public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner {
public SeparateClassloaderTestRunner(Class<?> clazz) throws InitializationError {
super(getFromTestClassloader(clazz));
}
private static Class<?> getFromTestClassloader(Class<?> clazz) throws InitializationError {
try {
ClassLoader testClassLoader = new TestClassLoader();
return Class.forName(clazz.getName(), true, testClassLoader);
} catch (ClassNotFoundException e) {
throw new InitializationError(e);
}
}
public static class TestClassLoader extends URLClassLoader {
public TestClassLoader() {
super(((URLClassLoader)getSystemClassLoader()).getURLs());
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("org.mypackages.")) {
return super.findClass(name);
}
return super.loadClass(name);
}
}
}
```
Note I had to do this to test code running in a legacy framework which I couldn't change. Given the choice I'd reduce the use of statics and/or put test hooks in to allow the system to be reset. It may not be pretty but it allows me to test an awful lot of code that would be difficult otherwise.
Also this solution breaks anything else that relies on classloading tricks such as Mockito. |
42,115 | <p>I am running into an issue I had before; can't find my reference on how to solve it.</p>
<p>Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below:</p>
<pre><code> config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
If config.ConnectionStrings.SectionInformation.IsProtected = False Then
config.ConnectionStrings.SectionInformation.ProtectSection(Nothing)
' We must save the changes to the configuration file.'
config.Save(ConfigurationSaveMode.Modified, True)
End If
</code></pre>
<p>The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is:</p>
<pre><code>Unhandled Exception: System.Configuration.ConfigurationErrorsException:
An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'.
Error message from the provider: Object already exists.
---> System.Security.Cryptography.CryptographicException: Object already exists
</code></pre>
| [
{
"answer_id": 42206,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like a permissions issue. The (new) user in question has write permissions to the app.config file? Was the previous user a local admin or power user that could have masked this problem? </p>\n"
},
{
"answer_id": 42213,
"author": "MikeScott8",
"author_id": 1889,
"author_profile": "https://Stackoverflow.com/users/1889",
"pm_score": 1,
"selected": false,
"text": "<p>So I did get it working.</p>\n\n<ol>\n<li>removed old users account from laptop</li>\n<li>reset app.config to have section not protected</li>\n<li>removed key file from all users machine keys</li>\n<li>ran app and allowed it to protect the section</li>\n</ol>\n\n<p>But all this did was get it working for this user.</p>\n\n<p>NOW I need to know what I have to do to change the code to protect the section so that multiple users on a PC can use the application. Virtual PC here I come (well after vacation to WDW tomorrow through next Wednesday)!</p>\n\n<p>any advice to help pointing me in right direction, as I am not very experienced in this RSA encryption type stuff.</p>\n"
},
{
"answer_id": 373205,
"author": "MikeScott8",
"author_id": 1889,
"author_profile": "https://Stackoverflow.com/users/1889",
"pm_score": 2,
"selected": true,
"text": "<p>I found a more elegant solution that in my original answer to myself. I found if I just logged in as th euser who orignally installed the application and caused the config file connectionstrings to be encrypted and go to the .net framework directory in a commadn prompt and run </p>\n\n<pre><code>aspnet_regiis -pa \"NetFrameworkConfigurationKey\" \"{domain}\\{user}\"\n</code></pre>\n\n<p>it gave the other user permission to access the RSA encryption key container and it then works for the other user(s).</p>\n\n<p>Just wanted to add it here as I thought I had blogged this issue on our dev blog but found it here, so in case I need to look it up again it will be here. Will add link to our dev blog point at this thread as well. </p>\n"
},
{
"answer_id": 2702297,
"author": "luisfbn",
"author_id": 324647,
"author_profile": "https://Stackoverflow.com/users/324647",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://blogs.msdn.com/mosharaf/archive/2005/11/17/protectedConfiguration.aspx#1657603\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/mosharaf/archive/2005/11/17/protectedConfiguration.aspx#1657603</a></p>\n\n<p>copy and paste :D</p>\n\n<p>Monday, February 12, 2007 12:15 AM by Naica</p>\n\n<p><strong>re: Encrypting configuration files using protected configuration</strong></p>\n\n<p>Here is a list of all steps I've done to encrypt two sections on my PC and then deploy it to the WebServer. Maybe it will help someone...:</p>\n\n<ol>\n<li><p>To create a machine-level RSA key container</p>\n\n<pre><code>aspnet_regiis -pc \"DataProtectionConfigurationProviderKeys\" -exp\n</code></pre></li>\n<li><p>Add this to web.config before connectionStrings section:</p>\n\n<p></p>\n\n<p></p>\n\n<p></p>\n\n<pre><code> <add name=\"DataProtectionConfigurationProvider\"\n\n type=\"System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0,\n\n Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,\n\n processorArchitecture=MSIL\"\n\n keyContainerName=\"DataProtectionConfigurationProviderKeys\"\n\n useMachineContainer=\"true\" />\n</code></pre>\n\n<p></p>\n\n<p></p>\n\n<p>Do not miss the <code><clear /></code> from above! Important when playing with encrypting/decrypting many times</p></li>\n<li><p>Check to have this at the top of Web.Config file. If missing add it:</p>\n\n<pre><code><configuration xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\">\n</code></pre></li>\n<li><p>Save and close Web.Config file in VS (very important!)</p></li>\n<li><p>In Command Prompt (my local PC) window go to:</p>\n\n<blockquote>\n <p>C:\\WINNT\\Microsoft.NET\\Framework\\v2.0.50727</p>\n</blockquote></li>\n<li><p>Encrypt: (Be aware to Change physical path for your App, or use -app option and give the name o virtual directory for app! Because I used VS on my PC I preferred the bellow option. The path is the path to Web.config file)</p>\n\n<p>aspnet_regiis -pef \"connectionStrings\" \"c:\\Bla\\Bla\\Bla\" -prov \"DataProtectionConfigurationProvider\"</p>\n\n<p>aspnet_regiis -pef \"system.web/membership\" \"c:\\Bla\\Bla\\Bla\" -prov \"DataProtectionConfigurationProvider\"</p></li>\n<li><p>To Decrypt (if needed only!):</p>\n\n<pre><code>aspnet_regiis -pdf \"connectionStrings\" \"c:\\Bla\\Bla\\Bla\"\n\naspnet_regiis -pdf \"system.web/membership\" \"c:\\Bla\\Bla\\Bla\"\n</code></pre></li>\n<li><p>Delete Keys Container (if needed only!)</p>\n\n<pre><code>aspnet_regiis -pz \"DataProtectionConfigurationProviderKeys\"\n</code></pre></li>\n<li><p>Save the above key to xml file in order to export it from your local PC to the WebServer (UAT or Production)</p>\n\n<pre><code>aspnet_regiis -px \"DataProtectionConfigurationProviderKeys\" \\temp\\mykeyfile.xml -pri\n</code></pre></li>\n<li><p>Import the key container on WebServer servers:</p>\n\n<pre><code>aspnet_regiis -pi \"DataProtectionConfigurationProviderKeys\" \\temp\\mykeyfile.xml\n</code></pre></li>\n<li><p>Grant access to the key on the web server</p>\n\n<pre><code>aspnet_regiis -pa \"DataProtectionConfigurationProviderKeys\" \"DOMAIN\\User\"\n</code></pre>\n\n<p>See in IIS the ASP.NET user or use:</p>\n\n<pre><code>Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name\n</code></pre></li>\n<li><p>Remove Grant access to the key on the web server (Only if required!)</p>\n\n<pre><code>aspnet_regiis -pr \"DataProtectionConfigurationProviderKeys\" \"Domain\\User\"\n</code></pre></li>\n<li><p>Copy and Paste to WebServer the encrypted Web.config file.</p></li>\n</ol>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1889/"
] | I am running into an issue I had before; can't find my reference on how to solve it.
Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below:
```
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
If config.ConnectionStrings.SectionInformation.IsProtected = False Then
config.ConnectionStrings.SectionInformation.ProtectSection(Nothing)
' We must save the changes to the configuration file.'
config.Save(ConfigurationSaveMode.Modified, True)
End If
```
The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is:
```
Unhandled Exception: System.Configuration.ConfigurationErrorsException:
An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'.
Error message from the provider: Object already exists.
---> System.Security.Cryptography.CryptographicException: Object already exists
``` | I found a more elegant solution that in my original answer to myself. I found if I just logged in as th euser who orignally installed the application and caused the config file connectionstrings to be encrypted and go to the .net framework directory in a commadn prompt and run
```
aspnet_regiis -pa "NetFrameworkConfigurationKey" "{domain}\{user}"
```
it gave the other user permission to access the RSA encryption key container and it then works for the other user(s).
Just wanted to add it here as I thought I had blogged this issue on our dev blog but found it here, so in case I need to look it up again it will be here. Will add link to our dev blog point at this thread as well. |
42,125 | <p>I have a library I created,</p>
<h3>File <em>mylib.c:</em></h3>
<pre><code>#include <mylib.h>
int
testlib() {
printf("Hello, World!\n");
return (0);
}
</code></pre>
<h3>File <em>mylib.h:</em></h3>
<pre><code>#include <stdio.h>
extern int testlib();
</code></pre>
<p>In my program, I've attempted to call this library function:</p>
<h3>File <em>myprogram.c</em>:</h3>
<pre><code>#include <mylib.h>
int
main (int argc, char *argv[]) {
testlib();
return (0);
}
</code></pre>
<p>When I attempt to compile this program I get the following error:</p>
<pre>In file included from myprogram.c:1
mylib.h:2 warning: function declaration isn't a prototype</pre>
<p>I'm using: <code>gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)</code></p>
<p>What is the proper way to declare a function prototype?</p>
| [
{
"answer_id": 42133,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>extern int testlib(void);\n</code></pre>\n"
},
{
"answer_id": 47693,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 10,
"selected": true,
"text": "<p>In C <code>int foo()</code> and <code>int foo(void)</code> are different functions. <code>int foo()</code> accepts an arbitrary number of arguments, while <code>int foo(void)</code> accepts 0 arguments. In C++ they mean the same thing. I suggest that you use <code>void</code> consistently when you mean no arguments.</p>\n\n<p>If you have a variable <code>a</code>, <code>extern int a;</code> is a way to tell the compiler that <code>a</code> is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (<code>extern</code>, <code>static</code>) only affects its visibility and <code>extern</code> is the default, so <code>extern</code> is actually unnecessary.</p>\n\n<p>I suggest removing the <code>extern</code>, it is extraneous and is usually omitted. </p>\n"
},
{
"answer_id": 20843829,
"author": "Keith Thompson",
"author_id": 827263,
"author_profile": "https://Stackoverflow.com/users/827263",
"pm_score": 6,
"selected": false,
"text": "<p>Quick answer: change <code>int testlib()</code> to <code>int testlib(void)</code> to specify that the function takes no arguments.</p>\n<p>A <em>prototype</em> is by definition a function declaration that specifies the type(s) of the function's argument(s).</p>\n<p>A non-prototype function declaration like</p>\n<pre><code>int foo();\n</code></pre>\n<p>is an old-style declaration that does not specify the number or types of arguments. (Prior to the 1989 ANSI C standard, this was the only kind of function declaration available in the language.) You can call such a function with any arbitrary number of arguments, and the compiler isn't required to complain -- but if the call is inconsistent with the <em>definition</em>, your program has undefined behavior.</p>\n<p>For a function that takes one or more arguments, you can specify the type of each argument in the declaration:</p>\n<pre><code>int bar(int x, double y);\n</code></pre>\n<p>Functions with no arguments are a special case. Logically, empty parentheses would have been a good way to specify that a function takes no arguments, but that syntax was already in use for old-style function declarations, so the ANSI C committee invented a new syntax using the <code>void</code> keyword:</p>\n<pre><code>int foo(void); /* foo takes no arguments */\n</code></pre>\n<p>A function <em>definition</em> (which includes code for what the function actually does) also provides a <em>declaration</em>. In your case, you have something similar to:</p>\n<pre><code>int testlib()\n{\n /* code that implements testlib */\n}\n</code></pre>\n<p>This provides a non-prototype declaration for <code>testlib</code>. As a definition, this tells the compiler that <code>testlib</code> has no parameters, but as a declaration, it only tells the compiler that <code>testlib</code> takes some unspecified but fixed number and type(s) of arguments.</p>\n<p>If you change <code>()</code> to <code>(void)</code> the declaration becomes a prototype.</p>\n<p>The advantage of a prototype is that if you accidentally call <code>testlib</code> with one or more arguments, the compiler will diagnose the error.</p>\n<p>(C++ has slightly different rules. C++ doesn't have old-style function declarations, and empty parentheses specifically mean that a function takes no arguments. C++ supports the <code>(void)</code> syntax for consistency with C. But unless you specifically need your code to compile both as C and as C++, you should probably use the <code>()</code> in C++ and the <code>(void)</code> syntax in C.)</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3807/"
] | I have a library I created,
### File *mylib.c:*
```
#include <mylib.h>
int
testlib() {
printf("Hello, World!\n");
return (0);
}
```
### File *mylib.h:*
```
#include <stdio.h>
extern int testlib();
```
In my program, I've attempted to call this library function:
### File *myprogram.c*:
```
#include <mylib.h>
int
main (int argc, char *argv[]) {
testlib();
return (0);
}
```
When I attempt to compile this program I get the following error:
```
In file included from myprogram.c:1
mylib.h:2 warning: function declaration isn't a prototype
```
I'm using: `gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)`
What is the proper way to declare a function prototype? | In C `int foo()` and `int foo(void)` are different functions. `int foo()` accepts an arbitrary number of arguments, while `int foo(void)` accepts 0 arguments. In C++ they mean the same thing. I suggest that you use `void` consistently when you mean no arguments.
If you have a variable `a`, `extern int a;` is a way to tell the compiler that `a` is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (`extern`, `static`) only affects its visibility and `extern` is the default, so `extern` is actually unnecessary.
I suggest removing the `extern`, it is extraneous and is usually omitted. |
42,153 | <p>I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead.</p>
<p>How do you embed a <code>JApplet</code> in HTML on a webpage?</p>
| [
{
"answer_id": 42162,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 1,
"selected": false,
"text": "<p>Use the <applet> tag. For more info: <a href=\"http://java.sun.com/docs/books/tutorial/deployment/applet/html.html\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/tutorial/deployment/applet/html.html</a></p>\n"
},
{
"answer_id": 42163,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": true,
"text": "<p>Here is an example from <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html\" rel=\"nofollow noreferrer\">sun's website</a>:</p>\n\n<pre><code><applet code=\"TumbleItem.class\" \n codebase=\"examples/\"\n archive=\"tumbleClasses.jar, tumbleImages.jar\"\n width=\"600\" height=\"95\">\n <param name=\"maxwidth\" value=\"120\">\n <param name=\"nimgs\" value=\"17\">\n <param name=\"offset\" value=\"-57\">\n <param name=\"img\" value=\"images/tumble\">\n\nYour browser is completely ignoring the &lt;APPLET&gt; tag!\n</applet>\n</code></pre>\n"
},
{
"answer_id": 42176,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "<p>Although you didn't say so, just in case you were using JSPs, you also have the option of the <a href=\"http://java.sun.com/products/jsp/tags/syntaxref.fm12.html\" rel=\"nofollow noreferrer\">jsp:plugin</a> tag?</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] | I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead.
How do you embed a `JApplet` in HTML on a webpage? | Here is an example from [sun's website](http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html):
```
<applet code="TumbleItem.class"
codebase="examples/"
archive="tumbleClasses.jar, tumbleImages.jar"
width="600" height="95">
<param name="maxwidth" value="120">
<param name="nimgs" value="17">
<param name="offset" value="-57">
<param name="img" value="images/tumble">
Your browser is completely ignoring the <APPLET> tag!
</applet>
``` |
42,182 | <p>I'm trying to write a blog post which includes a code segment inside a <code><pre></code> tag. The code segment includes a generic type and uses <code><></code> to define that type. This is what the segment looks like:</p>
<pre><code><pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
</code></pre>
<p>The resulting HTML removes the <code><></code> and ends up like this:</p>
<pre><code>PrimeCalc calc = new PrimeCalc();
Func del = calc.GetNextPrime;
</code></pre>
<p>How do I escape the <code><></code> so they show up in the HTML?</p>
| [
{
"answer_id": 42189,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": -1,
"selected": false,
"text": "<p>It's probably something specific to your blog software, but you might want to give the following strings a try (remove the underscore character):\n&_lt; &_gt;</p>\n"
},
{
"answer_id": 42191,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>&lt; and &gt;\n</code></pre>\n\n<p>Hope this helps?</p>\n"
},
{
"answer_id": 42192,
"author": "ckpwong",
"author_id": 2551,
"author_profile": "https://Stackoverflow.com/users/2551",
"pm_score": 3,
"selected": false,
"text": "<p><code>&lt;</code> and <code>&gt;</code> respectively</p>\n"
},
{
"answer_id": 42193,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 4,
"selected": false,
"text": "<p>Use <code>&lt;</code> and <code>&gt;</code> to do <code><</code> and <code>></code> inside html.</p>\n"
},
{
"answer_id": 42194,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 5,
"selected": false,
"text": "<pre class=\"lang-html prettyprint-override\"><code><pre>&gt;</pre>\n</code></pre>\n\n<p>renders as:</p>\n\n<pre>>\n</pre>\n\n<p>So you want:</p>\n\n<pre><code><pre>\n PrimeCalc calc = new PrimeCalc();\n Func&lt;int, int&gt; del = calc.GetNextPrime;\n</pre>\n</code></pre>\n\n<p>which turns out like:</p>\n\n<pre>\n PrimeCalc calc = new PrimeCalc();\n Func<int, int> del = calc.GetNextPrime;\n</pre>\n"
},
{
"answer_id": 42195,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 8,
"selected": true,
"text": "<pre><code><pre>\n PrimeCalc calc = new PrimeCalc();\n Func&lt;int, int&gt; del = calc.GetNextPrime;\n</pre>\n</code></pre>\n"
},
{
"answer_id": 42201,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 2,
"selected": false,
"text": "<p>What <a href=\"https://stackoverflow.com/questions/42182/how-to-escape-and-inside-pre-tags#42186\">rp said</a>, just replace the greater-than(>) and less-than(<) symbols with their html entity equivalent. Here's an example:</p>\n\n<pre><code><pre>\n PrimeCalc calc = new PrimeCalc();\n Func&lt;int, int&gt; del = calc.GetNextPrime;\n</pre>\n</code></pre>\n\n<p>This should appear as (this time using exactly the same without the prepended spaces for markdown):</p>\n\n<pre>\n PrimeCalc calc = new PrimeCalc();\n Func<int, int> del = calc.GetNextPrime;\n</pre>\n"
},
{
"answer_id": 27536517,
"author": "PanicBus",
"author_id": 2526710,
"author_profile": "https://Stackoverflow.com/users/2526710",
"pm_score": -1,
"selected": false,
"text": "<p>A better way to do is not to have to worry about the character codes at all. Just wrap all your code inside the <code><pre></code> tags with the following</p>\n\n<pre><code><pre>\n${fn:escapeXml('\n <!-- all your code -->\n')};\n</pre>\n</code></pre>\n\n<p>You'll need to have jQuery enabled for it to work, tho.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] | I'm trying to write a blog post which includes a code segment inside a `<pre>` tag. The code segment includes a generic type and uses `<>` to define that type. This is what the segment looks like:
```
<pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
```
The resulting HTML removes the `<>` and ends up like this:
```
PrimeCalc calc = new PrimeCalc();
Func del = calc.GetNextPrime;
```
How do I escape the `<>` so they show up in the HTML? | ```
<pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
``` |
42,187 | <p>I have read about partial methods in the latest <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="noreferrer">C# language specification</a>, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?</p>
| [
{
"answer_id": 42190,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 2,
"selected": false,
"text": "<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/bb531348.aspx\" rel=\"nofollow noreferrer\">Code generation</a></strong> is one of main reasons they exist and one of the main reasons to use them.</p>\n\n<hr>\n\n<p>EDIT: Even though that link is to information specific to Visual Basic, the same basic principles are relevant to C#.</p>\n"
},
{
"answer_id": 42227,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>I see them as lightweight events. You can have a reusable code file (usually autogenerated but not necessarily) and for each implementation, just handle the events you care about in your partial class. In fact, this is how it's used in LINQ to SQL (and why the language feature was invented).</p>\n"
},
{
"answer_id": 42243,
"author": "Jonathan Webb",
"author_id": 1518,
"author_profile": "https://Stackoverflow.com/users/1518",
"pm_score": 3,
"selected": false,
"text": "<p>Partial methods are very similar in concept to the GoF <a href=\"http://www.dofactory.com/Patterns/PatternTemplate.aspx\" rel=\"noreferrer\">Template Method</a> behavioural pattern (<a href=\"http://books.google.com/books?id=aQ1RAAAAMAAJ&q=design+patterns&dq=design+patterns&ei=pNO-SJqWEY_-jgH1pvHpDA&pgis=1\" rel=\"noreferrer\">Design Patterns</a>, p325). </p>\n\n<p>They allow the behaviour of an algorithm or operation to be defined in one place and implemented or changed elsewhere enabling extensibility and customisation. I've started to use partial methods in C# 3.0 instead of template methods because the I think the code is cleaner.</p>\n\n<p>One nice feature is that unimplemented partial methods incur no runtime overhead as they're compiled away.</p>\n"
},
{
"answer_id": 42341,
"author": "Ed Schwehm",
"author_id": 1206,
"author_profile": "https://Stackoverflow.com/users/1206",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the best resource for partial classes in C#.NET 3.0: <a href=\"http://msdn.microsoft.com/en-us/library/wa80x488(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/wa80x488(VS.85).aspx</a></p>\n\n<p>I try to avoid using partial classes (with the exception of partials created by Visual Studio for designer files; those are great). To me, it's more important to have all of the code for a class in one place. If your class is well designed and represents one thing (<a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>), then all of the code for that one thing should be in one place.</p>\n"
},
{
"answer_id": 43557,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 6,
"selected": true,
"text": "<p>Partial methods have been introduced for similar reasons to why partial classes were in .Net 2.</p>\n\n<p>A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs.</p>\n\n<p>The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other.</p>\n\n<p>The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time.</p>\n\n<ul>\n<li>In .Net 1 it was auto-generated code in a <code>#region</code> block</li>\n<li>In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer</li>\n</ul>\n\n<p>This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes.</p>\n\n<p>In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code.</p>\n\n<p>The extra bit here is that code needed to provide methods that developers might want to fill in.</p>\n\n<p>As developers will extend these classes (with extra partial files) they couldn't use abstract methods here.</p>\n\n<p>The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time.</p>\n\n<p>Empty methods <a href=\"https://stackoverflow.com/questions/11783/in-net-will-empty-method-calls-be-optimized-out\">are not optimised out</a>.</p>\n\n<p>So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out.</p>\n\n<p>So that it can do this partial methods always return void.</p>\n\n<p>If you create a new Linq DBML file it will auto-generate a partial class, something like</p>\n\n<pre><code>[System.Data.Linq.Mapping.DatabaseAttribute(Name=\"MyDB\")]\npublic partial class MyDataContext : System.Data.Linq.DataContext\n{\n ...\n\n partial void OnCreated();\n partial void InsertMyTable(MyTable instance);\n partial void UpdateMyTable(MyTable instance);\n partial void DeleteMyTable(MyTable instance);\n\n ...\n</code></pre>\n\n<p>Then in your own partial file you can extend this:</p>\n\n<pre><code>public partial class MyDataContext\n{\n partial void OnCreated() {\n //do something on data context creation\n }\n}\n</code></pre>\n\n<p>If you don't extend these methods they get optimised right out.</p>\n\n<p>Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer.</p>\n\n<p>The example I mentioned before is one possibility:</p>\n\n<pre><code>//this code will get optimised out if no body is implemented\npartial void DoSomethingIfCompFlag();\n\n#if COMPILER_FLAG\n//this code won't exist if the flag is off\npartial void DoSomethingIfCompFlag() {\n //your code\n}\n#endif\n</code></pre>\n\n<p>Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | I have read about partial methods in the latest [C# language specification](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx), so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods? | Partial methods have been introduced for similar reasons to why partial classes were in .Net 2.
A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs.
The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other.
The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time.
* In .Net 1 it was auto-generated code in a `#region` block
* In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer
This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes.
In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code.
The extra bit here is that code needed to provide methods that developers might want to fill in.
As developers will extend these classes (with extra partial files) they couldn't use abstract methods here.
The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time.
Empty methods [are not optimised out](https://stackoverflow.com/questions/11783/in-net-will-empty-method-calls-be-optimized-out).
So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out.
So that it can do this partial methods always return void.
If you create a new Linq DBML file it will auto-generate a partial class, something like
```
[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")]
public partial class MyDataContext : System.Data.Linq.DataContext
{
...
partial void OnCreated();
partial void InsertMyTable(MyTable instance);
partial void UpdateMyTable(MyTable instance);
partial void DeleteMyTable(MyTable instance);
...
```
Then in your own partial file you can extend this:
```
public partial class MyDataContext
{
partial void OnCreated() {
//do something on data context creation
}
}
```
If you don't extend these methods they get optimised right out.
Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer.
The example I mentioned before is one possibility:
```
//this code will get optimised out if no body is implemented
partial void DoSomethingIfCompFlag();
#if COMPILER_FLAG
//this code won't exist if the flag is off
partial void DoSomethingIfCompFlag() {
//your code
}
#endif
```
Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first. |
42,215 | <p>We get the following error;</p>
<pre><code>The request was aborted: Could not create SSL/TLS secure channel
</code></pre>
<p>while using a <code>WebRequest</code> object to make an <code>HTTPS</code> request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something. </p>
<p>Has anyone seen this kind of thing before?</p>
| [
{
"answer_id": 42228,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like it may be a Conenction: Keep-alive thing: <a href=\"http://blogs.x2line.com/al/archive/2005/01/04/759.aspx#780\" rel=\"nofollow noreferrer\">http://blogs.x2line.com/al/archive/2005/01/04/759.aspx#780</a></p>\n"
},
{
"answer_id": 42229,
"author": "Travis",
"author_id": 4284,
"author_profile": "https://Stackoverflow.com/users/4284",
"pm_score": 3,
"selected": true,
"text": "<p>I seem to recall having this problem last year. I suspect that you aren't closing your WebRequest objects properly, which is why after a certain amount of use it won't allow you to create any new connections.</p>\n"
},
{
"answer_id": 2829114,
"author": "Thiago",
"author_id": 340557,
"author_profile": "https://Stackoverflow.com/users/340557",
"pm_score": 2,
"selected": false,
"text": "<p>I have exactly the same problem! \nI send two requisitions to an HTTPS webservice in close period range (seconds).\nThe first requisition works fine, but the second requisition fails.</p>\n\n<p>I´ve tried to set \"System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Ssl3\", but the second requisition freezes...</p>\n\n<p>I´m using VB.NET 2008.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 32132106,
"author": "Vyacheslav Kinzerskiy",
"author_id": 5250067,
"author_profile": "https://Stackoverflow.com/users/5250067",
"pm_score": 1,
"selected": false,
"text": "<p>The similar problem for me fixed by: </p>\n\n<pre><code>System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] | We get the following error;
```
The request was aborted: Could not create SSL/TLS secure channel
```
while using a `WebRequest` object to make an `HTTPS` request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something.
Has anyone seen this kind of thing before? | I seem to recall having this problem last year. I suspect that you aren't closing your WebRequest objects properly, which is why after a certain amount of use it won't allow you to create any new connections. |
42,246 | <p>I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT. </p>
<p>The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server.</p>
<p>I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files.</p>
<p>Are there any other suggestions?</p>
<p>Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN:</p>
<p>from <a href="http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml" rel="nofollow noreferrer">http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml</a></p>
<pre><code>* select the two revisions
* right-click, "compare revisions"
* select all files in the list
* right-click, choose "export to..."
</code></pre>
| [
{
"answer_id": 42295,
"author": "Brian Lyttle",
"author_id": 636,
"author_profile": "https://Stackoverflow.com/users/636",
"pm_score": -1,
"selected": false,
"text": "<p>You don't provide information on what is allowed through the firewall. I'm not familiar with UnleashIT.</p>\n\n<p>I guess you could have a script that exports from SVN to a folder on the SVN server. The script then zips the exported files. You can then transport the ZIP file however you want and extract to the deployment server. </p>\n\n<p>TortoiseSVN supports proxy servers so you could use one of those from the client's side?</p>\n"
},
{
"answer_id": 42300,
"author": "Craig",
"author_id": 2047,
"author_profile": "https://Stackoverflow.com/users/2047",
"pm_score": 0,
"selected": false,
"text": "<p>You could try playing around with the <a href=\"http://svnbook.red-bean.com/en/1.1/re31.html\" rel=\"nofollow noreferrer\">svnadmin dump</a> command that ships with the Subversion binaries. You can use this command to dump the whole repository to a file, just certain revision, or a range of revisions. Then use <a href=\"http://svnbook.red-bean.com/en/1.0/re36.html\" rel=\"nofollow noreferrer\">svnadmin load</a> to load the <em>dump-file</em> into a new, clean repository.</p>\n\n<p>Not a perfect solution since it works in terms of the repository and not individual files.</p>\n"
},
{
"answer_id": 42503,
"author": "Dylan Bennett",
"author_id": 551,
"author_profile": "https://Stackoverflow.com/users/551",
"pm_score": 1,
"selected": false,
"text": "<p>So if I understand correctly...</p>\n\n<p>Let's say you have a repository that looks like this:</p>\n\n<pre><code>/\n|+-DIR1\n| |- FILEa\n| |- FILEb\n|+-DIR2\n| |- FILEc\n| |- FILEd\n|- FILEe\n|- FILEf\n</code></pre>\n\n<p>And let's say you update files <code>FILEa</code>, <code>FILEc</code>, and <code>FILEf</code> and commit them back into the repository. Then what you want to export out of the repository is a structure that looks like this:</p>\n\n<pre><code>/\n|+-DIR1\n| |- FILEa\n|+-DIR2\n| |- FILEc\n|- FILEf\n</code></pre>\n\n<p>Is that right?</p>\n"
},
{
"answer_id": 42507,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p>You just want the people who are behind the firewall to be able to access the latest files committed to Subversion, right?</p>\n\n<p>Could you write an <a href=\"http://svnbook.red-bean.com/en/1.4/svn.reposadmin.create.html#svn.reposadmin.create.hooks\" rel=\"nofollow noreferrer\">svn hook script</a> that uses some method (maybe scp or ftp) to send the files over to the remote location at the time they're committed?</p>\n"
},
{
"answer_id": 43250,
"author": "Jared",
"author_id": 3442,
"author_profile": "https://Stackoverflow.com/users/3442",
"pm_score": 1,
"selected": false,
"text": "<p>The Subversion hooks looks like it has a lot of promise. But being relatively uninformed about how to script the hook, how would I pull out the files that were committed and FTP them somewhere maintaining the directory structure?</p>\n\n<p>If I could do that, then someone inside the firewall can pull the files down to the deployment server and we'd be good to go.</p>\n"
},
{
"answer_id": 45983,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 2,
"selected": true,
"text": "<p>I've found <a href=\"http://samba.anu.edu.au/rsync/\" rel=\"nofollow noreferrer\">rsync</a> extremely useful for synchronizing directory trees across multiple systems. If you have shell access to your server from a development workstation, you can regularly check out code locally and run rsync, which will transfer only the files that have changed to the server.</p>\n\n<p>(This assumes a Unix-like environment on your development workstations. Cygwin will work fine.)</p>\n\n<pre><code>cd deploy\nsvn update\nrsync -a . server:webdir/\n</code></pre>\n\n<p>Your question sounds like you don't actually have any direct network access from your development workstations to your server, and what you're really looking for is a way to get Subversion to tell you which files have changed. <strong>svn export</strong> supports an argument to let you check out only the files that changed between particular revisions. From the svn help:</p>\n\n<pre><code> -r [--revision] arg : ARG (some commands also take ARG1:ARG2 range)\n A revision argument can be one of:\n NUMBER revision number\n '{' DATE '}' revision at start of the date\n 'HEAD' latest in repository\n 'BASE' base rev of item's working copy\n 'COMMITTED' last commit at or before BASE\n 'PREV' revision just before COMMITTED\n</code></pre>\n\n<p>You'll need to keep track of what the latest revision you copied to the server. Assuming it's SVN revision xxxx:</p>\n\n<pre><code>svn export -r xxxx:HEAD http://svn/\n</code></pre>\n\n<p>Then simply copy the contents of the <em>deploy</em> directory to your server on top of the existing files.</p>\n\n<p>This won't handle deleted files, which may prove problematic in some environments.</p>\n"
},
{
"answer_id": 262104,
"author": "bolk",
"author_id": 32764,
"author_profile": "https://Stackoverflow.com/users/32764",
"pm_score": 2,
"selected": false,
"text": "<p><code>svn export</code> does not accept a revision range, try it out.</p>\n\n<p>A possible solution is to get the list of changed files with:</p>\n\n<pre><code>svn diff --summarize -rXXX http://svn/...\n</code></pre>\n\n<p>and then export each of them.</p>\n"
},
{
"answer_id": 2430366,
"author": "Philip Gloyne",
"author_id": 141765,
"author_profile": "https://Stackoverflow.com/users/141765",
"pm_score": 0,
"selected": false,
"text": "<p>If you tag the revisions this may help <a href=\"http://github.com/philipgloyne/svn-diff-export\" rel=\"nofollow noreferrer\">github svn-diff-export</a></p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3442/"
] | I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT.
The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server.
I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files.
Are there any other suggestions?
Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN:
from <http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml>
```
* select the two revisions
* right-click, "compare revisions"
* select all files in the list
* right-click, choose "export to..."
``` | I've found [rsync](http://samba.anu.edu.au/rsync/) extremely useful for synchronizing directory trees across multiple systems. If you have shell access to your server from a development workstation, you can regularly check out code locally and run rsync, which will transfer only the files that have changed to the server.
(This assumes a Unix-like environment on your development workstations. Cygwin will work fine.)
```
cd deploy
svn update
rsync -a . server:webdir/
```
Your question sounds like you don't actually have any direct network access from your development workstations to your server, and what you're really looking for is a way to get Subversion to tell you which files have changed. **svn export** supports an argument to let you check out only the files that changed between particular revisions. From the svn help:
```
-r [--revision] arg : ARG (some commands also take ARG1:ARG2 range)
A revision argument can be one of:
NUMBER revision number
'{' DATE '}' revision at start of the date
'HEAD' latest in repository
'BASE' base rev of item's working copy
'COMMITTED' last commit at or before BASE
'PREV' revision just before COMMITTED
```
You'll need to keep track of what the latest revision you copied to the server. Assuming it's SVN revision xxxx:
```
svn export -r xxxx:HEAD http://svn/
```
Then simply copy the contents of the *deploy* directory to your server on top of the existing files.
This won't handle deleted files, which may prove problematic in some environments. |
42,247 | <p>The following code illustrates an object literal being assigned, but with no semicolon afterwards:</p>
<pre><code>var literal = {
say: function(msg) { alert(msg); }
}
literal.say("hello world!");
</code></pre>
<p>This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?</p>
<p>I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.</p>
| [
{
"answer_id": 42252,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 6,
"selected": true,
"text": "<p>Not technically, JavaScript has semicolons as optional in many situations. </p>\n\n<p>But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.</p>\n\n<p>Automatic semicolon insertion is performed by the interpreter, so you <em>can</em> leave them out if you so choose. In the comments, someone claimed that </p>\n\n<blockquote>\n <p>Semicolons are not optional with statements like break/continue/throw</p>\n</blockquote>\n\n<p>but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference. </p>\n\n<p>Here is the rest of the standard on semicolon insertion:</p>\n\n<blockquote>\n <p>For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.</p>\n</blockquote>\n"
},
{
"answer_id": 42256,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"http://www.jslint.com/\" rel=\"nofollow noreferrer\">JSLint</a> to keep your JavaScript clean and tidy</p>\n\n<p>JSLint says: </p>\n\n<blockquote>\n <p>Error:</p>\n \n <p>Implied global: alert 2</p>\n \n <p>Problem at line 3 character 2: Missing\n semicolon.</p>\n \n <p>}</p>\n</blockquote>\n"
},
{
"answer_id": 42259,
"author": "Kamiel Wanrooij",
"author_id": 4174,
"author_profile": "https://Stackoverflow.com/users/4174",
"pm_score": -1,
"selected": false,
"text": "<p>This is not valid (see clarification below) JavaScript code, since the assignment is just a regular statement, no different from</p>\n\n<pre><code>var foo = \"bar\";\n</code></pre>\n\n<p>The semicolon can be left out since JavaScript interpreters attempt to add a semicolon to fix syntax errors, but this is an extra and unnecessary step. I don't know of any strict mode, but I do know that automated parsers or compressors / obfuscators need that semicolon.</p>\n\n<p>If you want to be writing correct JavaScript code, write the semicolon :-)</p>\n\n<p>According to the ECMAscript spec, <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"nofollow noreferrer\">http://www.ecma-international.org/publications/standards/Ecma-262.htm</a>, the semicolons are automatically inserted if missing. This makes them not required for the script author, but it implies they are required for the interpreter. This means the answer to the original question is 'No', they are not required when writing a script, but, as is pointed out by others, it is recommended for various reasons.</p>\n"
},
{
"answer_id": 42269,
"author": "Travis",
"author_id": 4284,
"author_profile": "https://Stackoverflow.com/users/4284",
"pm_score": 0,
"selected": false,
"text": "<p>The semi-colon is not necessary. Some people choose to follow the convention of always terminating with a semi-colon instead of allowing JavaScript to do so automatically at linebreaks, but I'm sure you'll find groups advocating either direction.</p>\n\n<p>If you are looking at writing \"correct\" JavaScript, I would suggest testing things in Firefox with <code>javascript.options.strict</code> (accessed via <code>about:config</code>) set to true. It might not catch everything, but it should help you ensure your JavaScript code is more compliant.</p>\n"
},
{
"answer_id": 42311,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 4,
"selected": false,
"text": "<p>The YUI Compressor and dojo shrinksafe should work perfectly fine without semicolons since they're based on a full JavaScript parser. But Packer and JSMin won't.</p>\n\n<p>The other reason to always use semi-colons at the end of statements is that occasionally you can accidentally combine two statements to create something very different. For example, if you follow the statement with the common technique to create a scope using a closure:</p>\n\n<pre><code>var literal = {\n say: function(msg) { alert(msg); }\n}\n(function() {\n // ....\n})();\n</code></pre>\n\n<p>The parser might interpret the brackets as a function call, here causing a type error, but in other circumstances it could cause a subtle bug that's tricky to trace. Another interesting mishap is if the next statement starts with a regular expression, the parser might think the first forward slash is a division symbol.</p>\n"
},
{
"answer_id": 42317,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 2,
"selected": false,
"text": "<p>In this case there is no need for a semicolon at the end of the statement. The conclusion is the same but the reasoning is way off.</p>\n\n<p>JavaScript does not have semicolons as \"optional\". Rather, it has strict rules around automatic semicolon insertion. Semicolons are not optional with statements like <code>break</code>, <code>continue</code>, or <code>throw</code>. Refer to the <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"nofollow noreferrer\">ECMA Language Specification</a> for more details; specifically <a href=\"http://www.ecma-international.org/ecma-262/7.0/index.html#sec-rules-of-automatic-semicolon-insertion\" rel=\"nofollow noreferrer\">11.9.1, rules of automatic semicolon insertion</a>.</p>\n"
},
{
"answer_id": 42510,
"author": "JesDaw",
"author_id": 4440,
"author_profile": "https://Stackoverflow.com/users/4440",
"pm_score": 3,
"selected": false,
"text": "<p>JavaScript interpreters do something called \"semicolon insertion\", so if a line without a semicolon is valid, a semicolon will quietly be added to the end of the statement and no error will occur.</p>\n\n<pre><code>var foo = 'bar'\n// Valid, foo now contains 'bar'\nvar bas =\n { prop: 'yay!' }\n// Valid, bas now contains object with property 'prop' containing 'yay!'\nvar zeb =\nswitch (zeb) {\n ...\n// Invalid, because the lines following 'var zeb =' aren't an assignable value\n</code></pre>\n\n<p>Not too complicated and at least an error gets thrown when something is clearly not right. But there are cases where an error is <em>not</em> thrown, but the statements are not executed as intended due to semicolon insertion. Consider a function that is supposed to return an object:</p>\n\n<pre><code>return {\n prop: 'yay!'\n}\n// The object literal gets returned as expected and all is well\nreturn\n{\n prop: 'nay!'\n}\n// Oops! return by itself is a perfectly valid statement, so a semicolon\n// is inserted and undefined is unexpectedly returned, rather than the object\n// literal. Note that no error occurred.\n</code></pre>\n\n<p>Bugs like this can be maddeningly difficult to hunt down and while you can't <em>ensure</em> this never happens (since there's no way I know of to turn off semicolon insertion), these sorts of bugs are easier to identify when you make your intentions clear by consistently using semicolons. That and explicitly adding semicolons is generally considered good style.</p>\n\n<p>I was first made aware of this insidious little possibility when reading <a href=\"http://www.crockford.com/\" rel=\"nofollow noreferrer\">Douglas Crockford's</a> superb and succinct book \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/0596517742\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">JavaScript: The Good Parts</a>\". I <em>highly</em> recommend it.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | The following code illustrates an object literal being assigned, but with no semicolon afterwards:
```
var literal = {
say: function(msg) { alert(msg); }
}
literal.say("hello world!");
```
This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?
I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it. | Not technically, JavaScript has semicolons as optional in many situations.
But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.
Automatic semicolon insertion is performed by the interpreter, so you *can* leave them out if you so choose. In the comments, someone claimed that
>
> Semicolons are not optional with statements like break/continue/throw
>
>
>
but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference.
Here is the rest of the standard on semicolon insertion:
>
> For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
>
>
> |
42,254 | <p>I would like to flash a success message on my page.</p>
<p>I am using the jQuery <code>fadeOut</code> method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.</p>
<p>What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.</p>
<p>How can you animate this using jQuery? </p>
| [
{
"answer_id": 42255,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "<p>use <code>setTimeout(function(){$elem.hide();}, 5000);</code></p>\n\n<p>Where <code>$elem</code> is the element you wish to hide, and <code>5000</code> is the delay in milliseconds. You can actually use any function within the call to <code>setTimeout()</code>, that code just defines a small anonymous function for simplicity.</p>\n"
},
{
"answer_id": 42261,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var $msg = $('#msg-container-id');\n$msg.fadeIn(function(){\n setTimeout(function(){\n $msg.fadeOut(function(){\n $msg.remove();\n });\n },5000);\n});\n</code></pre>\n"
},
{
"answer_id": 42271,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "<p>For a pure jQuery approach, you can do</p>\n\n<pre><code>$(\"#element\").animate({opacity: 1.0}, 5000).fadeOut();\n</code></pre>\n\n<p>It's a hack, but it does the job</p>\n"
},
{
"answer_id": 42698,
"author": "dansays",
"author_id": 1923,
"author_profile": "https://Stackoverflow.com/users/1923",
"pm_score": 3,
"selected": false,
"text": "<p>While @John Sheehan's approach works, you run into the <a href=\"http://blog.bmn.name/2008/03/jquery-fadeinfadeout-ie-cleartype-glitch/\" rel=\"nofollow noreferrer\">jQuery fadeIn/fadeOut ClearType glitch</a> in IE7. Personally, I'd opt for @John Millikin's <code>setTimeout()</code> approach, but if you're set on a pure jQuery approach, better to trigger an animation on a non-opacity property, such as a margin.</p>\n\n<pre><code>var left = parseInt($('#element').css('marginLeft'));\n$('#element')\n .animate({ marginLeft: left ? left : 0 }, 5000)\n .fadeOut('fast');\n</code></pre>\n\n<p>You can be a bit cleaner if you know your margin to be a fixed value:</p>\n\n<pre><code>$('#element')\n .animate({ marginLeft: 0 }, 5000)\n .fadeOut('fast');\n</code></pre>\n\n<p><strong>EDIT</strong>: It looks like the <a href=\"http://plugins.jquery.com/project/fxqueues\" rel=\"nofollow noreferrer\">jQuery FxQueues plug-in</a> does just what you need:</p>\n\n<pre><code>$('#element').fadeOut({\n speed: 'fast',\n preDelay: 5000\n});\n</code></pre>\n"
},
{
"answer_id": 80675,
"author": "RET",
"author_id": 14750,
"author_profile": "https://Stackoverflow.com/users/14750",
"pm_score": 2,
"selected": false,
"text": "<p>Following on from dansays' comment, the following seems to work perfectly well:</p>\n\n<p><code>$('#thing') .animate({dummy:1}, 2000)\n .animate({ etc ... });</code></p>\n"
},
{
"answer_id": 2068227,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 6,
"selected": true,
"text": "<p>The new <code>delay()</code> function in jQuery 1.4 should do the trick.</p>\n\n<pre><code>$('#foo').fadeIn(200).delay(5000).fadeOut(200).remove();\n</code></pre>\n"
},
{
"answer_id": 3040106,
"author": "thekingoftruth",
"author_id": 241367,
"author_profile": "https://Stackoverflow.com/users/241367",
"pm_score": 1,
"selected": false,
"text": "<p>dansays's answer just doesn't work for me. For some reason, <code>remove()</code> runs immediately and the div disappears before any animations happen.</p>\n\n<p>The following works, however (by omitting the <code>remove()</code> method):</p>\n\n<pre><code>$('#foo').fadeIn(500).delay(5000).fadeOut(500);\n</code></pre>\n\n<p>I don't mind if there are hidden DIVs on the page (there shouldn't be more than a few anyway).</p>\n"
},
{
"answer_id": 7735285,
"author": "rjmoggach",
"author_id": 586932,
"author_profile": "https://Stackoverflow.com/users/586932",
"pm_score": 0,
"selected": false,
"text": "<p>Update for 1.6.2</p>\n\n<p>Nathan Long's answer will cause the element to pop off without obeying delay or <code>fadeOut</code>.</p>\n\n<p>This works:</p>\n\n<pre><code>$('#foo').delay(2000).fadeOut(2000);\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3645/"
] | I would like to flash a success message on my page.
I am using the jQuery `fadeOut` method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.
What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.
How can you animate this using jQuery? | The new `delay()` function in jQuery 1.4 should do the trick.
```
$('#foo').fadeIn(200).delay(5000).fadeOut(200).remove();
``` |
42,282 | <p>Which way do you prefer to create your forms in MVC?</p>
<pre><code><% Html.Form() { %>
<% } %>
</code></pre>
<p>Or</p>
<pre><code><form action="<%= Url.Action("ManageImage", "UserAccount") %>" method="post">
</form>
</code></pre>
<p>I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included. </p>
<p>What is your take?</p>
| [
{
"answer_id": 42289,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>On the whole, I think I'm kinda old-school as I prefer to roll my own HTML elements.</p>\n\n<p>I also prefer a view engine like like <a href=\"http://andrewpeters.net/2007/12/19/introducing-nhaml-an-aspnet-mvc-view-engine/\" rel=\"nofollow noreferrer\">NHaml</a>, which makes writing HTML almost an order of magnitude simpler.</p>\n"
},
{
"answer_id": 42304,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible.</p>\n"
},
{
"answer_id": 42502,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>I have to agree with both of you, I am not really like this simplistic WebForms style that seems to be integrating its way in to MVC. This stuff almost seems like it should be a 3rd party library or at the very least an extensions library that can be included if needed or wanted.</p>\n"
},
{
"answer_id": 42946,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 1,
"selected": false,
"text": "<p>I am totally in the opinion of old school HTML, that is what designers use. I don't like to include to much code centric syntax for this reason. I treat the web form view engine like a third party library, because I replaced it with a different view engine. If you do not like the way the web form view model works or the direction it is going, you can always <a href=\"https://stackoverflow.com/questions/42582/what-view-engine-are-you-using-with-aspnet-mvc\">go a different route</a>. That is one of the main reasons I love ASP.NET MVC.</p>\n"
},
{
"answer_id": 43080,
"author": "Andrew Peters",
"author_id": 608,
"author_profile": "https://Stackoverflow.com/users/608",
"pm_score": 0,
"selected": false,
"text": "<p>The reason for using helpers is that they allow you to encapsulate common patterns in a consistent and DRY fashion. Think of them as a way of refactoring views to remove duplication just as you would with regular code. </p>\n\n<p>For example, I <a href=\"http://andrewpeters.net/2008/08/21/nhaml-block-methods-and-restful-helpers/\" rel=\"nofollow noreferrer\">blogged</a> about some RESTful NHaml helpers that can build urls based on a model.</p>\n"
},
{
"answer_id": 44620,
"author": "Andrew Burns",
"author_id": 3683,
"author_profile": "https://Stackoverflow.com/users/3683",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Andrew Peters, DRY. It should also be pointed out that you can specify your controller, action, and params to the .Form() helper and if they fit into your routing rules then no query string parameters will be used.</p>\n\n<p>I also understand what Will was saying about the V in MVC. In my opinion I do not think it is a problem to put code in the view <strong>as long as it is for the view</strong>. It is really easy to cross the line between controller and view if you are not careful. Personally I can not stand to use C# as a template engine without my eyes bleeding or getting the urge to murder someone. This helps me keep my logic separated, controller logic in C#, view logic in brail.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17/"
] | Which way do you prefer to create your forms in MVC?
```
<% Html.Form() { %>
<% } %>
```
Or
```
<form action="<%= Url.Action("ManageImage", "UserAccount") %>" method="post">
</form>
```
I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included.
What is your take? | The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible. |
42,286 | <p>It seems like there should be something shorter than this:</p>
<pre><code>private string LoadFromFile(string path)
{
try
{
string fileContents;
using(StreamReader rdr = File.OpenText(path))
{
fileContents = rdr.ReadToEnd();
}
return fileContents;
}
catch
{
throw;
}
}
</code></pre>
| [
{
"answer_id": 42290,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>File.ReadAllText() maybe?</p>\n\n<p>ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/4803f846-3d8a-de8a-18eb-32cfcd038f76.htm if you have VS2008's help installed.</p>\n"
},
{
"answer_id": 42292,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "<pre><code>string text = File.ReadAllText(\"c:\\file1.txt\");\nFile.WriteAllText(\"c:\\file2.txt\", text);\n</code></pre>\n\n<p>Also check out ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes</p>\n"
},
{
"answer_id": 42293,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 5,
"selected": true,
"text": "<p>First of all, the title asks for \"how to write the contents of strnig to a text file\"\nbut your code example is for \"how to read the contents of a text file to a string.</p>\n\n<p>Answer to both questions:</p>\n\n<pre><code>using System.IO;\n...\nstring filename = \"C:/example.txt\";\nstring content = File.ReadAllText(filename);\nFile.WriteAllText(filename, content);\n</code></pre>\n\n<p>See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array.</p>\n"
},
{
"answer_id": 42322,
"author": "Bjorn Reppen",
"author_id": 1324220,
"author_profile": "https://Stackoverflow.com/users/1324220",
"pm_score": 2,
"selected": false,
"text": "<p>There's no point in that exception handler. It does nothing. This is just a shorterned version of your code, it's fine:</p>\n\n<pre><code> private string LoadFromFile(string path)\n {\n using(StreamReader rdr = File.OpenText(path))\n return rdr.ReadToEnd();\n }\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
] | It seems like there should be something shorter than this:
```
private string LoadFromFile(string path)
{
try
{
string fileContents;
using(StreamReader rdr = File.OpenText(path))
{
fileContents = rdr.ReadToEnd();
}
return fileContents;
}
catch
{
throw;
}
}
``` | First of all, the title asks for "how to write the contents of strnig to a text file"
but your code example is for "how to read the contents of a text file to a string.
Answer to both questions:
```
using System.IO;
...
string filename = "C:/example.txt";
string content = File.ReadAllText(filename);
File.WriteAllText(filename, content);
```
See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array. |
42,294 | <p>I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case. </p>
| [
{
"answer_id": 42301,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 9,
"selected": true,
"text": "<p>To get a sticky footer:</p>\n\n<ol>\n<li><p>Have a <code><div></code> with <code>class=\"wrapper\"</code> for your content.</p></li>\n<li><p>Right <strong>before</strong> the closing <code></div></code> of the <code>wrapper</code> place the\n<code><div class=\"push\"></div></code>.</p></li>\n<li><p>Right <strong>after</strong> the closing <code></div></code> of the <code>wrapper</code> place the \n<code><div class=\"footer\"></div></code>.</p></li>\n</ol>\n\n<pre class=\"lang-css prettyprint-override\"><code>* {\n margin: 0;\n}\nhtml, body {\n height: 100%;\n}\n.wrapper {\n min-height: 100%;\n height: auto !important;\n height: 100%;\n margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */\n}\n.footer, .push {\n height: 142px; /* .push must be the same height as .footer */\n}\n</code></pre>\n"
},
{
"answer_id": 42302,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": -1,
"selected": false,
"text": "<p>Try putting a container div (with overflow:auto) around the content and sidebar.</p>\n\n<p>If that doesn't work, do you have any screenshots or example links where the footer isn't displayed properly?</p>\n"
},
{
"answer_id": 42303,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 0,
"selected": false,
"text": "<p>One solution would be to set the min-height for the boxes. Unfortunately it seems that <a href=\"http://www.wellstyled.com/css-minheight-hack.html\" rel=\"nofollow noreferrer\">it's not well supported by IE</a> (surprise).</p>\n"
},
{
"answer_id": 42314,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 4,
"selected": false,
"text": "<p>Set the CSS for the <code>#footer</code> to:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>position: absolute;\nbottom: 0;\n</code></pre>\n\n<p>You will then need to add a <code>padding</code> or <code>margin</code> to the bottom of your <code>#sidebar</code> and <code>#content</code> to match the height of <code>#footer</code> or when they overlap, the <code>#footer</code> will cover them.</p>\n\n<p>Also, if I remember correctly, IE6 has a problem with the <code>bottom: 0</code> CSS. You might have to use a JS solution for IE6 (if you care about IE6 that is).</p>\n"
},
{
"answer_id": 42315,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 5,
"selected": false,
"text": "<p>You could use <code>position: absolute</code> following to put the footer at the bottom of the page, but then make sure your 2 columns have the appropriate <code>margin-bottom</code> so that they never get occluded by the footer.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#footer {\n position: absolute;\n bottom: 0px;\n width: 100%;\n}\n#content, #sidebar { \n margin-bottom: 5em; \n}\n</code></pre>\n"
},
{
"answer_id": 5138228,
"author": "obecalp",
"author_id": 47303,
"author_profile": "https://Stackoverflow.com/users/47303",
"pm_score": 0,
"selected": false,
"text": "<p>None of these pure css solutions work properly with dynamically resizing content (at least on firefox and Safari) e.g., if you have a background set on the container div, the page and then resize (adding a few rows) table inside the div, the table can stick out of the bottom of the styled area, i.e., you can have half the table in white on black theme and half the table complete white because both the font-color and background color is white. It's basically unfixable with themeroller pages.</p>\n\n<p>Nested div multi-column layout is an ugly hack and the 100% min-height body/container div for sticking footer is an uglier hack.</p>\n\n<p>The only none-script solution that works on all the browsers I've tried: a much simpler/shorter table with thead (for header)/tfoot (for footer)/tbody (td's for any number of columns) and 100% height. But this have perceived semantic and SEO disadvantages (tfoot must appear before tbody. ARIA roles may help decent search engines though).</p>\n"
},
{
"answer_id": 9345207,
"author": "Sophivorus",
"author_id": 809356,
"author_profile": "https://Stackoverflow.com/users/809356",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a solution with jQuery that works like a charm. It checks if the height of the window is greater than the height of the body. If it is, then it changes the margin-top of the footer to compensate. Tested in Firefox, Chrome, Safari and Opera.</p>\n\n<pre><code>$( function () {\n\n var height_diff = $( window ).height() - $( 'body' ).height();\n if ( height_diff > 0 ) {\n $( '#footer' ).css( 'margin-top', height_diff );\n }\n\n});\n</code></pre>\n\n<p>If your footer already has a margin-top (of 50 pixels, for example) you will need to change the last part for:</p>\n\n<pre><code>css( 'margin-top', height_diff + 50 )\n</code></pre>\n"
},
{
"answer_id": 12130241,
"author": "Paul Sweatte",
"author_id": 1113772,
"author_profile": "https://Stackoverflow.com/users/1113772",
"pm_score": 1,
"selected": false,
"text": "<p>Use absolute positioning and z-index to create a sticky footer div at any resolution using the following steps:</p>\n<ul>\n<li>Create a footer div with <code>position: absolute; bottom: 0;</code> and the desired height</li>\n<li>Set the padding of the footer to add whitespace between the content bottom and the window bottom</li>\n<li>Create a container <code>div</code> that wraps the body content with <code>position: relative; min-height: 100%;</code></li>\n<li>Add bottom padding to the main content <code>div</code> that is equal to the height plus padding of the footer</li>\n<li>Set the <code>z-index</code> of the footer greater than the container <code>div</code> if the footer is clipped</li>\n</ul>\n<p>Here is an example:</p>\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-html lang-html prettyprint-override\"><code><!doctype html>\n<html>\n <head>\n <title>Sticky Footer</title>\n <meta charset=\"utf-8\">\n <style>\n .wrapper { position: relative; min-height: 100%; }\n .footer { position: absolute; bottom:0; width: 100%; height: 200px; padding-top: 100px; background-color: gray; }\n .column { height: 2000px; padding-bottom: 300px; background-color: grxqeen; }\n /* Set the `html`, `body`, and container `div` to `height: 100%` for IE6 */\n </style>\n </head>\n <body>\n <div class=\"wrapper\">\n <div class=\"column\">\n <span>hello</span>\n </div>\n <div class=\"footer\">\n <p>This is a test. This is only a test...</p>\n </div>\n </div>\n </body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 26090114,
"author": "Danield",
"author_id": 703717,
"author_profile": "https://Stackoverflow.com/users/703717",
"pm_score": 7,
"selected": false,
"text": "<h2>Use CSS vh units!</h2>\n\n<p>Probably the most obvious and non-hacky way to go about a sticky footer would be to make use of the new <a href=\"http://www.w3.org/TR/css3-values/#viewport-relative-lengths\">css viewport units</a>.</p>\n\n<p>Take for example the following simple markup:</p>\n\n<pre><code><header>header goes here</header>\n<div class=\"content\">This page has little content</div>\n<footer>This is my footer</footer>\n</code></pre>\n\n<p>If the header is say 80px high and the footer is 40px high, then we can make our sticky footer <em>with one single rule</em> on the content div:</p>\n\n<pre><code>.content {\n min-height: calc(100vh - 120px);\n /* 80px header + 40px footer = 120px */\n}\n</code></pre>\n\n<p>Which means: let the height of the content div be <strong>at least</strong> 100% of the viewport height minus the combined heights of the header and footer.</p>\n\n<p>That's it.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\r\n margin:0;\r\n padding:0;\r\n}\r\nheader {\r\n background: yellow;\r\n height: 80px;\r\n}\r\n.content {\r\n min-height: calc(100vh - 120px);\r\n /* 80px header + 40px footer = 120px */\r\n background: pink;\r\n}\r\nfooter {\r\n height: 40px;\r\n background: aqua;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><header>header goes here</header>\r\n<div class=\"content\">This page has little content</div>\r\n<footer>This is my footer</footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>... and here's how the same code works with lots of content in the content div:<div class=\"snippet\" data-lang=\"js\" data-hide=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\r\n margin:0;\r\n padding:0;\r\n}\r\nheader {\r\n background: yellow;\r\n height: 80px;\r\n}\r\n.content {\r\n min-height: calc(100vh - 120px);\r\n /* 80px header + 40px footer = 120px */\r\n background: pink;\r\n}\r\nfooter {\r\n height: 40px;\r\n background: aqua;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><header>header goes here</header>\r\n<div class=\"content\">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.\r\n</div>\r\n<footer>\r\n This is my footer\r\n</footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>NB:</strong></p>\n\n<p>1) The height of the header and footer must be known</p>\n\n<p>2) Old versions of IE (IE8-) and Android (4.4-) don't support viewport units. (<a href=\"http://caniuse.com/viewport-units/embed/\">caniuse</a>)</p>\n\n<p>3) Once upon a time webkit had a problem with viewport units within a calc rule. This has indeed been fixed (<a href=\"http://blogs.adobe.com/webplatform/2014/06/12/improving-viewport-unit-support-in-webkit/\">see here</a>) so there's no problem there. However if you're looking to avoid using calc for some reason you can get around that using negative margins and padding with box-sizing -</p>\n\n<p>Like so:<div class=\"snippet\" data-lang=\"js\" data-hide=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\r\n margin:0;padding:0;\r\n}\r\nheader {\r\n background: yellow;\r\n height: 80px;\r\n position:relative;\r\n}\r\n.content {\r\n min-height: 100vh;\r\n background: pink;\r\n margin: -80px 0 -40px;\r\n padding: 80px 0 40px;\r\n box-sizing:border-box;\r\n}\r\nfooter {\r\n height: 40px;\r\n background: aqua;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><header>header goes here</header>\r\n<div class=\"content\">Lorem ipsum \r\n</div>\r\n<footer>\r\n This is my footer\r\n</footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 27587208,
"author": "Ajith",
"author_id": 4357818,
"author_profile": "https://Stackoverflow.com/users/4357818",
"pm_score": 1,
"selected": false,
"text": "<p>CSS :</p>\n\n<pre><code> #container{\n width: 100%;\n height: 100vh;\n }\n #container.footer{\n float:left;\n width:100%;\n height:20vh;\n margin-top:80vh;\n background-color:red;\n }\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code> <div id=\"container\">\n <div class=\"footer\">\n </div>\n </div>\n</code></pre>\n\n<p>This should do the trick if you are looking for a responsive footer aligned at the bottom of the page,which always keeps a top-margin of 80% of the viewport height.</p>\n"
},
{
"answer_id": 31528677,
"author": "Kyle Zimmer",
"author_id": 4293638,
"author_profile": "https://Stackoverflow.com/users/4293638",
"pm_score": 0,
"selected": false,
"text": "<p>Multiple people have put the answer to this simple problem up here, but I have one thing to add, considering how frustrated I was until I figured out what I was doing wrong.</p>\n\n<p>As mentioned the most straightforward way to do this is like so..</p>\n\n<pre><code>html {\n position: relative;\n min-height: 100%;\n}\n\nbody {\n background-color: transparent;\n position: static;\n height: 100%;\n margin-bottom: 30px;\n}\n\n.site-footer {\n position: absolute;\n height: 30px;\n bottom: 0px;\n left: 0px;\n right: 0px;\n}\n</code></pre>\n\n<p>However the property not mentioned in posts, presumably because it is usually default, is the <strong>position: static</strong> on the body tag. Position relative will not work!</p>\n\n<p>My wordpress theme had overridden the default body display and it confused me for an obnoxiously long time.</p>\n"
},
{
"answer_id": 34146411,
"author": "gcedo",
"author_id": 1871238,
"author_profile": "https://Stackoverflow.com/users/1871238",
"pm_score": 6,
"selected": false,
"text": "<h1>Sticky footer with <code>display: flex</code></h1>\n<p>Solution inspired by <a href=\"https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/\" rel=\"noreferrer\">Philip Walton's sticky footer</a>.</p>\n<h2>Explanation</h2>\n<p>This solution is <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/flex#Browser_compatibility\" rel=\"noreferrer\">valid only for</a>:</p>\n<ul>\n<li>Chrome ≥ 21.0</li>\n<li>Firefox ≥ 20.0</li>\n<li>Internet Explorer ≥ 10</li>\n<li>Safari ≥ 6.1</li>\n</ul>\n<p>It is based on the <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/flex\" rel=\"noreferrer\"><code>flex</code> display</a>, leveraging the <code>flex-grow</code> property, which allows an element to <em>grow</em> in either <strong>height</strong> or <strong>width</strong> (when the <code>flow-direction</code> is set to either <code>column</code> or <code>row</code> respectively), to occupy the extra space in the container.</p>\n<p>We are going to leverage also the <code>vh</code> unit, where <code>1vh</code> is <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/length#Viewport-percentage_lengths\" rel=\"noreferrer\">defined as</a>:</p>\n<blockquote>\n<p>1/100th of the height of the viewport</p>\n</blockquote>\n<p>Therefore a height of <code>100vh</code> it's a concise way to tell an element to span the full viewport's height.</p>\n<p>This is how you would structure your web page:</p>\n<pre><code>----------- body -----------\n----------------------------\n\n---------- footer ----------\n----------------------------\n</code></pre>\n<p>In order to have the footer stick to the bottom of the page, you want the space between the body and the footer to grow as much as it takes to push the footer at the bottom of the page.</p>\n<p>Therefore our layout becomes:</p>\n<pre><code>----------- body -----------\n----------------------------\n\n---------- spacer ----------\n <- This element must grow in height\n----------------------------\n\n---------- footer ----------\n----------------------------\n</code></pre>\n<h2>Implementation</h2>\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-css lang-css prettyprint-override\"><code>body {\n margin: 0;\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\n.spacer {\n flex: 1;\n}\n\n/* make it visible for the purposes of demo */\n.footer {\n height: 50px;\n background-color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body>\n <div class=\"content\">Hello World!</div>\n <div class=\"spacer\"></div>\n <footer class=\"footer\"></footer>\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You can play with it at <a href=\"https://jsfiddle.net/xzchhLjp/\" rel=\"noreferrer\">the JSFiddle</a>.</p>\n<h2>Safari quirks</h2>\n<p>Be aware that Safari has a <a href=\"http://philipwalton.com/articles/normalizing-cross-browser-flexbox-bugs/#minimum-content-sizing-of-flex-items\" rel=\"noreferrer\">flawed implementation of the <code>flex-shrink</code> property</a>, which allows items to shrink more than the minimum height that would be required to display the content.\nTo fix this issue you will have to set the <code>flex-shrink</code> property explicitly to 0 to the <code>.content</code> and the <code>footer</code> in the above example:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.content {\n flex-shrink: 0;\n}\n\n.footer {\n flex-shrink: 0;\n}\n</code></pre>\n<p>Alternatively, change the <code>flex</code> style for the <code>spacer</code> element into:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.spacer {\n flex: 1 0 auto;\n}\n</code></pre>\n<p>This 3-value shorthand style is equivalent to the following full setup:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.spacer {\n flex-grow: 1;\n flex-shrink: 0;\n flex-basis: auto;\n}\n</code></pre>\n<p>Elegantly works everywhere.</p>\n"
},
{
"answer_id": 34823140,
"author": "DevWL",
"author_id": 2179965,
"author_profile": "https://Stackoverflow.com/users/2179965",
"pm_score": 0,
"selected": false,
"text": "<p><strong>jQuery CROSS BROWSER CUSTOM PLUGIN - $.footerBottom()</strong></p>\n\n<p>Or use jQuery like I do, and set your footer height to <code>auto</code> or to <code>fix</code>, whatever you like, it will work anyway. this plugin uses jQuery selectors so to make it work, you will have to include the jQuery library to your file.</p>\n\n<p>Here is how you run the plugin. Import jQuery, copy the code of this custom jQuery plugin and import it after importing jQuery! It is very simple and basic, but important. </p>\n\n<p>When you do it, all you have to do is run this code:</p>\n\n<pre><code>$.footerBottom({target:\"footer\"}); //as html5 tag <footer>.\n// You can change it to your preferred \"div\" with for example class \"footer\" \n// by setting target to {target:\"div.footer\"}\n</code></pre>\n\n<p>there is no need to place it inside the document ready event. It will run well as it is. It will recalculate the position of your footer when the page is loaded and when the window get resized.</p>\n\n<p>Here is the code of the plugin which you do not have to understand. Just know how to implement it. It does the job for you. However, if you like to know how it works, just look through the code. I left comments for you.</p>\n\n<pre><code>//import jQuery library before this script\n</code></pre>\n\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>// Import jQuery library before this script\r\n\r\n// Our custom jQuery Plugin\r\n(function($) {\r\n $.footerBottom = function(options) { // Or use \"$.fn.footerBottom\" or \"$.footerBottom\" to call it globally directly from $.footerBottom();\r\n var defaults = {\r\n target: \"footer\",\r\n container: \"html\",\r\n innercontainer: \"body\",\r\n css: {\r\n footer: {\r\n position: \"absolute\",\r\n left: 0,\r\n bottom: 0,\r\n },\r\n\r\n html: {\r\n position: \"relative\",\r\n minHeight: \"100%\"\r\n }\r\n }\r\n };\r\n\r\n options = $.extend(defaults, options);\r\n\r\n // JUST SET SOME CSS DEFINED IN THE DEFAULTS SETTINGS ABOVE\r\n $(options.target).css({\r\n \"position\": options.css.footer.position,\r\n \"left\": options.css.footer.left,\r\n \"bottom\": options.css.footer.bottom,\r\n });\r\n\r\n $(options.container).css({\r\n \"position\": options.css.html.position,\r\n \"min-height\": options.css.html.minHeight,\r\n });\r\n\r\n function logic() {\r\n var footerOuterHeight = $(options.target).outerHeight(); // Get outer footer height\r\n $(options.innercontainer).css('padding-bottom', footerOuterHeight + \"px\"); // Set padding equal to footer height on body element\r\n $(options.target).css('height', footerOuterHeight + \"!important\"); // Set outerHeight of footer element to ... footer\r\n console.log(\"jQ custom plugin footerBottom runs\"); // Display text in console so ou can check that it works in your browser. Delete it if you like.\r\n };\r\n\r\n // DEFINE WHEN TO RUN FUNCTION\r\n $(window).on('load resize', function() { // Run on page loaded and on window resized\r\n logic();\r\n });\r\n\r\n // RETURN OBJECT FOR CHAINING IF NEEDED - IF NOT DELETE\r\n // return this.each(function() {\r\n // this.checked = true;\r\n // });\r\n // return this;\r\n };\r\n})(jQuery); // End of plugin\r\n\r\n\r\n// USE EXAMPLE\r\n$.footerBottom(); // Run our plugin with all default settings for HTML5</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/* Set your footer CSS to what ever you like it will work anyway */\r\nfooter {\r\n box-sizing: border-box;\r\n height: auto;\r\n width: 100%;\r\n padding: 30px 0;\r\n background-color: black;\r\n color: white;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n\r\n<!-- The structure doesn't matter much, you will always have html and body tag, so just make sure to point to your footer as needed if you use html5, as it should just do nothing run plugin with no settings it will work by default with the <footer> html5 tag -->\r\n<body>\r\n <div class=\"content\">\r\n <header>\r\n <nav>\r\n <ul>\r\n <li>link</li>\r\n <li>link</li>\r\n <li>link</li>\r\n <li>link</li>\r\n <li>link</li>\r\n <li>link</li>\r\n </ul>\r\n </nav>\r\n </header>\r\n\r\n <section>\r\n <p></p>\r\n <p>Lorem ipsum...</p>\r\n </section>\r\n </div>\r\n <footer>\r\n <p>Copyright 2009 Your name</p>\r\n <p>Copyright 2009 Your name</p>\r\n <p>Copyright 2009 Your name</p>\r\n </footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 35310742,
"author": "jjr2000",
"author_id": 3412043,
"author_profile": "https://Stackoverflow.com/users/3412043",
"pm_score": 1,
"selected": false,
"text": "<p>For this question many of the answers I have seen are clunky, hard to implement and inefficient so I thought I'd take a shot at it and come up with my own solution which is just a tiny bit of css and html</p>\n\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-css lang-css prettyprint-override\"><code>html,\r\nbody {\r\n height: 100%;\r\n margin: 0;\r\n}\r\n.body {\r\n min-height: calc(100% - 2rem);\r\n width: 100%;\r\n background-color: grey;\r\n}\r\n.footer {\r\n height: 2rem;\r\n width: 100%;\r\n background-color: yellow;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body>\r\n <div class=\"body\">test as body</div>\r\n <div class=\"footer\">test as footer</div>\r\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>this works by setting the height of the footer and then using css calc to work out the minimum height the page can be with the footer still at the bottom, hope this helps some people :)</p>\n"
},
{
"answer_id": 39199515,
"author": "user1235285",
"author_id": 1235285,
"author_profile": "https://Stackoverflow.com/users/1235285",
"pm_score": 0,
"selected": false,
"text": "<p>An old thread I know, but if you are looking for a responsive solution, this jQuery addition will help: </p>\n\n<pre><code>$(window).on('resize',sticky);\n$(document).bind(\"ready\", function() {\n sticky();\n});\n\nfunction sticky() {\n var fh = $(\"footer\").outerHeight();\n $(\"#push\").css({'height': fh});\n $(\"#wrapper\").css({'margin-bottom': -fh});\n}\n</code></pre>\n\n<p>Full guide can be found here: <a href=\"https://pixeldesigns.co.uk/blog/responsive-jquery-sticky-footer/\" rel=\"nofollow\">https://pixeldesigns.co.uk/blog/responsive-jquery-sticky-footer/</a></p>\n"
},
{
"answer_id": 39449537,
"author": "Ravinder Payal",
"author_id": 2988776,
"author_profile": "https://Stackoverflow.com/users/2988776",
"pm_score": 0,
"selected": false,
"text": "<p>I have created a very simple library <a href=\"https://github.com/ravinderpayal/FooterJS\" rel=\"nofollow\">https://github.com/ravinderpayal/FooterJS</a> </p>\n\n<p>It is very simple in use. After including library, just call this line of code. </p>\n\n<pre><code>footer.init(document.getElementById(\"ID_OF_ELEMENT_CONTAINING_FOOTER\"));\n</code></pre>\n\n<p>Footers can be dynamically changed by recalling above function with different parameter/id. </p>\n\n<pre><code>footer.init(document.getElementById(\"ID_OF_ANOTHER_ELEMENT_CONTAINING_FOOTER\"));\n</code></pre>\n\n<p>Note:- You haven't to alter or add any CSS. Library is dynamic which implies that even if screen is resized after loading page it will reset the position of footer. I have created this library, because CSS solves the problem for a while but when size of display changes significantly,from desktop to tablet or vice versa, they either overlap the content or they no longer remains sticky.</p>\n\n<p>Another solution is CSS Media Queries, but you have to manually write different CSS styles for different size of screens while this library does its work automatically and is supported by all basic JavaScript supporting browser.</p>\n\n<p><strong>Edit</strong>\nCSS solution:</p>\n\n<pre><code>@media only screen and (min-height: 768px) {/* or height/length of body content including footer*/\n /* For mobile phones: */\n #footer {\n width: 100%;\n position:fixed;\n bottom:0;\n }\n}\n</code></pre>\n\n<p>Now, if the height of display is more than your content length, we will make footer fixed to bottom and if not, it will automatically appear in very end of display as you need to scroll to view this.</p>\n\n<p>And, it seems a better solution than JavaScript/library one.</p>\n"
},
{
"answer_id": 44682287,
"author": "Laughing Horse",
"author_id": 6391229,
"author_profile": "https://Stackoverflow.com/users/6391229",
"pm_score": 0,
"selected": false,
"text": "<p>I wasn't having any luck with the solutions suggested on this page before but then finally, this little trick worked. I'll include it as another possible solution.</p>\n\n<pre><code>footer {\n position: fixed;\n right: 0;\n bottom: 0;\n left: 0;\n padding: 1rem;\n background-color: #efefef;\n text-align: center;\n}\n</code></pre>\n"
},
{
"answer_id": 44771365,
"author": "Reggie Pinkham",
"author_id": 2927114,
"author_profile": "https://Stackoverflow.com/users/2927114",
"pm_score": 0,
"selected": false,
"text": "<p>For natural header and footer heights use CSS Flexbox.</p>\n<p><a href=\"https://jsfiddle.net/Lsb6dk14/\" rel=\"nofollow noreferrer\">See JS Fiddle</a>.</p>\n<p><strong>HTML</strong></p>\n<pre><code><body>\n <header>\n ...\n </header>\n <main>\n ...\n </main>\n <footer>\n ...\n </footer>\n</body> \n</code></pre>\n<p><strong>CSS</strong></p>\n<pre><code>html {\n height: 100%;\n}\n\nbody {\n height: 100%;\n min-height: 100vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n margin: 0;\n display: flex;\n flex-direction: column;\n}\n\nmain {\n flex-grow: 1;\n flex-shrink: 0;\n}\n\nheader,\nfooter {\n flex: none;\n}\n</code></pre>\n"
},
{
"answer_id": 45021713,
"author": "Daniel Alsaker",
"author_id": 5872527,
"author_profile": "https://Stackoverflow.com/users/5872527",
"pm_score": 2,
"selected": false,
"text": "<p>I have myself struggled with this sometimes and I always found that the solution with all those div's within each other was a messy solution. \nI just messed around with it a bit, and I personally found out that this works and it certainly is one of the simplest ways:</p>\n\n<pre><code>html {\n position: relative;\n}\n\nhtml, body {\n margin: 0;\n padding: 0;\n min-height: 100%;\n}\n\nfooter {\n position: absolute;\n bottom: 0;\n}\n</code></pre>\n\n<p>What I like about this is that no extra HTML needs to be applied. You can simply add this CSS and then write your HTML as whenever</p>\n"
},
{
"answer_id": 47489319,
"author": "juan Isaza",
"author_id": 2394901,
"author_profile": "https://Stackoverflow.com/users/2394901",
"pm_score": 0,
"selected": false,
"text": "<p>For me the nicest way of displaying it (the footer) is sticking to the bottom but not covering content all the time:</p>\n\n<pre><code>#my_footer {\n position: static\n fixed; bottom: 0\n}\n</code></pre>\n"
},
{
"answer_id": 47640893,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 3,
"selected": false,
"text": "<p>A similar solution to <a href=\"https://stackoverflow.com/a/34146411/8620333\">@gcedo</a> but without the need of adding an intermediate content in order to push the footer down. We can simply add <code>margin-top:auto</code> to the footer and it will be pushed to the bottom of the page regardless his height or the height of the content above.</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-css lang-css prettyprint-override\"><code>body {\r\n display: flex;\r\n flex-direction: column;\r\n min-height: 100vh;\r\n margin:0;\r\n}\r\n\r\n.content {\r\n padding: 50px;\r\n background: red;\r\n}\r\n\r\n.footer {\r\n margin-top: auto;\r\n padding:10px;\r\n background: green;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"content\">\r\n some content here\r\n</div>\r\n<footer class=\"footer\">\r\n some content\r\n</footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 52106754,
"author": "Roger",
"author_id": 558193,
"author_profile": "https://Stackoverflow.com/users/558193",
"pm_score": 0,
"selected": false,
"text": "<p>The flex solutions worked for me as far as making the footer sticky, but unfortunately changing the body to use flex layout made some of our page layouts change, and not for the better. What finally worked for me was:</p>\n\n<pre><code> jQuery(document).ready(function() {\n\n var fht = jQuery('footer').outerHeight(true);\n jQuery('main').css('min-height', \"calc(92vh - \" + fht + \"px)\");\n\n});\n</code></pre>\n\n<p>I got this from ctf0's response at <a href=\"https://css-tricks.com/couple-takes-sticky-footer/\" rel=\"nofollow noreferrer\">https://css-tricks.com/couple-takes-sticky-footer/</a></p>\n"
},
{
"answer_id": 52440647,
"author": "VXp",
"author_id": 2851632,
"author_profile": "https://Stackoverflow.com/users/2851632",
"pm_score": 2,
"selected": false,
"text": "<p>Since the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout\" rel=\"nofollow noreferrer\">Grid</a> solution hasn't been presented yet, here it is, with just two <em>declarations</em> for the <em>parent element</em>, if we take the <code>height: 100%</code> and <code>margin: 0</code> for granted:</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-css lang-css prettyprint-override\"><code>html, body {height: 100%}\r\n\r\nbody {\r\n display: grid; /* generates a block-level grid */\r\n align-content: space-between; /* places an even amount of space between each grid item, with no space at the far ends */\r\n margin: 0;\r\n}\r\n\r\n.content {\r\n background: lightgreen;\r\n /* demo / for default snippet window */\r\n height: 1em;\r\n animation: height 2.5s linear alternate infinite;\r\n}\r\n\r\nfooter {background: lightblue}\r\n\r\n@keyframes height {to {height: 250px}}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"content\">Content</div>\r\n<footer>Footer</footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/align-content\" rel=\"nofollow noreferrer\"><code>align-content: space-between</code></a></li>\n</ul>\n\n<blockquote>\n <p>The items are evenly distributed within the alignment container along\n the cross axis. The spacing between each pair of adjacent items is the\n same. The first item is flush with the main-start edge, and the last\n item is flush with the main-end edge.</p>\n</blockquote>\n"
},
{
"answer_id": 53919076,
"author": "antelove",
"author_id": 7656367,
"author_profile": "https://Stackoverflow.com/users/7656367",
"pm_score": 1,
"selected": false,
"text": "<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-css lang-css prettyprint-override\"><code>div.fixed {\r\n position: fixed;\r\n bottom: 0;\r\n right: 0;\r\n width: 100%;\r\n border: 3px solid #73AD21;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body style=\"height:1500px\">\r\n\r\n <h2>position: fixed;</h2>\r\n\r\n <p>An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>\r\n\r\n <div class=\"fixed\">\r\n This div element has position: fixed;\r\n </div>\r\n\r\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 58892044,
"author": "kiko carisse",
"author_id": 5045446,
"author_profile": "https://Stackoverflow.com/users/5045446",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want it using position fixed, and following you annoyingly on mobile, this seems to be working for me so far.</p>\n\n<pre><code>html {\n min-height: 100%;\n position: relative;\n}\n\n#site-footer {\n position: absolute;\n bottom: 0;\n left: 0;\n width: 100%;\n padding: 6px 2px;\n background: #32383e;\n}\n</code></pre>\n\n<p>Just set the html to <code>min-height: 100%;</code> and <code>position: relative;</code>, then <code>position: absolute; bottom: 0; left: 0;</code> on the footer. I then made sure the footer was the last element in the body.</p>\n\n<p>Let me know if this doesn't work for anyone else, and why. I know these tedious style hacks can behave strangely among various circumstances I'd not thought of.</p>\n"
},
{
"answer_id": 63382499,
"author": "cssyphus",
"author_id": 1447509,
"author_profile": "https://Stackoverflow.com/users/1447509",
"pm_score": 0,
"selected": false,
"text": "<h1>REACT-friendly solution - (no spacer div required)</h1>\n<p>Chris Coyier (the venerable CSS-Tricks website) has kept his <a href=\"https://css-tricks.com/couple-takes-sticky-footer/\" rel=\"nofollow noreferrer\">page on the Sticky-Footer</a> up-to-date, with at least FIVE methods now for creating a sticky footer, including using FlexBox and CSS-Grid.</p>\n<p>Why is this important? Because, for me, the earlier/older methods I used for years did not work with React - I had to use Chris' flexbox solution - which was <em><strong>easy</strong></em> and <em><strong>worked</strong></em>.</p>\n<p>Below is his <a href=\"https://css-tricks.com/couple-takes-sticky-footer/#there-is-flexbox\" rel=\"nofollow noreferrer\">CSS-Tricks flexbox Sticky Footer</a> - just look at the code below, it cannot possibly be simpler.</p>\n<p><em>(The (below) StackSnippet example does not perfectly render the bottom of the example. The footer is shown extending past the bottom of the screen, which does not happen in real life.)</em></p>\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-css lang-css prettyprint-override\"><code>html,body{height: 100%;}\nbody {display:flex; flex-direction:column;}\n.content {flex: 1 0 auto;} /* flex: grow / shrink / flex-basis; */\n.footer {flex-shrink: 0;}\n\n/* ---- BELOW IS ONLY for demo ---- */\n.footer{background: palegreen;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body>\n <div class=\"content\">Page Content - height expands to fill space</div>\n <footer class=\"footer\">Footer Content</footer>\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Chris also demonstrates this <a href=\"https://css-tricks.com/couple-takes-sticky-footer/#there-is-grid\" rel=\"nofollow noreferrer\">CSS-Grid solution</a> for those who prefer grid.</p>\n<hr />\n<h3>References:</h3>\n<p><a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\" rel=\"nofollow noreferrer\">CSS-Tricks - A Complete Guide to Flexbox</a></p>\n"
},
{
"answer_id": 65774517,
"author": "Juliano Suman Curti",
"author_id": 14145197,
"author_profile": "https://Stackoverflow.com/users/14145197",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at <a href=\"http://1linelayouts.glitch.me/\" rel=\"nofollow noreferrer\">http://1linelayouts.glitch.me/</a>, example 4. Una Kravets nails this problem.</p>\n<p>This creates a 3 layer page with header, main and footer.</p>\n<p>-Your footer will always stay at the bottom, and use space to fit the content;</p>\n<p>-Your header will always stay at the top, and use space to fit the content;</p>\n<p>-Your main will always use all the available remaining space (remaining fraction of space), enough to fill the screen, if need.</p>\n<h2>HTML</h2>\n<pre><code><div class="parent">\n <header class="blue section" contenteditable>Header</header>\n <main class="coral section" contenteditable>Main</main>\n <footer class="purple section" contenteditable>Footer Content</footer>\n</div>\n \n</code></pre>\n<h2>CSS</h2>\n<pre><code>.parent {\n display: grid;\n height: 95vh; /* no scroll bars if few content */\n grid-template-rows: auto 1fr auto;\n}\n \n</code></pre>\n"
},
{
"answer_id": 67166444,
"author": "siaeva",
"author_id": 3494114,
"author_profile": "https://Stackoverflow.com/users/3494114",
"pm_score": 2,
"selected": false,
"text": "<p>Just invented a very simple solution that worked great for me. You just wrap all page content except for the footer within in a div, and then set the min-height to 100% of the viewpoint minus the height of the footer. No need for absolute positioning on the footer or multiple wrapper divs.</p>\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-css lang-css prettyprint-override\"><code>.page-body {min-height: calc(100vh - 400px);} /*Replace 400px with your footer height*/</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 67828478,
"author": "Matt",
"author_id": 10266312,
"author_profile": "https://Stackoverflow.com/users/10266312",
"pm_score": 1,
"selected": false,
"text": "<p>On my sites I always use:</p>\n<pre><code>position: fixed;\n</code></pre>\n<p>...in my CSS for a footer. That anchors it to the bottom of the page.</p>\n"
},
{
"answer_id": 69988420,
"author": "DINA TAKLIT",
"author_id": 9039646,
"author_profile": "https://Stackoverflow.com/users/9039646",
"pm_score": 0,
"selected": false,
"text": "<p>A quick easy solution by using flex</p>\n<ul>\n<li>Give the <code>html</code> and <code>body</code> a height of <code>100%</code></li>\n</ul>\n<pre class=\"lang-css prettyprint-override\"><code>html,\nbody {\n width: 100%;\n height: 100%;\n}\n</code></pre>\n<ul>\n<li>Display the body as <code>flex</code> with <code>column</code> direction:</li>\n</ul>\n<pre class=\"lang-css prettyprint-override\"><code>body { \n min-height: 100%;\n display: flex;\n flex-direction: column;\n}\n</code></pre>\n<ul>\n<li>Add <code>flex-grow: 1</code> for the main</li>\n</ul>\n<pre class=\"lang-css prettyprint-override\"><code>main {\n flex-grow: 1;\n}\n</code></pre>\n<blockquote>\n<p><code>flex-grow</code> specifies how much of the remaining space in the flex container should be assigned to the item (the flex grow factor).</p>\n</blockquote>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>*, \n*::after,\n*::before{\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\nhtml,\nbody {\n width: 100%;\n height: 100%;\n}\n\nbody {\n min-height: 100%;\n display: flex;\n flex-direction: column;\n}\n\nmain {\n flex-grow: 1;\n}\n\nfooter{\n background-color: black;\n color: white;\n padding: 1rem 0;\n display: flex; \n justify-content: center;\n align-items: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body> \n <main>\n <section >\n Hero\n </section>\n </main>\n\n <footer >\n <div>\n <p > &copy; Copyright 2021</p>\n </div>\n </footer>\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 73325579,
"author": "Shubham Sarda",
"author_id": 7846238,
"author_profile": "https://Stackoverflow.com/users/7846238",
"pm_score": 0,
"selected": false,
"text": "<p>Keeping your <code><main></code> as min-height 90vh will solve your problem forever.\nHere is the base structure that will help you follow semantics and cover entire page.</p>\n<p><strong>Step 1:</strong> Keep everything inside the main tag except the header and footer.</p>\n<pre><code><body>\n <header>\n <!╌ nav, logo ╌> \n </header>\n <main>\n <!╌ section and div ╌> \n </main>\n <footer>\n <!╌ nav, logo ╌>\n </footer>\n</body>\n</code></pre>\n<p><strong>Step 2:</strong> Add min-height: 90vh for main</p>\n<pre><code>main{\n min-height: 90vh;\n}\n</code></pre>\n<p>Usually, header and footer are 70px minimum in height so this case works well, tried and tested!</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] | I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case. | To get a sticky footer:
1. Have a `<div>` with `class="wrapper"` for your content.
2. Right **before** the closing `</div>` of the `wrapper` place the
`<div class="push"></div>`.
3. Right **after** the closing `</div>` of the `wrapper` place the
`<div class="footer"></div>`.
```css
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
height: 142px; /* .push must be the same height as .footer */
}
``` |
42,323 | <p>I have the next function:</p>
<pre><code>function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
// If the real width is bigger than width parameter
images[i].style.width=width;
//}
}
}
</code></pre>
<p>I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. </p>
<hr>
<p><code>images[i].offsetWidth</code> returns 111 for an image of 109px width. Is this because 1px each side border? </p>
| [
{
"answer_id": 42331,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 2,
"selected": false,
"text": "<p>Here is, hopefully, enough sample code to give you what you want:</p>\n\n<pre><code>var myImage = document.getElementById(\"myImagesId\");\nvar imageWidth = myImage.offsetWidth;\nvar imageHeight = myImage.offsetHeight;\n</code></pre>\n\n<p>That should give you the numbers you need to derive the solution you want. I think you can write the rest of the code yourself. :)</p>\n\n<hr>\n\n<p>EDIT: Here, I couldn't help myself - is this what you are after?</p>\n\n<pre><code>function setImagesWidth(id,width) {\n var images = document.getElementById(id).getElementsByTagName(\"img\");\n for(var i = 0; i < images.length;i++) {\n if(images[i].offsetWidth > width) {\n images[i].style.width= (width + \"px\");\n }\n } \n}\n</code></pre>\n"
},
{
"answer_id": 42362,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 0,
"selected": false,
"text": "<p>Careful, it looks like you might rather want <code>clientWidth</code>:</p>\n\n<p><a href=\"http://developer.mozilla.org/en/Determining_the_dimensions_of_elements\" rel=\"nofollow noreferrer\">http://developer.mozilla.org/en/Determining_the_dimensions_of_elements</a></p>\n"
},
{
"answer_id": 42381,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 0,
"selected": false,
"text": "<p>EDIT: Can i accept somehow this answer as the final one?</p>\n\n<p>Since offsetWidth does not return any unit, the <em>.px</em> ending must be concatenated for the css attribute.</p>\n\n<pre><code>// width in pixels\nfunction setImagesWidth(id,width) {\n var images = document.getElementById(id).getElementsByTagName(\"img\");\n for(var i = 0; i < images.length;i++) {\n if(images[i].offsetWidth > width) {\n images[i].style.width= (width+\".px\"); \n } \n } \n}\n</code></pre>\n"
},
{
"answer_id": 42494,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 2,
"selected": true,
"text": "<p>@Sergio del Amo: Indeed, if you check out my link you'll see that you want <code>clientWidth</code> instead.</p>\n\n<p>@Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the \"px\" suffix, so let's go with this, including the <code>clientWidth</code> change:</p>\n\n<pre><code>// width in pixels\nfunction setImagesWidth(id, width)\n{\n var images = document.getElementById(id).getElementsByTagName(\"img\");\n var newWidth = width + \"px\";\n for (var i = 0; i < images.length; ++i)\n {\n if (images[i].clientWidth > width)\n {\n images[i].style.width = newWidth;\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 28289783,
"author": "Tomáš Zato",
"author_id": 607407,
"author_profile": "https://Stackoverflow.com/users/607407",
"pm_score": 0,
"selected": false,
"text": "<p>Just in case you, the reader, came here from google looking for a way to tell what is actual image <em>file</em> pixel width and height, this is how:</p>\n\n<pre><code>var img = new Image(\"path...\");\nvar width = image.naturalWidth;\nvar height = image.naturalHeight;\n</code></pre>\n\n<p>This becomes quite usefull when dealing with all kinds of drawing on scaled images.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> var img = document.getElementById(\"img\");\r\n var width = img.naturalWidth;\r\n var height = img.naturalHeight;\r\n document.getElementById(\"info\").innerHTML = \"HTML Dimensions: \"+img.width+\" x \"+img.height + \r\n \"\\nReal pixel dimensions:\"+ \r\n width+\" x \"+height; </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><img id=\"img\" src=\"http://upload.wikimedia.org/wikipedia/commons/0/03/Circle-withsegments.svg\" width=\"100\">\r\n\r\n<pre id=\"info\">\r\n\r\n</pre></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I have the next function:
```
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
// If the real width is bigger than width parameter
images[i].style.width=width;
//}
}
}
```
I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework.
---
`images[i].offsetWidth` returns 111 for an image of 109px width. Is this because 1px each side border? | @Sergio del Amo: Indeed, if you check out my link you'll see that you want `clientWidth` instead.
@Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the `clientWidth` change:
```
// width in pixels
function setImagesWidth(id, width)
{
var images = document.getElementById(id).getElementsByTagName("img");
var newWidth = width + "px";
for (var i = 0; i < images.length; ++i)
{
if (images[i].clientWidth > width)
{
images[i].style.width = newWidth;
}
}
}
``` |
42,342 | <p>Sometimes IE6 will render the text of a <code><ul></code> list the same color as the background color. If you select it, they show back up, or if you scroll the page up and back down.</p>
<p>It is obviously a rendering bug, but I was wondering if anyone knows of a workaround to make it reliable?</p>
| [
{
"answer_id": 42346,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried explicitly setting a line-height? For some reason this seems to be the solution to a great many IE6 rendering bugs!</p>\n\n<p>e.g.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.mylist {\n line-height: 1.6em;\n}\n</code></pre>\n"
},
{
"answer_id": 42352,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 2,
"selected": true,
"text": "<p>try giving it hasLayout with</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>zoom: 1\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | Sometimes IE6 will render the text of a `<ul>` list the same color as the background color. If you select it, they show back up, or if you scroll the page up and back down.
It is obviously a rendering bug, but I was wondering if anyone knows of a workaround to make it reliable? | try giving it hasLayout with
```css
zoom: 1
``` |
42,345 | <p>How can I determine if a string is an IP address? Either <em>IPv4</em> or <em>IPv6</em>?</p>
<p>What is the least and most number of characters?</p>
<p>I assume this would be a <strong>regex</strong> answer.</p>
| [
{
"answer_id": 42359,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>For IPv4 you can use this regular expression.</p>\n\n<pre><code>\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\n</code></pre>\n\n<p>It looks quite complex but it works by limiting each quad to the numbers 0-255.</p>\n"
},
{
"answer_id": 42376,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 0,
"selected": false,
"text": "<p>Since half of that regex handles the fact that the last segment doesn't have a period at the end, you could cut it in half if you tack a '.' to the end of your possible IP address.</p>\n\n<p>Something like this:</p>\n\n<pre><code>bool IsValidIPAddress(string possibleIP){\n CrazyRegex = \\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){4}\\b\n return Regex.Match(possibleIP+'.', CrazyRegex)\n}\n</code></pre>\n"
},
{
"answer_id": 42384,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>@unsliced that is correct however it will of course depend on implementation, if you are parsing an IP from a user visiting your site then your are fine to use regex as it SHOULD be in x.x.x.x format.</p>\n\n<p>For IPv6 you could use this</p>\n\n<pre><code>[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}\n</code></pre>\n\n<p>however it does not catch everything because with IPv6 it is much more complicated, acording to wikipedia all of the following examples are technicaly correct however the regex above will only catch the ones with a *</p>\n\n<pre><code>2001:0db8:0000:0000:0000:0000:1428:57ab*\n2001:0db8:0000:0000:0000::1428:57ab*\n2001:0db8:0:0:0:0:1428:57ab*\n2001:0db8:0:0::1428:57ab\n2001:0db8::1428:57ab\n2001:db8::1428:57ab\n</code></pre>\n"
},
{
"answer_id": 42393,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 3,
"selected": false,
"text": "<p>In .NET there's an IPAddress type which has a handy method <a href=\"http://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse.aspx\" rel=\"noreferrer\">TryParse</a>.</p>\n\n<p>Example: </p>\n\n<pre><code>if(System.Net.IPAddress.TryParse(PossibleIPAddress, validatedIPAddress)){\n //validatedIPAddress is good\n}\n\n// or more simply:\nbool IsValidIPAddress(string possibleIP){\n return System.Net.IPAddress.TryParse(PossibleIPAddress, null)\n}\n</code></pre>\n"
},
{
"answer_id": 42413,
"author": "Niniki",
"author_id": 4155,
"author_profile": "https://Stackoverflow.com/users/4155",
"pm_score": 3,
"selected": false,
"text": "<p>I've done this before, but I like Raymond Chen's post at:</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/05/22/603788.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2006/05/22/603788.aspx</a></p>\n\n<p>Where he basically advocates using regexes for what they're good at: parsing out the tokens. Then evaluate the results. His example:</p>\n\n<pre><code>function isDottedIPv4(s)\n{\n var match = s.match(/^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/);\n return match != null &&\n match[1] <= 255 && match[2] <= 255 &&\n match[3] <= 255 && match[4] <= 255;\n}\n</code></pre>\n\n<p>It's much easier to look at that and grok what it's supposed to be doing.</p>\n"
},
{
"answer_id": 42584,
"author": "Dough",
"author_id": 4451,
"author_profile": "https://Stackoverflow.com/users/4451",
"pm_score": -1,
"selected": false,
"text": "<p>IPv4 becomes: <code>/\\d\\d?\\d?.\\d\\d?\\d?.\\d\\d?\\d?.\\d\\d?\\d?/</code></p>\n\n<p>I'm not sure about the IPv6 rules.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | How can I determine if a string is an IP address? Either *IPv4* or *IPv6*?
What is the least and most number of characters?
I assume this would be a **regex** answer. | In .NET there's an IPAddress type which has a handy method [TryParse](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse.aspx).
Example:
```
if(System.Net.IPAddress.TryParse(PossibleIPAddress, validatedIPAddress)){
//validatedIPAddress is good
}
// or more simply:
bool IsValidIPAddress(string possibleIP){
return System.Net.IPAddress.TryParse(PossibleIPAddress, null)
}
``` |
42,386 | <p>Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?</p>
<pre><code>//pseudo-codeish
string s = Coalesce(string1, string2, string3);
</code></pre>
<p>or, more generally,</p>
<pre><code>object obj = Coalesce(obj1, obj2, obj3, ...objx);
</code></pre>
| [
{
"answer_id": 42387,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>the <strong>??</strong> operator.</p>\n\n<pre><code>string a = nullstring ?? \"empty!\";\n</code></pre>\n"
},
{
"answer_id": 42397,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 4,
"selected": false,
"text": "<p>As Darren Kopp said.</p>\n\n<p>Your statement</p>\n\n<pre><code>object obj = Coalesce(obj1, obj2, obj3, ...objx);\n</code></pre>\n\n<p>Can be written like this:</p>\n\n<pre><code>object obj = obj1 ?? obj2 ?? obj3 ?? ... objx;\n</code></pre>\n\n<p>to put it in other words:</p>\n\n<pre><code>var a = b ?? c;\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>var a = b != null ? b : c;\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4438/"
] | Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?
```
//pseudo-codeish
string s = Coalesce(string1, string2, string3);
```
or, more generally,
```
object obj = Coalesce(obj1, obj2, obj3, ...objx);
``` | As Darren Kopp said.
Your statement
```
object obj = Coalesce(obj1, obj2, obj3, ...objx);
```
Can be written like this:
```
object obj = obj1 ?? obj2 ?? obj3 ?? ... objx;
```
to put it in other words:
```
var a = b ?? c;
```
is equivalent to
```
var a = b != null ? b : c;
``` |
42,395 | <p>How do you write the syntax for a While loop?</p>
<h2>C<code>#</code></h2>
<pre><code>int i = 0;
while (i != 10)
{
Console.WriteLine(i);
i++;
}
</code></pre>
<h2>VB.Net</h2>
<pre><code>Dim i As Integer = 0
While i <> 10
Console.WriteLine(i)
i += 1
End While
</code></pre>
<h2>PHP</h2>
<pre><code><?php
while(CONDITION)
{
//Do something here.
}
?>
<?php
//MySQL query stuff here
$result = mysql_query($sql, $link) or die("Opps");
while($row = mysql_fetch_assoc($result))
{
$_SESSION['fName'] = $row['fName'];
$_SESSION['lName'] = $row['lName'];
//...
}
?>
</code></pre>
<h2>Python</h2>
<pre><code>i = 0
while i != 10:
print i
i += 1
</code></pre>
| [
{
"answer_id": 42409,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 4,
"selected": true,
"text": "<p>In PHP a while loop will look like this:</p>\n\n<pre><code><?php\nwhile(CONDITION)\n{\n//Do something here.\n}\n?>\n</code></pre>\n\n<p>A real world example of this might look something like this</p>\n\n<pre><code><?php\n//MySQL query stuff here\n$result = mysql_query($sql, $link) or die(\"Opps\");\nwhile($row = mysql_fetch_assoc($result))\n{\n$_SESSION['fName'] = $row['fName'];\n$_SESSION['lName'] = $row['lName'];\n//...\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 42420,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": false,
"text": "<p>There may be a place for this type of question, but only if the answer is correct. <code>While</code> isn't a keyword in C#. <code>while</code> is. Also, the space between the <code>!</code> and <code>=</code> isn't valid. Try:</p>\n\n<pre><code>int i=0; \nwhile (i != 10)\n{ \n Console.WriteLine(i); \n i++; \n}\n</code></pre>\n\n<p>While I'm here, <a href=\"/questions/tagged/python\">Python</a>:</p>\n\n<pre><code>i = 0\nwhile i != 10:\n print i\n i += 1\n</code></pre>\n"
},
{
"answer_id": 1134686,
"author": "SingleNegationElimination",
"author_id": 65696,
"author_profile": "https://Stackoverflow.com/users/65696",
"pm_score": 0,
"selected": false,
"text": "<h2>TCL</h2>\n\n<pre><code>set i 0\nwhile {$i != 10} {\n puts $i\n incr i\n}\n</code></pre>\n\n<p>C++, C, JavaScript, Java and a myriad of other C-like languages all look exactly the same as C#, except in the way that they write the output to the console, or possibly the way you create the variable <code>i</code>. Answering that would belong in some other question.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] | How do you write the syntax for a While loop?
C`#`
----
```
int i = 0;
while (i != 10)
{
Console.WriteLine(i);
i++;
}
```
VB.Net
------
```
Dim i As Integer = 0
While i <> 10
Console.WriteLine(i)
i += 1
End While
```
PHP
---
```
<?php
while(CONDITION)
{
//Do something here.
}
?>
<?php
//MySQL query stuff here
$result = mysql_query($sql, $link) or die("Opps");
while($row = mysql_fetch_assoc($result))
{
$_SESSION['fName'] = $row['fName'];
$_SESSION['lName'] = $row['lName'];
//...
}
?>
```
Python
------
```
i = 0
while i != 10:
print i
i += 1
``` | In PHP a while loop will look like this:
```
<?php
while(CONDITION)
{
//Do something here.
}
?>
```
A real world example of this might look something like this
```
<?php
//MySQL query stuff here
$result = mysql_query($sql, $link) or die("Opps");
while($row = mysql_fetch_assoc($result))
{
$_SESSION['fName'] = $row['fName'];
$_SESSION['lName'] = $row['lName'];
//...
}
?>
``` |
42,396 | <p>Here's the code from the ascx that has the repeater:</p>
<pre><code><asp:Repeater ID="ListOfEmails" runat="server" >
<HeaderTemplate><h3>A sub-header:</h3></HeaderTemplate>
<ItemTemplate>
[Some other stuff is here]
<asp:Button ID="removeEmail" runat="server" Text="X" ToolTip="remove" />
</ItemTemplate>
</asp:Repeater>
</code></pre>
<p>And in the codebehind for the repeater's databound and events:</p>
<pre><code>Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound
If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button)
removeEmail.CommandArgument = e.Item.ItemIndex.ToString()
AddHandler removeEmail.Click, AddressOf removeEmail_Click
AddHandler removeEmail.Command, AddressOf removeEmail_Command
End If
End Sub
Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Write("<h1>click</h1>")
End Sub
Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
Response.Write("<h1>command</h1>")
End Sub
</code></pre>
<p>Neither the click or command is getting called, what am I doing wrong?</p>
| [
{
"answer_id": 42404,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an experiment for you to try:</p>\n\n<p>Set a breakpoint on ListOfEmails_ItemDataBound and see if it's being called for postbacks.</p>\n"
},
{
"answer_id": 42412,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": true,
"text": "<p>Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the <code>Repeater.ItemCommand</code> Event.</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeater.itemcommand\" rel=\"nofollow noreferrer\"><code>ItemCommand</code></a> contains <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeatercommandeventargs\" rel=\"nofollow noreferrer\"><code>RepeaterCommandEventArgs</code></a> which has two important fields:</p>\n\n<ul>\n<li>CommandName</li>\n<li>CommandArgument</li>\n</ul>\n\n<p>So, a trivial example: </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)\n {\n // Stuff to databind\n Button myButton = (Button)e.Item.FindControl(\"myButton\");\n\n myButton.CommandName = \"Add\";\n myButton.CommandArgument = \"Some Identifying Argument\";\n }\n}\n\nvoid rptr_ItemCommand(object source, RepeaterCommandEventArgs e)\n{\n if (e.CommandName == \"Add\")\n {\n // Do your event\n }\n}\n</code></pre>\n"
},
{
"answer_id": 42427,
"author": "Craig",
"author_id": 2047,
"author_profile": "https://Stackoverflow.com/users/2047",
"pm_score": 2,
"selected": false,
"text": "<p>You need to handle the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemcommand.aspx\" rel=\"nofollow noreferrer\">ItemCommand event</a> on your Repeater. Here's <a href=\"http://www.developer.com/net/asp/article.php/3609466\" rel=\"nofollow noreferrer\">an example</a>.</p>\n\n<p>Then, your button clicks will be handled by the ListOfEmails_ItemCommand method. I don't think wiring up the Click or Command event (of the button) in ItemDataBound will work.</p>\n"
},
{
"answer_id": 4220093,
"author": "catfood",
"author_id": 12802,
"author_profile": "https://Stackoverflow.com/users/12802",
"pm_score": 0,
"selected": false,
"text": "<p>You know what's frustrating about this?</p>\n\n<p>If you specify an OnClick in that asp:Button tag, the build <em>will</em> verify that the named method exists in the codebehind class, and report an error if it doesn't... even though that method will never get called.</p>\n"
},
{
"answer_id": 4996126,
"author": "Piotr Latusek",
"author_id": 562786,
"author_profile": "https://Stackoverflow.com/users/562786",
"pm_score": 2,
"selected": false,
"text": "<p>If you're planning to use ItemCommand event, make sure you register to ItemCommand event in Page_Init not in Page_Load.</p>\n\n<pre><code>protected void Page_Init(object sender, EventArgs e)\n{\n // rptr is your repeater's name\n rptr.ItemCommand += new RepeaterCommandEventHandler(rptr_ItemCommand);\n}\n</code></pre>\n\n<p>I am not sure why it wasn't working for me with this event registered in Page_Load but moving it to Page_Init helped.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | Here's the code from the ascx that has the repeater:
```
<asp:Repeater ID="ListOfEmails" runat="server" >
<HeaderTemplate><h3>A sub-header:</h3></HeaderTemplate>
<ItemTemplate>
[Some other stuff is here]
<asp:Button ID="removeEmail" runat="server" Text="X" ToolTip="remove" />
</ItemTemplate>
</asp:Repeater>
```
And in the codebehind for the repeater's databound and events:
```
Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound
If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button)
removeEmail.CommandArgument = e.Item.ItemIndex.ToString()
AddHandler removeEmail.Click, AddressOf removeEmail_Click
AddHandler removeEmail.Command, AddressOf removeEmail_Command
End If
End Sub
Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Write("<h1>click</h1>")
End Sub
Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
Response.Write("<h1>command</h1>")
End Sub
```
Neither the click or command is getting called, what am I doing wrong? | Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the `Repeater.ItemCommand` Event.
[`ItemCommand`](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeater.itemcommand) contains [`RepeaterCommandEventArgs`](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeatercommandeventargs) which has two important fields:
* CommandName
* CommandArgument
So, a trivial example:
```cs
void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
// Stuff to databind
Button myButton = (Button)e.Item.FindControl("myButton");
myButton.CommandName = "Add";
myButton.CommandArgument = "Some Identifying Argument";
}
}
void rptr_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Add")
{
// Do your event
}
}
``` |
42,416 | <p>I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with : 'Thread (nil) may have been prematurely finalized'.</p>
| [
{
"answer_id": 42431,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "<p>here's a link to it on the ubuntu site:</p>\n\n<p><a href=\"http://packages.ubuntu.com/intrepid/libgluezilla\" rel=\"nofollow noreferrer\">http://packages.ubuntu.com/intrepid/libgluezilla</a></p>\n\n<p>there is a download section at the bottom for a deb package</p>\n"
},
{
"answer_id": 42613,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 0,
"selected": false,
"text": "<p>After installing the DEB that John pointed to, my app crashes... Is this because the deb is for the wrong Ubuntu (8.08 rather than 8.04)? It appears to be the correct version of libgluezilla for the version of Mono (everything is. 1.9.1)...</p>\n\n<p>Here is what I get when I try to run the application with </p>\n\n<pre>\n$MONO_LOG_LEVEL=debug mono TestbedCSharp.exe\n\n\nMono-INFO: Assembly Loader probing location: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll'.\nMono-INFO: Image addref Mono.Mozilla 0x8514cb0 -> /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll 0x8514590: 2\n\nMono-INFO: Assembly Ref addref Mono.Mozilla 0x8514cb0 -> mscorlib 0x823ba30: 10\n\nMono-INFO: Assembly Mono.Mozilla 0x8514cb0 added to domain TestbedCSharp.exe, ref_count=1\n\nMono-INFO: AOT failed to load AOT module /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.so: /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.so: cannot open shared object file: No such file or directory\n\nMono-INFO: Assembly Loader loaded assembly from location: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll'.\nMono-INFO: Config attempting to parse: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.config'.\nMono-INFO: Config attempting to parse: '/etc/mono/assemblies/Mono.Mozilla/Mono.Mozilla.config'.\nMono-INFO: Config attempting to parse: '/home/kris/.mono/assemblies/Mono.Mozilla/Mono.Mozilla.config'.\nMono-INFO: Assembly Ref addref System.Windows.Forms 0x82880d8 -> Mono.Mozilla 0x8514cb0: 2\n\nMono-INFO: Assembly Ref addref Mono.Mozilla 0x8514cb0 -> System 0x8290908: 5\n\nMono-INFO: DllImport attempting to load: 'gluezilla'.\nMono-INFO: DllImport loading location: 'libgluezilla.so'.\nMono-INFO: Searching for 'gluezilla_init'.\nMono-INFO: Probing 'gluezilla_init'.\nMono-INFO: Found as 'gluezilla_init'.\n\n** (TestbedCSharp.exe:22700): WARNING **: Thread (nil) may have been prematurely finalized\n</pre>\n"
},
{
"answer_id": 67689,
"author": "jldugger",
"author_id": 9947,
"author_profile": "https://Stackoverflow.com/users/9947",
"pm_score": 3,
"selected": true,
"text": "<pre><code>apt-cache search libgluezilla\nlibmono-mozilla0.1-cil - Mono Mozilla library\n</code></pre>\n\n<p>From the package description: </p>\n\n<pre><code>Description: Mono Mozilla library\n Mono is a platform for running and developing applications based on the\n ECMA/ISO Standards. Mono is an open source effort led by Novell.\n Mono provides a complete CLR (Common Language Runtime) including compiler and\n runtime, which can produce and execute CIL (Common Intermediate Language)\n bytecode (aka assemblies), and a class library.\n .\n This package contains the implementation of the WebControl class based on the\n Mozilla engine using libgluezilla.\nHomepage: http://www.mono-project.com/\n</code></pre>\n\n<p>You'll probably need to uninstall anything that came in from intrepid without being properly backported.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] | I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with : 'Thread (nil) may have been prematurely finalized'. | ```
apt-cache search libgluezilla
libmono-mozilla0.1-cil - Mono Mozilla library
```
From the package description:
```
Description: Mono Mozilla library
Mono is a platform for running and developing applications based on the
ECMA/ISO Standards. Mono is an open source effort led by Novell.
Mono provides a complete CLR (Common Language Runtime) including compiler and
runtime, which can produce and execute CIL (Common Intermediate Language)
bytecode (aka assemblies), and a class library.
.
This package contains the implementation of the WebControl class based on the
Mozilla engine using libgluezilla.
Homepage: http://www.mono-project.com/
```
You'll probably need to uninstall anything that came in from intrepid without being properly backported. |
42,422 | <p>Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak.</p>
<p>EG:</p>
<pre><code>try
dim mySQL as new sqlcommand(sSQL, cnInput)
// do a sql execute and read the data
mySQL = new sqlcommand(sSQLdifferent, cnInput)
// do sql execute and read the data
catch ...
finally
if mysql isnot nothing then
mysql.dispose
mysql = nothing
end if
</code></pre>
<p>EDIT: put try catch in to avoid the comments about not using them</p>
| [
{
"answer_id": 42434,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "<p>Garbage collection will gather up the first new when it is run.</p>\n\n<p>Only the second one you purposely dispose in the Finally block. The first one will be disposed of the next time the garbage collection is run.</p>\n\n<p>I do not think this is a good idea. If the first command is not closed correctly it is possible you would have an open connection to the database and it will not be disposed.</p>\n\n<p>A better way would be to dispose the first command after you are done using it, and then to reuse it.</p>\n"
},
{
"answer_id": 42436,
"author": "Campbell",
"author_id": 942,
"author_profile": "https://Stackoverflow.com/users/942",
"pm_score": 0,
"selected": false,
"text": "<p>No, the garbage collector will find the old version of mySql and deallocate it in due course.</p>\n\n<p>The garbage collector should pick up anything that's been dereferenced as long as it hasn't been moved into the Large Object Heap.</p>\n"
},
{
"answer_id": 42445,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<p>Just to extend what Longhorn213 said, here's the code for it:</p>\n\n<pre><code>Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)\n ' do stuff'\nEnd Using\n\nUsing mysql as SqlCommand = new SqlCommand(otherSql, cnInput)\n ' do other stuff'\nEnd Using\n</code></pre>\n\n<p>(edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. <a href=\"http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx</a></p>\n"
},
{
"answer_id": 42453,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>Whilst garbage collection will clean up after you <em>eventually</em> the dispose pattern is there to help the system release any resources associated with the object sooner, So you should call dispose once you are done with the object before re-assigning to it.</p>\n"
},
{
"answer_id": 42454,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "<p>Uh, to all those people saying \"it's OK, don't worry about it, the GC will handle it...\" the whole <em>point</em> of the <code>Dispose</code> pattern is to handle those resources the GC <em>can't</em> dispose of. So if an object has a <code>Dispose</code> method, you'd better call it when you're done with it!</p>\n\n<p>In summary, Longhorn213 is correct, listen to him.</p>\n"
},
{
"answer_id": 42501,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p>One thing I never worked out - If I have a class implementing <code>IDisposable</code>, but I never actually dispose it myself, I just leave it hanging around for the GC, will the GC actually call <code>Dispose</code> for me?</p>\n"
},
{
"answer_id": 43118,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Be careful. If you have to do a lot of these in a loop it can be slow. It's much better to just update the .CommandText property of the same command, like this (also, you can clean up the syntax a little):</p>\n\n<pre><code>Using mysql as New SqlCommand(sSql, cnInput)\n ' do stuff'\n\n mySql.CommandText = otherSql\n\n 'do other stuff'\nEnd Using\n</code></pre>\n\n<p>Of course, that only works if the first command is no longer active. If you're still in the middle of going through a datareader then you better create a new command.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2357/"
] | Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak.
EG:
```
try
dim mySQL as new sqlcommand(sSQL, cnInput)
// do a sql execute and read the data
mySQL = new sqlcommand(sSQLdifferent, cnInput)
// do sql execute and read the data
catch ...
finally
if mysql isnot nothing then
mysql.dispose
mysql = nothing
end if
```
EDIT: put try catch in to avoid the comments about not using them | Just to extend what Longhorn213 said, here's the code for it:
```
Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)
' do stuff'
End Using
Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput)
' do other stuff'
End Using
```
(edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. <http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx> |
42,428 | <p>X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions.</p>
<p>Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X?</p>
<p>I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.</p>
| [
{
"answer_id": 42434,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "<p>Garbage collection will gather up the first new when it is run.</p>\n\n<p>Only the second one you purposely dispose in the Finally block. The first one will be disposed of the next time the garbage collection is run.</p>\n\n<p>I do not think this is a good idea. If the first command is not closed correctly it is possible you would have an open connection to the database and it will not be disposed.</p>\n\n<p>A better way would be to dispose the first command after you are done using it, and then to reuse it.</p>\n"
},
{
"answer_id": 42436,
"author": "Campbell",
"author_id": 942,
"author_profile": "https://Stackoverflow.com/users/942",
"pm_score": 0,
"selected": false,
"text": "<p>No, the garbage collector will find the old version of mySql and deallocate it in due course.</p>\n\n<p>The garbage collector should pick up anything that's been dereferenced as long as it hasn't been moved into the Large Object Heap.</p>\n"
},
{
"answer_id": 42445,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<p>Just to extend what Longhorn213 said, here's the code for it:</p>\n\n<pre><code>Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)\n ' do stuff'\nEnd Using\n\nUsing mysql as SqlCommand = new SqlCommand(otherSql, cnInput)\n ' do other stuff'\nEnd Using\n</code></pre>\n\n<p>(edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. <a href=\"http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx</a></p>\n"
},
{
"answer_id": 42453,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>Whilst garbage collection will clean up after you <em>eventually</em> the dispose pattern is there to help the system release any resources associated with the object sooner, So you should call dispose once you are done with the object before re-assigning to it.</p>\n"
},
{
"answer_id": 42454,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "<p>Uh, to all those people saying \"it's OK, don't worry about it, the GC will handle it...\" the whole <em>point</em> of the <code>Dispose</code> pattern is to handle those resources the GC <em>can't</em> dispose of. So if an object has a <code>Dispose</code> method, you'd better call it when you're done with it!</p>\n\n<p>In summary, Longhorn213 is correct, listen to him.</p>\n"
},
{
"answer_id": 42501,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p>One thing I never worked out - If I have a class implementing <code>IDisposable</code>, but I never actually dispose it myself, I just leave it hanging around for the GC, will the GC actually call <code>Dispose</code> for me?</p>\n"
},
{
"answer_id": 43118,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Be careful. If you have to do a lot of these in a loop it can be slow. It's much better to just update the .CommandText property of the same command, like this (also, you can clean up the syntax a little):</p>\n\n<pre><code>Using mysql as New SqlCommand(sSql, cnInput)\n ' do stuff'\n\n mySql.CommandText = otherSql\n\n 'do other stuff'\nEnd Using\n</code></pre>\n\n<p>Of course, that only works if the first command is no longer active. If you're still in the middle of going through a datareader then you better create a new command.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1476/"
] | X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions.
Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X?
I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks. | Just to extend what Longhorn213 said, here's the code for it:
```
Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)
' do stuff'
End Using
Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput)
' do other stuff'
End Using
```
(edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. <http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx> |
42,446 | <pre><code>class Foo
{
static bool Bar(Stream^ stream);
};
class FooWrapper
{
bool Bar(LPCWSTR szUnicodeString)
{
return Foo::Bar(??);
}
};
</code></pre>
<p><code>MemoryStream</code> will take a <code>byte[]</code> but I'd <em>like</em> to do this without copying the data if possible.</p>
| [
{
"answer_id": 42605,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 0,
"selected": false,
"text": "<p>If I had to copy the memory, I think the following would work:</p>\n\n<pre><code>\nstatic Stream^ UnicodeStringToStream(LPCWSTR szUnicodeString)\n{\n //validate the input parameter\n if (szUnicodeString == NULL)\n {\n return nullptr;\n }\n\n //get the length of the string\n size_t lengthInWChars = wcslen(szUnicodeString); \n size_t lengthInBytes = lengthInWChars * sizeof(wchar_t);\n\n //allocate the .Net byte array\n array^ byteArray = gcnew array(lengthInBytes);\n\n //copy the unmanaged memory into the byte array\n Marshal::Copy((IntPtr)(void*)szUnicodeString, byteArray, 0, lengthInBytes);\n\n //create a memory stream from the byte array\n return gcnew MemoryStream(byteArray);\n}</code></pre>\n"
},
{
"answer_id": 42968,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 4,
"selected": true,
"text": "<p>You can avoid the copy if you use an <a href=\"http://msdn.microsoft.com/en-us/library/system.io.unmanagedmemorystream.aspx\" rel=\"nofollow noreferrer\"><code>UnmanagedMemoryStream()</code></a> instead (class exists in .NET FCL 2.0 and later). Like <code>MemoryStream</code>, it is a subclass of <code>IO.Stream</code>, and has all the usual stream operations.</p>\n\n<p>Microsoft's description of the class is:</p>\n\n<blockquote>\n <p>Provides access to unmanaged blocks of memory from managed code.</p>\n</blockquote>\n\n<p>which pretty much tells you what you need to know. Note that <code>UnmanagedMemoryStream()</code> is not CLS-compliant.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] | ```
class Foo
{
static bool Bar(Stream^ stream);
};
class FooWrapper
{
bool Bar(LPCWSTR szUnicodeString)
{
return Foo::Bar(??);
}
};
```
`MemoryStream` will take a `byte[]` but I'd *like* to do this without copying the data if possible. | You can avoid the copy if you use an [`UnmanagedMemoryStream()`](http://msdn.microsoft.com/en-us/library/system.io.unmanagedmemorystream.aspx) instead (class exists in .NET FCL 2.0 and later). Like `MemoryStream`, it is a subclass of `IO.Stream`, and has all the usual stream operations.
Microsoft's description of the class is:
>
> Provides access to unmanaged blocks of memory from managed code.
>
>
>
which pretty much tells you what you need to know. Note that `UnmanagedMemoryStream()` is not CLS-compliant. |
42,482 | <p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p>
<p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p>
<p>A Python solution would be ideal, but doesn't appear to be available.</p>
| [
{
"answer_id": 42485,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 1,
"selected": false,
"text": "<p>Open Office has an <a href=\"http://api.openoffice.org/\" rel=\"nofollow noreferrer\">API</a></p>\n"
},
{
"answer_id": 43301,
"author": "paulmorriss",
"author_id": 2983,
"author_profile": "https://Stackoverflow.com/users/2983",
"pm_score": 2,
"selected": false,
"text": "<p>Using the OpenOffice API, and Python, and <a href=\"http://www.pitonyak.org/oo.php\" rel=\"nofollow noreferrer\">Andrew Pitonyak's excellent online macro book</a> I managed to do this. Section 7.16.4 is the place to start.</p>\n\n<p>One other tip to make it work without needing the screen at all is to use the Hidden property:</p>\n\n<pre><code>RO = PropertyValue('ReadOnly', 0, True, 0)\nHidden = PropertyValue('Hidden', 0, True, 0)\nxDoc = desktop.loadComponentFromURL( docpath,\"_blank\", 0, (RO, Hidden,) )\n</code></pre>\n\n<p>Otherwise the document flicks up on the screen (probably on the webserver console) when you open it.</p>\n"
},
{
"answer_id": 43364,
"author": "codeape",
"author_id": 3571,
"author_profile": "https://Stackoverflow.com/users/3571",
"pm_score": 5,
"selected": true,
"text": "<p>I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python).</p>\n\n<pre><code>import os\n\ndef doc_to_text_catdoc(filename):\n (fi, fo, fe) = os.popen3('catdoc -w \"%s\"' % filename)\n fi.close()\n retval = fo.read()\n erroroutput = fe.read()\n fo.close()\n fe.close()\n if not erroroutput:\n return retval\n else:\n raise OSError(\"Executing the command caused an error: %s\" % erroroutput)\n\n# similar doc_to_text_antiword()\n</code></pre>\n\n<p>The -w switch to catdoc turns off line wrapping, BTW.</p>\n"
},
{
"answer_id": 1387028,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>For docx files, check out the Python script docx2txt available at</p>\n\n<p><a href=\"http://cobweb.ecn.purdue.edu/~kak/distMisc/docx2txt\" rel=\"nofollow noreferrer\">http://cobweb.ecn.purdue.edu/~kak/distMisc/docx2txt</a></p>\n\n<p>for extracting the plain text from a docx document.</p>\n"
},
{
"answer_id": 1979931,
"author": "mikemaccana",
"author_id": 123671,
"author_profile": "https://Stackoverflow.com/users/123671",
"pm_score": 4,
"selected": false,
"text": "<p>(Same answer as <a href=\"https://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python\">extracting text from MS word files in python</a>)</p>\n<p>Use the native Python docx module which I made this week. Here's how to extract all the text from a doc:</p>\n<pre><code>document = opendocx('Hello world.docx')\n\n# This location is where most document content lives \ndocbody = document.xpath('/w:document/w:body', namespaces=wordnamespaces)[0]\n\n# Extract all text\nprint getdocumenttext(document)\n</code></pre>\n<p>See <a href=\"https://python-docx.readthedocs.org/en/latest/\" rel=\"nofollow noreferrer\">Python DocX site</a></p>\n<p>100% Python, no COM, no .net, no Java, no parsing serialized XML with regexs.</p>\n"
},
{
"answer_id": 20663596,
"author": "Etienne",
"author_id": 146481,
"author_profile": "https://Stackoverflow.com/users/146481",
"pm_score": 2,
"selected": false,
"text": "<p>If all you want to do is extracting text from Word files (.docx), it's possible to do it only with Python. Like Guy Starbuck wrote it, you just need to unzip the file and then parse the XML. Inspired by <code>python-docx</code>, I have written a <a href=\"http://etienned.github.io/posts/extract-text-from-word-docx-simply/\" rel=\"nofollow\">simple function</a> to do this:</p>\n\n<pre><code>try:\n from xml.etree.cElementTree import XML\nexcept ImportError:\n from xml.etree.ElementTree import XML\nimport zipfile\n\n\n\"\"\"\nModule that extract text from MS XML Word document (.docx).\n(Inspired by python-docx <https://github.com/mikemaccana/python-docx>)\n\"\"\"\n\nWORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'\nPARA = WORD_NAMESPACE + 'p'\nTEXT = WORD_NAMESPACE + 't'\n\n\ndef get_docx_text(path):\n \"\"\"\n Take the path of a docx file as argument, return the text in unicode.\n \"\"\"\n document = zipfile.ZipFile(path)\n xml_content = document.read('word/document.xml')\n document.close()\n tree = XML(xml_content)\n\n paragraphs = []\n for paragraph in tree.getiterator(PARA):\n texts = [node.text\n for node in paragraph.getiterator(TEXT)\n if node.text]\n if texts:\n paragraphs.append(''.join(texts))\n\n return '\\n\\n'.join(paragraphs)\n</code></pre>\n"
},
{
"answer_id": 30122626,
"author": "markling",
"author_id": 2455413,
"author_profile": "https://Stackoverflow.com/users/2455413",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/16516044/is-it-possible-to-read-word-files-doc-docx-in-python/30122239#30122239\">This worked well</a> for .doc and .odt.</p>\n\n<p>It calls openoffice on the command line to convert your file to text, which you can then simply load into python.</p>\n\n<p>(It seems to have other format options, though they are not apparenlty documented.)</p>\n"
},
{
"answer_id": 51905584,
"author": "Dhinesh kumar M",
"author_id": 7479213,
"author_profile": "https://Stackoverflow.com/users/7479213",
"pm_score": 2,
"selected": false,
"text": "<p><strong>tika-python</strong></p>\n\n<p>A Python port of the Apache Tika library, According to the documentation Apache tika supports text extraction from over 1500 file formats. </p>\n\n<p><strong>Note:</strong> It also works charmingly with <strong>pyinstaller</strong></p>\n\n<p>Install with pip :</p>\n\n<pre><code>pip install tika\n</code></pre>\n\n<p><strong>Sample:</strong></p>\n\n<pre><code>#!/usr/bin/env python\nfrom tika import parser\nparsed = parser.from_file('/path/to/file')\nprint(parsed[\"metadata\"]) #To get the meta data of the file\nprint(parsed[\"content\"]) # To get the content of the file\n</code></pre>\n\n<p>Link to official <a href=\"https://github.com/chrismattmann/tika-python\" rel=\"nofollow noreferrer\">GitHub</a></p>\n"
},
{
"answer_id": 62974454,
"author": "prossblad",
"author_id": 5012591,
"author_profile": "https://Stackoverflow.com/users/5012591",
"pm_score": 0,
"selected": false,
"text": "<p>Honestly <strong>don't use "pip install tika</strong>", this has been developed for mono-user (one developper working on his laptop) and not for multi-users (multi-developpers).</p>\n<p>The small class TikaWrapper.py bellow which uses Tika in command line is widely enough to meet our needs.</p>\n<p>You just have to instanciate this class with JAVA_HOME path and the Tika jar path, that's all ! And it works perfectly for lot of formats (e.g: PDF, DOCX, ODT, XLSX, PPT, etc.).</p>\n<pre><code>#!/bin/python\n# -*- coding: utf-8 -*-\n\n# Class to extract metadata and text from different file types (such as PPT, XLS, and PDF)\n# Developed by Philippe ROSSIGNOL\n#####################\n# TikaWrapper class #\n#####################\nclass TikaWrapper:\n\n java_home = None\n tikalib_path = None\n\n # Constructor\n def __init__(self, java_home, tikalib_path):\n self.java_home = java_home\n self.tika_lib_path = tikalib_path\n\n def extractMetadata(self, filePath, encoding="UTF-8", returnTuple=False):\n '''\n - Description:\n Extract metadata from a document\n \n - Params:\n filePath: The document file path\n encoding: The encoding (default = "UTF-8")\n returnTuple: If True return a tuple which contains both the output and the error (default = False)\n \n - Examples:\n metadata = extractMetadata(filePath="MyDocument.docx")\n metadata, error = extractMetadata(filePath="MyDocument.docx", encoding="UTF-8", returnTuple=True)\n '''\n cmd = self._getCmd(self._cmdExtractMetadata, filePath, encoding)\n out, err = self._execute(cmd, encoding)\n if (returnTuple): return out, err\n return out\n\n def extractText(self, filePath, encoding="UTF-8", returnTuple=False):\n '''\n - Description:\n Extract text from a document\n \n - Params:\n filePath: The document file path\n encoding: The encoding (default = "UTF-8")\n returnTuple: If True return a tuple which contains both the output and the error (default = False)\n \n - Examples:\n text = extractText(filePath="MyDocument.docx")\n text, error = extractText(filePath="MyDocument.docx", encoding="UTF-8", returnTuple=True)\n '''\n cmd = self._getCmd(self._cmdExtractText, filePath, encoding)\n out, err = self._execute(cmd, encoding)\n return out, err\n\n # ===========\n # = PRIVATE =\n # ===========\n\n _cmdExtractMetadata = "${JAVA_HOME}/bin/java -jar ${TIKALIB_PATH} --metadata ${FILE_PATH}"\n _cmdExtractText = "${JAVA_HOME}/bin/java -jar ${TIKALIB_PATH} --encoding=${ENCODING} --text ${FILE_PATH}"\n\n def _getCmd(self, cmdModel, filePath, encoding):\n cmd = cmdModel.replace("${JAVA_HOME}", self.java_home)\n cmd = cmd.replace("${TIKALIB_PATH}", self.tika_lib_path)\n cmd = cmd.replace("${ENCODING}", encoding)\n cmd = cmd.replace("${FILE_PATH}", filePath)\n return cmd\n\n def _execute(self, cmd, encoding):\n import subprocess\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = process.communicate()\n out = out.decode(encoding=encoding)\n err = err.decode(encoding=encoding)\n return out, err\n</code></pre>\n"
},
{
"answer_id": 63790262,
"author": "Vishal Sanap",
"author_id": 7752269,
"author_profile": "https://Stackoverflow.com/users/7752269",
"pm_score": 0,
"selected": false,
"text": "<p>Just in case if someone wants to do in Java language there is Apache poi api. extractor.getText() will extract plane text from docx . Here is the link <a href=\"https://www.tutorialspoint.com/apache_poi_word/apache_poi_word_text_extraction.htm\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/apache_poi_word/apache_poi_word_text_extraction.htm</a></p>\n"
},
{
"answer_id": 70816823,
"author": "vhx.ai",
"author_id": 18004763,
"author_profile": "https://Stackoverflow.com/users/18004763",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Textract-Plus</strong></p>\n<p>Use textract-plus which can extract text from most of the document extensions including doc , docm , dotx and docx.\n(It uses antiword as a backend for doc files)\n<a href=\"https://textract-plus.readthedocs.io/en/latest/index.html\" rel=\"nofollow noreferrer\">refer docs</a></p>\n<p>Install-</p>\n<pre><code>pip install textract-plus\n</code></pre>\n<p>Sample-</p>\n<pre><code>import textractplus as tp\ntext=tp.process('path/to/yourfile.doc')\n</code></pre>\n"
},
{
"answer_id": 71948159,
"author": "CpILL",
"author_id": 196732,
"author_profile": "https://Stackoverflow.com/users/196732",
"pm_score": 0,
"selected": false,
"text": "<p>There is also <a href=\"https://pandoc.org/\" rel=\"nofollow noreferrer\">pandoc</a> the swiss-army-knife of documents. It converts from every format to nearly every other format. From the demos page</p>\n<pre><code>pandoc -s input_file.docx -o output_file.txt\n</code></pre>\n"
},
{
"answer_id": 72573235,
"author": "r-or",
"author_id": 12875177,
"author_profile": "https://Stackoverflow.com/users/12875177",
"pm_score": 0,
"selected": false,
"text": "<p>Like <a href=\"https://stackoverflow.com/a/20663596/12875177\">Etienne's answer</a>.\nWith python 3.9 <code>getiterator</code> was deprecated in ET, so you need to replace it with <code>iter</code>:</p>\n<pre><code>\ndef get_docx_text(path):\n """\n Take the path of a docx file as argument, return the text in unicode.\n """\n document = zipfile.ZipFile(path)\n xml_content = document.read('word/document.xml')\n document.close()\n tree = XML(xml_content)\n\n paragraphs = []\n for paragraph in tree.iter(PARA):\n texts = [node.text\n for node in paragraph.iter(TEXT)\n if node.text]\n if texts:\n paragraphs.append(''.join(texts))\n\n return '\\n\\n'.join(paragraphs)\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2678/"
] | Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)
Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.
A Python solution would be ideal, but doesn't appear to be available. | I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python).
```
import os
def doc_to_text_catdoc(filename):
(fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename)
fi.close()
retval = fo.read()
erroroutput = fe.read()
fo.close()
fe.close()
if not erroroutput:
return retval
else:
raise OSError("Executing the command caused an error: %s" % erroroutput)
# similar doc_to_text_antiword()
```
The -w switch to catdoc turns off line wrapping, BTW. |
42,490 | <p><em>Disclaimer: I'm stuck on TFS and I hate it.</em></p>
<p>My source control structure looks like this:</p>
<ul>
<li>/dev</li>
<li>/releases</li>
<li>/branches</li>
<li>/experimental-upgrade</li>
</ul>
<p>I branched from dev to experimental-upgrade and didn't touch it. I then did some more work in dev and merged to experimental-upgrade. Somehow TFS complained that I had changes in both source and target and I had to resolve them. I chose to "Copy item from source branch" for all 5 items.</p>
<p>I check out the experimental-upgrade to a local folder and try to open the main solution file in there. TFS prompts me: </p>
<blockquote>
<p>"Projects have recently been added to this solution. Would you like to get them from source control?</p>
</blockquote>
<p>If I say yes it does some stuff but ultimately comes back failing to load a handful of the projects. If I say no I get the same result.</p>
<p>Comparing my sln in both branches tells me that they are equal.</p>
<p>Can anyone let me know what I'm doing wrong? This should be a straightforward branch/merge operation...</p>
<p>TIA.</p>
<hr>
<p><strong>UPDATE:</strong></p>
<p>I noticed that if I click "yes" on the above dialog, the projects are downloaded to the $/ root of source control... (i.e. out of the dev & branches folders)</p>
<p>If I open up the solution in the branch and remove the dead projects and try to re-add them (by right-clicking sln, add existing project, choose project located in the branch folder, it gives me the error...</p>
<blockquote>
<p>Cannot load the project c:\sandbox\my_solution\proj1\proj1.csproj, the file has been removed or deleted. The project path I was trying to add is this: c:\sandbox\my_solution\branches\experimental-upgrade\proj1\proj1.csproj</p>
</blockquote>
<p>What in the world is pointing these projects <em>outside</em> of their local root? The solution file is identical to the one in the dev branch, and those projects load just fine. I also looked at the vspscc and vssscc files but didn't find anything.</p>
<p>Ideas?</p>
| [
{
"answer_id": 42534,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>@Nick: No changes have been made to this just yet. I may have to delete it and re-branch (however you really can't fully delete in TFS)</p>\n\n<p>And I have to disagree... branching is absolutely a good practice for experimental changes. Shelving is just temporary storage that will get backed up if I don't want to check in yet. But this needs to be developed while we develop real features.</p>\n"
},
{
"answer_id": 42548,
"author": "Kevin Berridge",
"author_id": 4407,
"author_profile": "https://Stackoverflow.com/users/4407",
"pm_score": 0,
"selected": false,
"text": "<p>Without knowing more about your solution setup I can't be sure. But, if you have any project references that could explain it. Because you have the \"experimental-upgrade\" subfolder under \"branches\" your relative paths have changed.</p>\n\n<p>This means when VS used to look for your referenced projects in ..\\..\\project\\whatever it now has to look in ..\\..\\..\\project\\whatever. Note the extra ..\\</p>\n\n<p>To fix this you have to re-add your project references. I haven't found a better way. You can either remove them and re-add them, or go to the properties window and change the path to them, then reload them. Either way, you'll have to redo your references to them from any projects.</p>\n\n<p>Also, check your working folders to make sure that it didn't download any of your projects into the wrong folders. This can happen sometimes...</p>\n"
},
{
"answer_id": 42553,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 3,
"selected": true,
"text": "<p>@Ben</p>\n\n<p>You can actually do a full delete in TFS, but it is highly not recommended unless you know what you are doing. You have to do it from the command line with the command tf destroy</p>\n\n<pre><code>tf destroy [/keephistory] itemspec1 [;versionspec]\n [itemspec2...itemspecN] [/stopat:versionspec] [/preview]\n [/startcleanup] [/noprompt]\n\nVersionspec:\n Date/Time Dmm/dd/yyyy\n or any .Net Framework-supported format\n or any of the date formats of the local machine\n Changeset number Cnnnnnn\n Label Llabelname\n Latest version T\n Workspace Wworkspacename;workspaceowner\n</code></pre>\n\n<p>Just before you do this make sure you try it out with the /preview. Also everybody has their own methodology for branching. Mine is to branch releases, and do all development in the development or root folder. Also it sounded like branching worked fine for you, just the solution file was screwed up, which may be because of a binding issue and the vssss file.</p>\n"
},
{
"answer_id": 42560,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 0,
"selected": false,
"text": "<p>A couple of things. Are the folder structures the same? Can you delete and readd the project references successfully? </p>\n\n<p>If you create a solution and then manually add all of the projects, does that work. (That may not be feasable - we have solutions with over a hundred projects).</p>\n\n<p>One other thing (and it may be silly) - after you did the branch, did you commit it? I'm wondering if you branched and didn't check it in, and then merged, and then when you tried to check-in then, TFS was mighty confused.</p>\n"
},
{
"answer_id": 42568,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>@Kevin:</p>\n\n<blockquote>\n <p>This means when VS used to look for your referenced projects in ....\\project\\whatever it now has to look in ......\\project\\whatever. Note the extra ..\\</p>\n</blockquote>\n\n<p>You may be on to something here, however it doesn't explain why some projects load and others do not. I haven't found a correlation between them yet.</p>\n\n<p>I think I'll try to re-add the projects and see if that works.</p>\n"
},
{
"answer_id": 42571,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>@Cory:</p>\n\n<p>I think that's what I'm going to try... I have about 20 projects and 8 or so aren't loading. The folder structures are identical from root... ie: there aren't any references outside of DEV.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3381/"
] | *Disclaimer: I'm stuck on TFS and I hate it.*
My source control structure looks like this:
* /dev
* /releases
* /branches
* /experimental-upgrade
I branched from dev to experimental-upgrade and didn't touch it. I then did some more work in dev and merged to experimental-upgrade. Somehow TFS complained that I had changes in both source and target and I had to resolve them. I chose to "Copy item from source branch" for all 5 items.
I check out the experimental-upgrade to a local folder and try to open the main solution file in there. TFS prompts me:
>
> "Projects have recently been added to this solution. Would you like to get them from source control?
>
>
>
If I say yes it does some stuff but ultimately comes back failing to load a handful of the projects. If I say no I get the same result.
Comparing my sln in both branches tells me that they are equal.
Can anyone let me know what I'm doing wrong? This should be a straightforward branch/merge operation...
TIA.
---
**UPDATE:**
I noticed that if I click "yes" on the above dialog, the projects are downloaded to the $/ root of source control... (i.e. out of the dev & branches folders)
If I open up the solution in the branch and remove the dead projects and try to re-add them (by right-clicking sln, add existing project, choose project located in the branch folder, it gives me the error...
>
> Cannot load the project c:\sandbox\my\_solution\proj1\proj1.csproj, the file has been removed or deleted. The project path I was trying to add is this: c:\sandbox\my\_solution\branches\experimental-upgrade\proj1\proj1.csproj
>
>
>
What in the world is pointing these projects *outside* of their local root? The solution file is identical to the one in the dev branch, and those projects load just fine. I also looked at the vspscc and vssscc files but didn't find anything.
Ideas? | @Ben
You can actually do a full delete in TFS, but it is highly not recommended unless you know what you are doing. You have to do it from the command line with the command tf destroy
```
tf destroy [/keephistory] itemspec1 [;versionspec]
[itemspec2...itemspecN] [/stopat:versionspec] [/preview]
[/startcleanup] [/noprompt]
Versionspec:
Date/Time Dmm/dd/yyyy
or any .Net Framework-supported format
or any of the date formats of the local machine
Changeset number Cnnnnnn
Label Llabelname
Latest version T
Workspace Wworkspacename;workspaceowner
```
Just before you do this make sure you try it out with the /preview. Also everybody has their own methodology for branching. Mine is to branch releases, and do all development in the development or root folder. Also it sounded like branching worked fine for you, just the solution file was screwed up, which may be because of a binding issue and the vssss file. |
42,505 | <p>I have a C# singleton class that multiple classes use. Is access through <code>Instance</code> to the <code>Toggle()</code> method thread-safe? If yes, by what assumptions, rules, etc. If no, why <em>and</em> how can I fix it?</p>
<pre><code>public class MyClass
{
private static readonly MyClass instance = new MyClass();
public static MyClass Instance
{
get { return instance; }
}
private int value = 0;
public int Toggle()
{
if(value == 0)
{
value = 1;
}
else if(value == 1)
{
value = 0;
}
return value;
}
}
</code></pre>
| [
{
"answer_id": 42511,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 0,
"selected": false,
"text": "<p>Quote:</p>\n\n<pre><code>if(value == 0) { value = 1; }\nif(value == 1) { value = 0; }\nreturn value;\n</code></pre>\n\n<p><code>value</code> will always be 0...</p>\n"
},
{
"answer_id": 42517,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<p>Your thread could stop in the middle of that method and transfer control to a different thread. You need a critical section around that code...</p>\n\n<pre><code>private static object _lockDummy = new object();\n\n\n...\n\nlock(_lockDummy)\n{\n //do stuff\n}\n</code></pre>\n"
},
{
"answer_id": 42526,
"author": "levand",
"author_id": 3044,
"author_profile": "https://Stackoverflow.com/users/3044",
"pm_score": -1,
"selected": false,
"text": "<p>Well, I actually don't know C# that well... but I am ok at Java, so I will give the answer for that, and hopefully the two are similar enough that it will be useful. If not, I apologize.</p>\n\n<p>The answer is, no, it's not safe. One thread could call Toggle() at the same time as the other, and it is possible, although unlikely with this code, that Thread1 could set <code>value</code> in between the times that Thread2 checks it and when it sets it.</p>\n\n<p>To fix, simply make Toggle() <code>synchronized</code>. It doesn't block on anything or call anything that might spawn another thread which could call Toggle(), so that's all you have to do save it.</p>\n"
},
{
"answer_id": 42533,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 3,
"selected": false,
"text": "<p>The original impplementation is not thread safe, as Ben points out</p>\n\n<p>A simple way to make it thread safe is to introduce a lock statement. Eg. like this:</p>\n\n<pre><code>public class MyClass\n{\n private Object thisLock = new Object();\n private static readonly MyClass instance = new MyClass();\n public static MyClass Instance\n {\n get { return instance; }\n }\n private Int32 value = 0;\n public Int32 Toggle()\n {\n lock(thisLock)\n {\n if(value == 0) \n {\n value = 1; \n }\n else if(value == 1) \n { \n value = 0; \n }\n return value;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 42536,
"author": "fhe",
"author_id": 4445,
"author_profile": "https://Stackoverflow.com/users/4445",
"pm_score": 2,
"selected": false,
"text": "<p>I'd also add a protected constructor to MyClass to prevent the compiler from generating a public default constructor.</p>\n"
},
{
"answer_id": 42551,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p>Is access through 'Instance' to the 'Toggle()' class threadsafe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it?</p>\n</blockquote>\n\n<p>No, it's not threadsafe.</p>\n\n<p>Basically, both threads can run the <code>Toggle</code> function at the same time, so this could happen</p>\n\n<pre><code> // thread 1 is running this code\n if(value == 0) \n {\n value = 1; \n // RIGHT NOW, thread 2 steps in.\n // It sees value as 1, so runs the other branch, and changes it to 0\n // This causes your method to return 0 even though you actually want 1\n }\n else if(value == 1) \n { \n value = 0; \n }\n return value;\n</code></pre>\n\n<p>You need to operate with the following assumption.</p>\n\n<p>If 2 threads are running, they can and will interleave and interact with eachother randomly at any point. You can be half way through writing or reading a 64 bit integer or float (on a 32 bit CPU) and another thread can jump in and change it out from underneath you.</p>\n\n<p>If the 2 threads never access anything in common, it doesn't matter, but as soon as they do, you need to prevent them from stepping on each others toes. The way to do this in .NET is with locks.</p>\n\n<p>You can decide what and where to lock by thinking about things like this:</p>\n\n<p>For a given block of code, if the value of <code>something</code> got changed out from underneath me, would it matter? If it would, you need to lock that <code>something</code> for the duration of the code where it would matter.</p>\n\n<p>Looking at your example again</p>\n\n<pre><code> // we read value here\n if(value == 0) \n {\n value = 1; \n }\n else if(value == 1) \n { \n value = 0; \n }\n // and we return it here\n return value;\n</code></pre>\n\n<p>In order for this to return what we expect it to, we assume that <code>value</code> won't get changed between the read and the <code>return</code>. In order for this assumption to actually be correct, you need to lock <code>value</code> for the duration of that code block.</p>\n\n<p>So you'd do this:</p>\n\n<pre><code>lock( value )\n{\n if(value == 0) \n ... // all your code here\n return value;\n}\n</code></pre>\n\n<p><strong>HOWEVER</strong></p>\n\n<p>In .NET you can only lock Reference Types. Int32 is a Value Type, so we can't lock it.<br>\nWe solve this by introducing a 'dummy' object, and locking <em>that</em> wherever we'd want to lock 'value'.</p>\n\n<p>This is what <a href=\"https://stackoverflow.com/questions/42505/thread-safe-use-of-a-singletons-members/42517#42517\">Ben Scheirman</a> is referring to.</p>\n"
},
{
"answer_id": 42572,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>That is what I thought. But, I I'm\n looking for the details... 'Toggle()'\n is not a static method, but it is a\n member of a static property (when\n using 'Instance'). Is that what makes\n it shared among threads?</p>\n</blockquote>\n\n<p>If your application is multi-threaded and you can forsee that multiple thread will access that method, that makes it shared among threads. Because your class is a Singleton you know that the diferent thread will access the SAME object, so be cautioned about the thread-safety of your methods.</p>\n\n<blockquote>\n <p>And how does this apply to singletons\n in general. Would I have to address\n this in every method on my class?</p>\n</blockquote>\n\n<p>As I said above, because its a singleton you know diferent thread will acess the same object, possibly at the same time. This does not mean you have to make every method obtain a lock. If you notice that a simultaneos invocation can lead to corrupted state of the class, then you should apply the method mentioned by @Thomas</p>\n"
},
{
"answer_id": 42585,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Can I assume that the singleton pattern exposes my otherwise lovely thread-safe class to all the thread problems of regular static members?</p>\n</blockquote>\n\n<p>No. Your class is simply not threadsafe. The singleton has nothing to do with it.</p>\n\n<blockquote>\n <p>(I'm getting my head around the fact that instance members called on a static object cause threading problems)</p>\n</blockquote>\n\n<p>It's nothing to do with that either.</p>\n\n<p>You have to think like this: Is it possible in my program for 2 (or more) threads to access this piece of data at the same time?</p>\n\n<p>The fact that you obtain the data via a singleton, or static variable, or passing in an object as a method parameter doesn't matter. At the end of the day it's all just some bits and bytes in your PC's RAM, and all that matters is whether multiple threads can see the same bits.</p>\n"
},
{
"answer_id": 42611,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I was thinking that if I dump the singleton pattern and force everyone to get a new instance of the class it would ease some problems... but that doesn't stop anyone else from initializing a static object of that type and passing that around... or from spinning off multiple threads, all accessing 'Toggle()' from the same instance.</p>\n</blockquote>\n\n<p>Bingo :-)</p>\n\n<blockquote>\n <p>I get it now. It's a tough world. I wish I weren't refactoring legacy code :(</p>\n</blockquote>\n\n<p>Unfortunately, multithreading is hard and you have to be very paranoid about things :-)\nThe simplest solution in this case is to stick with the singleton, and add a lock around the value, like in the examples.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
] | I have a C# singleton class that multiple classes use. Is access through `Instance` to the `Toggle()` method thread-safe? If yes, by what assumptions, rules, etc. If no, why *and* how can I fix it?
```
public class MyClass
{
private static readonly MyClass instance = new MyClass();
public static MyClass Instance
{
get { return instance; }
}
private int value = 0;
public int Toggle()
{
if(value == 0)
{
value = 1;
}
else if(value == 1)
{
value = 0;
}
return value;
}
}
``` | >
> Is access through 'Instance' to the 'Toggle()' class threadsafe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it?
>
>
>
No, it's not threadsafe.
Basically, both threads can run the `Toggle` function at the same time, so this could happen
```
// thread 1 is running this code
if(value == 0)
{
value = 1;
// RIGHT NOW, thread 2 steps in.
// It sees value as 1, so runs the other branch, and changes it to 0
// This causes your method to return 0 even though you actually want 1
}
else if(value == 1)
{
value = 0;
}
return value;
```
You need to operate with the following assumption.
If 2 threads are running, they can and will interleave and interact with eachother randomly at any point. You can be half way through writing or reading a 64 bit integer or float (on a 32 bit CPU) and another thread can jump in and change it out from underneath you.
If the 2 threads never access anything in common, it doesn't matter, but as soon as they do, you need to prevent them from stepping on each others toes. The way to do this in .NET is with locks.
You can decide what and where to lock by thinking about things like this:
For a given block of code, if the value of `something` got changed out from underneath me, would it matter? If it would, you need to lock that `something` for the duration of the code where it would matter.
Looking at your example again
```
// we read value here
if(value == 0)
{
value = 1;
}
else if(value == 1)
{
value = 0;
}
// and we return it here
return value;
```
In order for this to return what we expect it to, we assume that `value` won't get changed between the read and the `return`. In order for this assumption to actually be correct, you need to lock `value` for the duration of that code block.
So you'd do this:
```
lock( value )
{
if(value == 0)
... // all your code here
return value;
}
```
**HOWEVER**
In .NET you can only lock Reference Types. Int32 is a Value Type, so we can't lock it.
We solve this by introducing a 'dummy' object, and locking *that* wherever we'd want to lock 'value'.
This is what [Ben Scheirman](https://stackoverflow.com/questions/42505/thread-safe-use-of-a-singletons-members/42517#42517) is referring to. |
42,519 | <p>Inspired by <a href="https://devblogs.microsoft.com/oldnewthing/20080902-00/?p=21003" rel="noreferrer">Raymond Chen's post</a>, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.</p>
<pre><code>[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
</code></pre>
<p>Becomes:</p>
<pre><code>[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
</code></pre>
<p><strong>Update</strong>: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?</p>
| [
{
"answer_id": 42535,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 8,
"selected": true,
"text": "<p>Here it is in C#</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>int[,] array = new int[4,4] {\n { 1,2,3,4 },\n { 5,6,7,8 },\n { 9,0,1,2 },\n { 3,4,5,6 }\n};\n\nint[,] rotated = RotateMatrix(array, 4);\n\nstatic int[,] RotateMatrix(int[,] matrix, int n) {\n int[,] ret = new int[n, n];\n\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n ret[i, j] = matrix[n - j - 1, i];\n }\n }\n\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 42578,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "<p>Here's my Ruby version (note the values aren't displayed the same, but it still rotates as described).</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>def rotate(matrix)\n result = []\n 4.times { |x|\n result[x] = []\n 4.times { |y|\n result[x][y] = matrix[y][3 - x]\n }\n }\n\n result\nend\n\nmatrix = []\nmatrix[0] = [1,2,3,4]\nmatrix[1] = [5,6,7,8]\nmatrix[2] = [9,0,1,2]\nmatrix[3] = [3,4,5,6]\n\ndef print_matrix(matrix)\n 4.times { |y|\n 4.times { |x|\n print \"#{matrix[x][y]} \"\n }\n puts \"\"\n }\nend\n\nprint_matrix(matrix)\nputs \"\"\nprint_matrix(rotate(matrix))\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>1 5 9 3 \n2 6 0 4 \n3 7 1 5 \n4 8 2 6 \n\n4 3 2 1 \n8 7 6 5 \n2 1 0 9 \n6 5 4 3\n</code></pre>\n"
},
{
"answer_id": 42590,
"author": "Kevin Berridge",
"author_id": 4407,
"author_profile": "https://Stackoverflow.com/users/4407",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array#42535\">Nick's</a> answer would work for an NxM array too with only a small modification (as opposed to an NxN).</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>string[,] orig = new string[n, m];\nstring[,] rot = new string[m, n];\n\n...\n\nfor ( int i=0; i < n; i++ )\n for ( int j=0; j < m; j++ )\n rot[j, n - i - 1] = orig[i, j];\n</code></pre>\n\n<p>One way to think about this is that you have moved the center of the axis (0,0) from the top left corner to the top right corner. You're simply transposing from one to the other.</p>\n"
},
{
"answer_id": 42612,
"author": "nsanders",
"author_id": 1244,
"author_profile": "https://Stackoverflow.com/users/1244",
"pm_score": 3,
"selected": false,
"text": "<p>A couple of people have already put up examples which involve making a new array. </p>\n\n<p>A few other things to consider:</p>\n\n<p>(a) Instead of actually moving the data, simply traverse the \"rotated\" array differently. </p>\n\n<p>(b) Doing the rotation in-place can be a little trickier. You'll need a bit of scratch place (probably roughly equal to one row or column in size). There's an ancient ACM paper about doing in-place transposes (<a href=\"http://doi.acm.org/10.1145/355719.355729\" rel=\"noreferrer\">http://doi.acm.org/10.1145/355719.355729</a>), but their example code is nasty goto-laden FORTRAN.</p>\n\n<p>Addendum:</p>\n\n<p><a href=\"http://doi.acm.org/10.1145/355611.355612\" rel=\"noreferrer\">http://doi.acm.org/10.1145/355611.355612</a> is another, supposedly superior, in-place transpose algorithm.</p>\n"
},
{
"answer_id": 43333,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 5,
"selected": false,
"text": "<p>As I said in my previous post, here's some code in C# that implements an O(1) matrix rotation for any size matrix. For brevity and readability there's no error checking or range checking. The code:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>static void Main (string [] args)\n{\n int [,]\n // create an arbitrary matrix\n m = {{0, 1}, {2, 3}, {4, 5}};\n\n Matrix\n // create wrappers for the data\n m1 = new Matrix (m),\n m2 = new Matrix (m),\n m3 = new Matrix (m);\n\n // rotate the matricies in various ways - all are O(1)\n m1.RotateClockwise90 ();\n m2.Rotate180 ();\n m3.RotateAnitclockwise90 ();\n\n // output the result of transforms\n System.Diagnostics.Trace.WriteLine (m1.ToString ());\n System.Diagnostics.Trace.WriteLine (m2.ToString ());\n System.Diagnostics.Trace.WriteLine (m3.ToString ());\n}\n\nclass Matrix\n{\n enum Rotation\n {\n None,\n Clockwise90,\n Clockwise180,\n Clockwise270\n }\n\n public Matrix (int [,] matrix)\n {\n m_matrix = matrix;\n m_rotation = Rotation.None;\n }\n\n // the transformation routines\n public void RotateClockwise90 ()\n {\n m_rotation = (Rotation) (((int) m_rotation + 1) & 3);\n }\n\n public void Rotate180 ()\n {\n m_rotation = (Rotation) (((int) m_rotation + 2) & 3);\n }\n\n public void RotateAnitclockwise90 ()\n {\n m_rotation = (Rotation) (((int) m_rotation + 3) & 3);\n }\n\n // accessor property to make class look like a two dimensional array\n public int this [int row, int column]\n {\n get\n {\n int\n value = 0;\n\n switch (m_rotation)\n {\n case Rotation.None:\n value = m_matrix [row, column];\n break;\n\n case Rotation.Clockwise90:\n value = m_matrix [m_matrix.GetUpperBound (0) - column, row];\n break;\n\n case Rotation.Clockwise180:\n value = m_matrix [m_matrix.GetUpperBound (0) - row, m_matrix.GetUpperBound (1) - column];\n break;\n\n case Rotation.Clockwise270:\n value = m_matrix [column, m_matrix.GetUpperBound (1) - row];\n break;\n }\n\n return value;\n }\n\n set\n {\n switch (m_rotation)\n {\n case Rotation.None:\n m_matrix [row, column] = value;\n break;\n\n case Rotation.Clockwise90:\n m_matrix [m_matrix.GetUpperBound (0) - column, row] = value;\n break;\n\n case Rotation.Clockwise180:\n m_matrix [m_matrix.GetUpperBound (0) - row, m_matrix.GetUpperBound (1) - column] = value;\n break;\n\n case Rotation.Clockwise270:\n m_matrix [column, m_matrix.GetUpperBound (1) - row] = value;\n break;\n }\n }\n }\n\n // creates a string with the matrix values\n public override string ToString ()\n {\n int\n num_rows = 0,\n num_columns = 0;\n\n switch (m_rotation)\n {\n case Rotation.None:\n case Rotation.Clockwise180:\n num_rows = m_matrix.GetUpperBound (0);\n num_columns = m_matrix.GetUpperBound (1);\n break;\n\n case Rotation.Clockwise90:\n case Rotation.Clockwise270:\n num_rows = m_matrix.GetUpperBound (1);\n num_columns = m_matrix.GetUpperBound (0);\n break;\n }\n\n StringBuilder\n output = new StringBuilder ();\n\n output.Append (\"{\");\n\n for (int row = 0 ; row <= num_rows ; ++row)\n {\n if (row != 0)\n {\n output.Append (\", \");\n }\n\n output.Append (\"{\");\n\n for (int column = 0 ; column <= num_columns ; ++column)\n {\n if (column != 0)\n {\n output.Append (\", \");\n }\n\n output.Append (this [row, column].ToString ());\n }\n\n output.Append (\"}\");\n }\n\n output.Append (\"}\");\n\n return output.ToString ();\n }\n\n int [,]\n // the original matrix\n m_matrix;\n\n Rotation\n // the current view of the matrix\n m_rotation;\n}\n</code></pre>\n\n<p>OK, I'll put my hand up, it doesn't actually do any modifications to the original array when rotating. But, in an OO system that doesn't matter as long as the object looks like it's been rotated to the clients of the class. At the moment, the Matrix class uses references to the original array data so changing any value of m1 will also change m2 and m3. A small change to the constructor to create a new array and copy the values to it will sort that out.</p>\n"
},
{
"answer_id": 44368,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 6,
"selected": false,
"text": "<p>Here is one that does the rotation in place instead of using a completely new array to hold the result. I've left off initialization of the array and printing it out. This only works for square arrays but they can be of any size. Memory overhead is equal to the size of one element of the array so you can do the rotation of as large an array as you want.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int a[4][4];\nint n = 4;\nint tmp;\nfor (int i = 0; i < n / 2; i++)\n{\n for (int j = i; j < n - i - 1; j++)\n {\n tmp = a[i][j];\n a[i][j] = a[j][n-i-1];\n a[j][n-i-1] = a[n-i-1][n-j-1];\n a[n-i-1][n-j-1] = a[n-j-1][i];\n a[n-j-1][i] = tmp;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 48607,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 1,
"selected": false,
"text": "<p>@dagorym: Aw, man. I had been hanging onto this as a good \"I'm bored, what can I ponder\" puzzle. I came up with my in-place transposition code, but got here to find yours pretty much identical to mine...ah, well. Here it is in Ruby.</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>require 'pp'\nn = 10\na = []\nn.times { a << (1..n).to_a }\n\npp a\n\n0.upto(n/2-1) do |i|\n i.upto(n-i-2) do |j|\n tmp = a[i][j]\n a[i][j] = a[n-j-1][i]\n a[n-j-1][i] = a[n-i-1][n-j-1]\n a[n-i-1][n-j-1] = a[j][n-i-1]\n a[j][n-i-1] = tmp\n end\nend\n\npp a\n</code></pre>\n"
},
{
"answer_id": 193942,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 5,
"selected": false,
"text": "<p>Whilst rotating the data in place might be necessary (perhaps to update the physically stored representation), it becomes simpler and possibly more performant to add a layer of indirection onto the array access, perhaps an interface:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>interface IReadableMatrix\n{\n int GetValue(int x, int y);\n}\n</code></pre>\n\n<p>If your <code>Matrix</code> already implements this interface, then it can be rotated via a <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"noreferrer\">decorator</a> class like this:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>class RotatedMatrix : IReadableMatrix\n{\n private readonly IReadableMatrix _baseMatrix;\n\n public RotatedMatrix(IReadableMatrix baseMatrix)\n {\n _baseMatrix = baseMatrix;\n }\n\n int GetValue(int x, int y)\n {\n // transpose x and y dimensions\n return _baseMatrix(y, x);\n }\n}\n</code></pre>\n\n<p>Rotating +90/-90/180 degrees, flipping horizontally/vertically and scaling can all be achieved in this fashion as well.</p>\n\n<p>Performance would need to be measured in your specific scenario. However the O(n^2) operation has now been replaced with an O(1) call. It's a virtual method call which <em>is</em> slower than direct array access, so it depends upon how frequently the rotated array is used after rotation. If it's used once, then this approach would definitely win. If it's rotated then used in a long-running system for days, then in-place rotation might perform better. It also depends whether you can accept the up-front cost.</p>\n\n<p>As with all performance issues, measure, measure, measure!</p>\n"
},
{
"answer_id": 496056,
"author": "recursive",
"author_id": 44743,
"author_profile": "https://Stackoverflow.com/users/44743",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Python:</strong></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>rotated = list(zip(*original[::-1]))\n</code></pre>\n\n<p>and counterclockwise:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>rotated_ccw = list(zip(*original))[::-1]\n</code></pre>\n\n<p><strong>How this works:</strong></p>\n\n<p><code>zip(*original)</code> will swap axes of 2d arrays by stacking corresponding items from lists into new lists. (The <a href=\"https://docs.python.org/reference/expressions.html#calls\" rel=\"noreferrer\"><code>*</code> operator</a> tells the function to distribute the contained lists into arguments)</p>\n\n<pre><code>>>> list(zip(*[[1,2,3],[4,5,6],[7,8,9]]))\n[[1,4,7],[2,5,8],[3,6,9]]\n</code></pre>\n\n<p>The <code>[::-1]</code> statement reverses array elements (please see <a href=\"https://docs.python.org/2.3/whatsnew/section-slices.html\" rel=\"noreferrer\">Extended Slices</a> or <a href=\"https://stackoverflow.com/questions/509211/understanding-slice-notation\">this question</a>):</p>\n\n<pre><code>>>> [[1,2,3],[4,5,6],[7,8,9]][::-1]\n[[7,8,9],[4,5,6],[1,2,3]]\n</code></pre>\n\n<p>Finally, combining the two will result in the rotation transformation.</p>\n\n<p>The change in placement of <code>[::-1]</code> will reverse lists in different levels of the matrix.</p>\n"
},
{
"answer_id": 768796,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <iomanip>\n\nusing namespace std;\nconst int SIZE=3;\nvoid print(int a[][SIZE],int);\nvoid rotate(int a[][SIZE],int);\n\nvoid main()\n{\n int a[SIZE][SIZE]={{11,22,33},{44,55,66},{77,88,99}};\n cout<<\"the array befor rotate\\n\";\n\n print(a,SIZE);\n rotate( a,SIZE);\n cout<<\"the array after rotate\\n\";\n print(a,SIZE);\n cout<<endl;\n\n}\n\nvoid print(int a[][SIZE],int SIZE)\n{\n int i,j;\n for(i=0;i<SIZE;i++)\n for(j=0;j<SIZE;j++)\n cout<<a[i][j]<<setw(4);\n}\n\nvoid rotate(int a[][SIZE],int SIZE)\n{\n int temp[3][3],i,j;\n for(i=0;i<SIZE;i++)\n for(j=0;j<SIZE/2.5;j++)\n {\n temp[i][j]= a[i][j];\n a[i][j]= a[j][SIZE-i-1] ;\n a[j][SIZE-i-1] =temp[i][j];\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 948280,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre class=\"lang-cpp prettyprint-override\"><code>short normal[4][4] = {{8,4,7,5},{3,4,5,7},{9,5,5,6},{3,3,3,3}};\n\nshort rotated[4][4];\n\nfor (int r = 0; r < 4; ++r)\n{\n for (int c = 0; c < 4; ++c)\n {\n rotated[r][c] = normal[c][3-r];\n }\n}\n</code></pre>\n\n<p>Simple C++ method, tho there would be a big memory overhead in a big array.</p>\n"
},
{
"answer_id": 1092721,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>This a better version of it in Java: I've made it for a matrix with a different width and height</p>\n\n<ul>\n<li>h is here the height of the matrix after rotating</li>\n<li>w is here the width of the matrix after rotating</li>\n</ul>\n\n<p> </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public int[][] rotateMatrixRight(int[][] matrix)\n{\n /* W and H are already swapped */\n int w = matrix.length;\n int h = matrix[0].length;\n int[][] ret = new int[h][w];\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n ret[i][j] = matrix[w - j - 1][i];\n }\n }\n return ret;\n}\n\n\npublic int[][] rotateMatrixLeft(int[][] matrix)\n{\n /* W and H are already swapped */\n int w = matrix.length;\n int h = matrix[0].length; \n int[][] ret = new int[h][w];\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n ret[i][j] = matrix[j][h - i - 1];\n }\n }\n return ret;\n}\n</code></pre>\n\n<p>This code is based on Nick Berardi's post.</p>\n"
},
{
"answer_id": 3137413,
"author": "James Lin",
"author_id": 342553,
"author_profile": "https://Stackoverflow.com/users/342553",
"pm_score": 2,
"selected": false,
"text": "<p>PHP:</p>\n\n<pre><code><?php \n$a = array(array(1,2,3,4),array(5,6,7,8),array(9,0,1,2),array(3,4,5,6));\n$b = array(); //result\n\nwhile(count($a)>0)\n{\n $b[count($a[0])-1][] = array_shift($a[0]);\n if (count($a[0])==0)\n {\n array_shift($a);\n }\n}\n</code></pre>\n\n<p>From PHP5.6, Array transposition can be performed with a sleak <code>array_map()</code> call. In other words, columns are converted to rows.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/pIl5n\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$array = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 0, 1, 2],\n [3, 4, 5, 6]\n];\n$transposed = array_map(null, ...$array);\n</code></pre>\n\n<p>$transposed:</p>\n\n<pre><code>[\n [1, 5, 9, 3],\n [2, 6, 0, 4],\n [3, 7, 1, 5],\n [4, 8, 2, 6]\n]\n</code></pre>\n"
},
{
"answer_id": 3137649,
"author": "Clark Gaebel",
"author_id": 105760,
"author_profile": "https://Stackoverflow.com/users/105760",
"pm_score": 0,
"selected": false,
"text": "<p>All the current solutions have O(n^2) overhead as scratch space (this excludes those filthy OOP cheaters!). Here's a solution with O(1) memory usage, rotating the matrix in-place 90 degress right. Screw extensibility, this sucker runs fast!</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <algorithm>\n#include <cstddef>\n\n// Rotates an NxN matrix of type T 90 degrees to the right.\ntemplate <typename T, size_t N>\nvoid rotate_matrix(T (&matrix)[N][N])\n{\n for(size_t i = 0; i < N; ++i)\n for(size_t j = 0; j <= (N-i); ++j)\n std::swap(matrix[i][j], matrix[j][i]);\n}\n</code></pre>\n\n<p>DISCLAIMER: I didn't actually test this. Let's play whack-a-bug!</p>\n"
},
{
"answer_id": 3571501,
"author": "Nakilon",
"author_id": 322020,
"author_profile": "https://Stackoverflow.com/users/322020",
"pm_score": 4,
"selected": false,
"text": "<p>Ruby-way: <code>.transpose.map &:reverse</code></p>\n"
},
{
"answer_id": 8664879,
"author": "dimple",
"author_id": 1120601,
"author_profile": "https://Stackoverflow.com/users/1120601",
"pm_score": 9,
"selected": false,
"text": "<p><strong>O(n^2) time and O(1) space algorithm</strong> ( without any workarounds and hanky-panky stuff! )</p>\n\n<p><strong>Rotate by +90:</strong></p>\n\n<ol>\n<li>Transpose</li>\n<li>Reverse each row</li>\n</ol>\n\n<p><strong>Rotate by -90:</strong></p>\n\n<p><em>Method 1 :</em></p>\n\n<ol>\n<li>Transpose</li>\n<li>Reverse each column</li>\n</ol>\n\n<p><em>Method 2 :</em></p>\n\n<ol>\n<li>Reverse each row</li>\n<li>Transpose</li>\n</ol>\n\n<p><strong>Rotate by +180:</strong></p>\n\n<p><em>Method 1</em>: Rotate by +90 twice</p>\n\n<p><em>Method 2</em>: Reverse each row and then reverse each column (Transpose)</p>\n\n<p><strong>Rotate by -180:</strong></p>\n\n<p><em>Method 1</em>: Rotate by -90 twice</p>\n\n<p><em>Method 2</em>: Reverse each column and then reverse each row</p>\n\n<p><em>Method 3</em>: Rotate by +180 as they are same</p>\n"
},
{
"answer_id": 8668894,
"author": "Turk",
"author_id": 1121328,
"author_profile": "https://Stackoverflow.com/users/1121328",
"pm_score": 1,
"selected": false,
"text": "<p><code>For i:= 0 to X do\n For j := 0 to X do\n graphic[j][i] := graphic2[X-i][j]</code></p>\n\n<p>X is the size of the array the graphic is in.</p>\n"
},
{
"answer_id": 9711525,
"author": "James Yu",
"author_id": 1270299,
"author_profile": "https://Stackoverflow.com/users/1270299",
"pm_score": 2,
"selected": false,
"text": "<p>here's a in-space rotate method, by java, only for square. for non-square 2d array, you will have to create new array anyway.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void rotateInSpace(int[][] arr) {\n int z = arr.length;\n for (int i = 0; i < z / 2; i++) {\n for (int j = 0; j < (z / 2 + z % 2); j++) {\n int x = i, y = j;\n int temp = arr[x][y];\n for (int k = 0; k < 4; k++) {\n int temptemp = arr[y][z - x - 1];\n arr[y][z - x - 1] = temp;\n temp = temptemp;\n\n int tempX = y;\n y = z - x - 1;\n x = tempX;\n }\n }\n }\n}\n</code></pre>\n\n<p>code to rotate any size 2d array by creating new array:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private int[][] rotate(int[][] arr) {\n int width = arr[0].length;\n int depth = arr.length;\n int[][] re = new int[width][depth];\n for (int i = 0; i < depth; i++) {\n for (int j = 0; j < width; j++) {\n re[j][depth - i - 1] = arr[i][j];\n }\n }\n return re;\n}\n</code></pre>\n"
},
{
"answer_id": 10021595,
"author": "Spidey",
"author_id": 131326,
"author_profile": "https://Stackoverflow.com/users/131326",
"pm_score": 2,
"selected": false,
"text": "<p>This is my implementation, in C, O(1) memory complexity, in place rotation, 90 degrees clockwise:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\n#define M_SIZE 5\n\nstatic void initMatrix();\nstatic void printMatrix();\nstatic void rotateMatrix();\n\nstatic int m[M_SIZE][M_SIZE];\n\nint main(void){\n initMatrix();\n printMatrix();\n rotateMatrix();\n printMatrix();\n\n return 0;\n}\n\nstatic void initMatrix(){\n int i, j;\n\n for(i = 0; i < M_SIZE; i++){\n for(j = 0; j < M_SIZE; j++){\n m[i][j] = M_SIZE*i + j + 1;\n }\n }\n}\n\nstatic void printMatrix(){\n int i, j;\n\n printf(\"Matrix\\n\");\n for(i = 0; i < M_SIZE; i++){\n for(j = 0; j < M_SIZE; j++){\n printf(\"%02d \", m[i][j]);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\nstatic void rotateMatrix(){\n int r, c;\n\n for(r = 0; r < M_SIZE/2; r++){\n for(c = r; c < M_SIZE - r - 1; c++){\n int tmp = m[r][c];\n\n m[r][c] = m[M_SIZE - c - 1][r];\n m[M_SIZE - c - 1][r] = m[M_SIZE - r - 1][M_SIZE - c - 1];\n m[M_SIZE - r - 1][M_SIZE - c - 1] = m[c][M_SIZE - r - 1];\n m[c][M_SIZE - r - 1] = tmp;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11695638,
"author": "k00ka",
"author_id": 3410287,
"author_profile": "https://Stackoverflow.com/users/3410287",
"pm_score": 1,
"selected": false,
"text": "<p>#transpose is a standard method of Ruby's Array class, thus:</p>\n\n<pre><code>% irb\nirb(main):001:0> m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6]]\n=> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6]] \nirb(main):002:0> m.reverse.transpose\n=> [[3, 9, 5, 1], [4, 0, 6, 2], [5, 1, 7, 3], [6, 2, 8, 4]]\n</code></pre>\n\n<p>The implementation is an n^2 transposition function written in C. You can see it here:\n<a href=\"http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-transpose\" rel=\"nofollow\">http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-transpose</a>\nby choosing \"click to toggle source\" beside \"transpose\".</p>\n\n<p>I recall better than O(n^2) solutions, but only for specially constructed matrices (such as sparse matrices)</p>\n"
},
{
"answer_id": 15073652,
"author": "rohitmb",
"author_id": 2108332,
"author_profile": "https://Stackoverflow.com/users/2108332",
"pm_score": 1,
"selected": false,
"text": "<p>C code for matrix rotation 90 degree clockwise IN PLACE for any M*N matrix</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void rotateInPlace(int * arr[size][size], int row, int column){\n int i, j;\n int temp = row>column?row:column;\n int flipTill = row < column ? row : column;\n for(i=0;i<flipTill;i++){\n for(j=0;j<i;j++){\n swapArrayElements(arr, i, j);\n }\n }\n\n temp = j+1;\n\n for(i = row>column?i:0; i<row; i++){\n for(j=row<column?temp:0; j<column; j++){\n swapArrayElements(arr, i, j);\n }\n }\n\n for(i=0;i<column;i++){\n for(j=0;j<row/2;j++){\n temp = arr[i][j];\n arr[i][j] = arr[i][row-j-1];\n arr[i][row-j-1] = temp;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 15432619,
"author": "user1596193",
"author_id": 1596193,
"author_profile": "https://Stackoverflow.com/users/1596193",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my attempt for matrix 90 deg rotation which is a 2 step solution in C. First transpose the matrix in place and then swap the cols.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define ROWS 5\n#define COLS 5\n\nvoid print_matrix_b(int B[][COLS], int rows, int cols) \n{\n for (int i = 0; i <= rows; i++) {\n for (int j = 0; j <=cols; j++) {\n printf(\"%d \", B[i][j]);\n }\n printf(\"\\n\");\n }\n}\n\nvoid swap_columns(int B[][COLS], int l, int r, int rows)\n{\n int tmp;\n for (int i = 0; i <= rows; i++) {\n tmp = B[i][l];\n B[i][l] = B[i][r];\n B[i][r] = tmp;\n }\n}\n\n\nvoid matrix_2d_rotation(int B[][COLS], int rows, int cols)\n{\n int tmp;\n // Transpose the matrix first\n for (int i = 0; i <= rows; i++) {\n for (int j = i; j <=cols; j++) {\n tmp = B[i][j];\n B[i][j] = B[j][i];\n B[j][i] = tmp;\n }\n }\n // Swap the first and last col and continue until\n // the middle.\n for (int i = 0; i < (cols / 2); i++)\n swap_columns(B, i, cols - i, rows);\n}\n\n\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n int B[ROWS][COLS] = { \n {1, 2, 3, 4, 5}, \n {6, 7, 8, 9, 10},\n {11, 12, 13, 14, 15},\n {16, 17, 18, 19, 20},\n {21, 22, 23, 24, 25}\n };\n\n matrix_2d_rotation(B, ROWS - 1, COLS - 1);\n\n print_matrix_b(B, ROWS - 1, COLS -1);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 15501334,
"author": "ramon.liu",
"author_id": 2025792,
"author_profile": "https://Stackoverflow.com/users/2025792",
"pm_score": -1,
"selected": false,
"text": "<p>The O(1) memory algorithm:</p>\n\n<ol>\n<li><p>rotate the outer-most data, then you can get below result:</p>\n\n<pre><code>[3][9][5][1]\n[4][6][7][2]\n[5][0][1][3]\n[6][2][8][4]\n</code></pre></li>\n</ol>\n\n<p>To do this rotation, we know </p>\n\n<pre><code> dest[j][n-1-i] = src[i][j]\n</code></pre>\n\n<p>Observe below: \n a(0,0) -> a(0,3)\n a(0,3) -> a(3,3)\n a(3,3) -> a(3,0)\n a(3,0) -> a(0,0)</p>\n\n<p>Therefore it's a circle, you can rotate N elements in one loop. Do this N-1 loop then you can rotate the outer-most elements.</p>\n\n<ol>\n<li>Now you can the inner is a same question for 2X2. </li>\n</ol>\n\n<p>Therefore we can conclude it like below:</p>\n\n<pre><code>function rotate(array, N)\n{\n Rotate outer-most data\n rotate a new array with N-2 or you can do the similar action following step1\n}\n</code></pre>\n"
},
{
"answer_id": 16661397,
"author": "radium",
"author_id": 1642753,
"author_profile": "https://Stackoverflow.com/users/1642753",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the Java version:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void rightRotate(int[][] matrix, int n) {\n for (int layer = 0; layer < n / 2; layer++) {\n int first = layer;\n int last = n - 1 - first;\n for (int i = first; i < last; i++) {\n int offset = i - first;\n int temp = matrix[first][i];\n matrix[first][i] = matrix[last-offset][first];\n matrix[last-offset][first] = matrix[last][last-offset];\n matrix[last][last-offset] = matrix[i][last];\n matrix[i][last] = temp;\n }\n }\n}\n</code></pre>\n\n<p>the method first rotate the mostouter layer, then move to the inner layer squentially.</p>\n"
},
{
"answer_id": 18013355,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre class=\"lang-java prettyprint-override\"><code>private static int[][] rotate(int[][] matrix, int n) {\n int[][] rotated = new int[n][n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n rotated[i][j] = matrix[n-j-1][i];\n }\n }\n return rotated;\n}\n</code></pre>\n"
},
{
"answer_id": 18215843,
"author": "thiagoh",
"author_id": 889213,
"author_profile": "https://Stackoverflow.com/users/889213",
"pm_score": 1,
"selected": false,
"text": "<p>here is my In Place implementation in C</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void rotateRight(int matrix[][SIZE], int length) {\n\n int layer = 0;\n\n for (int layer = 0; layer < length / 2; ++layer) {\n\n int first = layer;\n int last = length - 1 - layer;\n\n for (int i = first; i < last; ++i) {\n\n int topline = matrix[first][i];\n int rightcol = matrix[i][last];\n int bottomline = matrix[last][length - layer - 1 - i];\n int leftcol = matrix[length - layer - 1 - i][first];\n\n matrix[first][i] = leftcol;\n matrix[i][last] = topline;\n matrix[last][length - layer - 1 - i] = rightcol;\n matrix[length - layer - 1 - i][first] = bottomline;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18262380,
"author": "mhawksey",
"author_id": 1027723,
"author_profile": "https://Stackoverflow.com/users/1027723",
"pm_score": 2,
"selected": false,
"text": "<p>Implementation of dimple's +90 pseudocode (e.g. transpose then reverse each row) in JavaScript:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function rotate90(a){\n // transpose from http://www.codesuck.com/2012/02/transpose-javascript-array-in-one-line.html\n a = Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });\n // row reverse\n for (i in a){\n a[i] = a[i].reverse();\n }\n return a;\n}\n</code></pre>\n"
},
{
"answer_id": 20199933,
"author": "tweaking",
"author_id": 2716562,
"author_profile": "https://Stackoverflow.com/users/2716562",
"pm_score": 5,
"selected": false,
"text": "<p>There are tons of good code here but I just want to show what's going on geometrically so you can understand the code logic a little better. Here is how I would approach this.</p>\n\n<p>first of all, do not confuse this with transposition which is very easy..</p>\n\n<p>the basica idea is to treat it as layers and we rotate one layer at a time..</p>\n\n<p>say we have a 4x4</p>\n\n<pre><code>1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n</code></pre>\n\n<p>after we rotate it clockwise by 90 we get</p>\n\n<pre><code>13 9 5 1\n14 10 6 2 \n15 11 7 3\n16 12 8 4\n</code></pre>\n\n<p>so let's decompose this, first we rotate the 4 corners essentially</p>\n\n<pre><code>1 4\n\n\n13 16\n</code></pre>\n\n<p>then we rotate the following diamond which is sort of askew</p>\n\n<pre><code> 2\n 8\n9 \n 15\n</code></pre>\n\n<p>and then the 2nd skewed diamond</p>\n\n<pre><code> 3\n5 \n 12\n 14\n</code></pre>\n\n<p>so that takes care of the outer edge so essentially we do that one shell at a time until </p>\n\n<p>finally the middle square (or if it's odd just the final element which does not move)</p>\n\n<pre><code>6 7\n10 11\n</code></pre>\n\n<p>so now let's figure out the indices of each layer, assume we always work with the outermost layer, we are doing</p>\n\n<pre><code>[0,0] -> [0,n-1], [0,n-1] -> [n-1,n-1], [n-1,n-1] -> [n-1,0], and [n-1,0] -> [0,0]\n[0,1] -> [1,n-1], [1,n-2] -> [n-1,n-2], [n-1,n-2] -> [n-2,0], and [n-2,0] -> [0,1]\n[0,2] -> [2,n-2], [2,n-2] -> [n-1,n-3], [n-1,n-3] -> [n-3,0], and [n-3,0] -> [0,2]\n</code></pre>\n\n<p>so on and so on\nuntil we are halfway through the edge</p>\n\n<p>so in general the pattern is </p>\n\n<pre><code>[0,i] -> [i,n-i], [i,n-i] -> [n-1,n-(i+1)], [n-1,n-(i+1)] -> [n-(i+1),0], and [n-(i+1),0] to [0,i]\n</code></pre>\n"
},
{
"answer_id": 20202797,
"author": "user3000711",
"author_id": 3000711,
"author_profile": "https://Stackoverflow.com/users/3000711",
"pm_score": -1,
"selected": false,
"text": "<p>It is not possible to do it quicker than O(n^2) for in place rotation, for the reason that if we want to rotate the matrix, we have to touch all the n^2 element at least once, no matter what algorithm you are implementing.</p>\n"
},
{
"answer_id": 21265476,
"author": "user2793692",
"author_id": 2793692,
"author_profile": "https://Stackoverflow.com/users/2793692",
"pm_score": 3,
"selected": false,
"text": "<p>Time - O(N), Space - O(1)</p>\n\n<pre><code>public void rotate(int[][] matrix) {\n int n = matrix.length;\n for (int i = 0; i < n / 2; i++) {\n int last = n - 1 - i;\n for (int j = i; j < last; j++) {\n int top = matrix[i][j];\n matrix[i][j] = matrix[last - j][i];\n matrix[last - j][i] = matrix[last][last - j];\n matrix[last][last - j] = matrix[j][last];\n matrix[j][last] = top;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 21977882,
"author": "taxicala",
"author_id": 2988337,
"author_profile": "https://Stackoverflow.com/users/2988337",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a recursive PHP way:</p>\n\n<pre><code>$m = array();\n $m[0] = array('a', 'b', 'c');\n $m[1] = array('d', 'e', 'f');\n $m[2] = array('g', 'h', 'i');\n $newMatrix = array();\n\n function rotateMatrix($m, $i = 0, &$newMatrix)\n {\n foreach ($m as $chunk) {\n $newChunk[] = $chunk[$i];\n }\n $newMatrix[] = array_reverse($newChunk);\n $i++;\n\n if ($i < count($m)) {\n rotateMatrix($m, $i, $newMatrix);\n }\n }\n\n rotateMatrix($m, 0, $newMatrix);\n echo '<pre>';\n var_dump($newMatrix);\n echo '<pre>';\n</code></pre>\n"
},
{
"answer_id": 22858585,
"author": "Alex",
"author_id": 3497339,
"author_profile": "https://Stackoverflow.com/users/3497339",
"pm_score": 0,
"selected": false,
"text": "<p>My version of rotation:</p>\n\n<pre><code>void rotate_matrix(int *matrix, int size)\n{\n\nint result[size*size];\n\n for (int i = 0; i < size; ++i)\n for (int j = 0; j < size; ++j)\n result[(size - 1 - i) + j*size] = matrix[i*size+j];\n\n for (int i = 0; i < size*size; ++i)\n matrix[i] = result[i];\n}\n</code></pre>\n\n<p>In it we change last column to first row and so further. It is may be not optimal but clear for understanding.</p>\n"
},
{
"answer_id": 23486371,
"author": "user4964091",
"author_id": 4964091,
"author_profile": "https://Stackoverflow.com/users/4964091",
"pm_score": -1,
"selected": false,
"text": "<p><strong>For Novice programmers, in plain C++ . (Borland stuff)</strong> </p>\n\n<pre><code>#include<iostream.h>\n#include<conio.h>\n\nint main()\n{\n clrscr();\n\n int arr[10][10]; // 2d array that holds input elements \n int result[10][10]; //holds result\n\n int m,n; //rows and columns of arr[][]\n int x,y; //rows and columns of result[][]\n\n int i,j; //loop variables\n int t; //temporary , holds data while conversion\n\n cout<<\"Enter no. of rows and columns of array: \";\n cin>>m>>n;\n cout<<\"\\nEnter elements of array: \\n\\n\";\n for(i = 0; i < m; i++)\n {\n for(j = 0; j<n ; j++)\n {\n cin>>arr[i][j]; // input array elements from user\n }\n }\n\n\n //rotating matrix by +90 degrees\n\n x = n ; //for non-square matrix\n y = m ; \n\n for(i = 0; i < x; i++)\n { t = m-1; // to create required array bounds\n for(j = 0; j < y; j++)\n {\n result[i][j] = arr[t][i];\n t--;\n }\n }\n\n //print result\n\n cout<<\"\\nRotated matrix is: \\n\\n\";\n for(i = 0; i < x; i++)\n {\n for(j = 0; j < y; j++)\n {\n cout<<result[i][j]<<\" \";\n }\n cout<<\"\\n\";\n }\n\n getch();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 24356420,
"author": "Paul Calabro",
"author_id": 517137,
"author_profile": "https://Stackoverflow.com/users/517137",
"pm_score": -1,
"selected": false,
"text": "<pre><code>#!/usr/bin/env python\n\noriginal = [ [1,2,3],\n [4,5,6],\n [7,8,9] ]\n\n# Rotate matrix 90 degrees...\nfor i in map(None,*original[::-1]):\n print str(i) + '\\n'\n</code></pre>\n\n<p>This causes the sides to be rotated 90 degrees (ie. 123 (top side) is now 741 (left side).</p>\n\n<p>This Python solution works because it uses slicing with a negative step to reverse the row orders (bringing 7 to top)</p>\n\n<pre><code>original = [ [7,8,9],\n [4,5,6],\n [1,2,3] ]\n</code></pre>\n\n<p>It then uses map (along with the implied identity function which is the result of map with None as first arg) along with * to unpack all elements in sequence, to regroup the columns (ie. the first elements are put in a tuple together, the 2nd elements are put in a tuple together, and so forth). You effectively get get returned the following regrouping:</p>\n\n<pre><code>original = [[7,8,9],\n [4,5,6],\n [1,2,3]]\n</code></pre>\n"
},
{
"answer_id": 26180084,
"author": "obotezat",
"author_id": 373108,
"author_profile": "https://Stackoverflow.com/users/373108",
"pm_score": -1,
"selected": false,
"text": "<p><strong>PHP:</strong></p>\n\n<pre><code>array_unshift($array, null);\n$array = call_user_func_array(\"array_map\", $array);\n</code></pre>\n\n<p>If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:</p>\n\n<pre><code>$array = array_reverse($array);\n</code></pre>\n"
},
{
"answer_id": 26320746,
"author": "Mr. Nex",
"author_id": 3680827,
"author_profile": "https://Stackoverflow.com/users/3680827",
"pm_score": 2,
"selected": false,
"text": "<p>From a linear point of view, consider the matrices:</p>\n\n<pre><code> 1 2 3 0 0 1\nA = 4 5 6 B = 0 1 0\n 7 8 9 1 0 0\n</code></pre>\n\n<p>Now take A transpose</p>\n\n<pre><code> 1 4 7\nA' = 2 5 8\n 3 6 9\n</code></pre>\n\n<p>And consider the action of A' on B, or B on A'.<br>\nRespectively:</p>\n\n<pre><code> 7 4 1 3 6 9\nA'B = 8 5 2 BA' = 2 5 8\n 9 6 3 1 4 7\n</code></pre>\n\n<p>This is expandable for any n x n matrix.\nAnd applying this concept quickly in code:</p>\n\n<pre><code>void swapInSpace(int** mat, int r1, int c1, int r2, int c2)\n{\n mat[r1][c1] ^= mat[r2][c2];\n mat[r2][c2] ^= mat[r1][c1];\n mat[r1][c1] ^= mat[r2][c2];\n}\n\nvoid transpose(int** mat, int size)\n{\n for (int i = 0; i < size; i++)\n {\n for (int j = (i + 1); j < size; j++)\n {\n swapInSpace(mat, i, j, j, i);\n }\n }\n}\n\nvoid rotate(int** mat, int size)\n{\n //Get transpose\n transpose(mat, size);\n\n //Swap columns\n for (int i = 0; i < size / 2; i++)\n {\n for (int j = 0; j < size; j++)\n {\n swapInSpace(mat, i, j, size - (i + 1), j);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 26374543,
"author": "Jason Oster",
"author_id": 466030,
"author_profile": "https://Stackoverflow.com/users/466030",
"pm_score": 4,
"selected": false,
"text": "<p>There are a lot of answers already, and I found two claiming O(1) time complexity. The <strong>real</strong> O(1) algorithm is to leave the array storage untouched, and change how you index its elements. The goal here is that it does not consume additional memory, nor does it require additional time to iterate the data.</p>\n\n<p>Rotations of 90, -90 and 180 degrees are simple transformations which can be performed as long as you know how many rows and columns are in your 2D array; To rotate any vector by 90 degrees, swap the axes and negate the Y axis. For -90 degree, swap the axes and negate the X axis. For 180 degrees, negate both axes without swapping.</p>\n\n<p>Further transformations are possible, such as mirroring horizontally and/or vertically by negating the axes independently.</p>\n\n<p>This can be done through e.g. an accessor method. The examples below are JavaScript functions, but the concepts apply equally to all languages.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> // Get an array element in column/row order\r\n var getArray2d = function(a, x, y) {\r\n return a[y][x];\r\n };\r\n\r\n //demo\r\n var arr = [\r\n [5, 4, 6],\r\n [1, 7, 9],\r\n [-2, 11, 0],\r\n [8, 21, -3],\r\n [3, -1, 2]\r\n ];\r\n\r\n var newarr = [];\r\n arr[0].forEach(() => newarr.push(new Array(arr.length)));\r\n\r\n for (var i = 0; i < newarr.length; i++) {\r\n for (var j = 0; j < newarr[0].length; j++) {\r\n newarr[i][j] = getArray2d(arr, i, j);\r\n }\r\n }\r\n console.log(newarr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Get an array element rotated 90 degrees clockwise\r\nfunction getArray2dCW(a, x, y) {\r\n var t = x;\r\n x = y;\r\n y = a.length - t - 1;\r\n return a[y][x];\r\n}\r\n\r\n//demo\r\nvar arr = [\r\n [5, 4, 6],\r\n [1, 7, 9],\r\n [-2, 11, 0],\r\n [8, 21, -3],\r\n [3, -1, 2]\r\n];\r\n\r\nvar newarr = [];\r\narr[0].forEach(() => newarr.push(new Array(arr.length)));\r\n\r\nfor (var i = 0; i < newarr[0].length; i++) {\r\n for (var j = 0; j < newarr.length; j++) {\r\n newarr[j][i] = getArray2dCW(arr, i, j);\r\n }\r\n}\r\nconsole.log(newarr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Get an array element rotated 90 degrees counter-clockwise\r\nfunction getArray2dCCW(a, x, y) {\r\n var t = x;\r\n x = a[0].length - y - 1;\r\n y = t;\r\n return a[y][x];\r\n}\r\n\r\n//demo\r\nvar arr = [\r\n [5, 4, 6],\r\n [1, 7, 9],\r\n [-2, 11, 0],\r\n [8, 21, -3],\r\n [3, -1, 2]\r\n];\r\n\r\nvar newarr = [];\r\narr[0].forEach(() => newarr.push(new Array(arr.length)));\r\n\r\nfor (var i = 0; i < newarr[0].length; i++) {\r\n for (var j = 0; j < newarr.length; j++) {\r\n newarr[j][i] = getArray2dCCW(arr, i, j);\r\n }\r\n}\r\nconsole.log(newarr);</code></pre>\r\n</div>\r\n</div>\r\n</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>// Get an array element rotated 180 degrees\r\nfunction getArray2d180(a, x, y) {\r\n x = a[0].length - x - 1;\r\n y = a.length - y - 1;\r\n return a[y][x];\r\n}\r\n\r\n//demo\r\nvar arr = [\r\n [5, 4, 6],\r\n [1, 7, 9],\r\n [-2, 11, 0],\r\n [8, 21, -3],\r\n [3, -1, 2]\r\n];\r\n\r\nvar newarr = [];\r\narr.forEach(() => newarr.push(new Array(arr[0].length)));\r\n\r\nfor (var i = 0; i < newarr[0].length; i++) {\r\n for (var j = 0; j < newarr.length; j++) {\r\n newarr[j][i] = getArray2d180(arr, i, j);\r\n }\r\n}\r\nconsole.log(newarr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This code assumes an array of nested arrays, where each inner array is a row.</p>\n\n<p>The method allows you to read (or write) elements (even in random order) as if the array has been rotated or transformed. Now just pick the right function to call, probably by reference, and away you go!</p>\n\n<p>The concept can be extended to apply transformations additively (and non-destructively) through the accessor methods. Including arbitrary angle rotations and scaling.</p>\n"
},
{
"answer_id": 27161656,
"author": "spark",
"author_id": 4279802,
"author_profile": "https://Stackoverflow.com/users/4279802",
"pm_score": -1,
"selected": false,
"text": "<p>JavaScript solution to rotate matrix by 90 degrees in place:</p>\n\n<pre><code>function rotateBy90(m) {\n var length = m.length;\n //for each layer of the matrix\n for (var first = 0; first < length >> 1; first++) {\n var last = length - 1 - first;\n for (var i = first; i < last; i++) {\n var top = m[first][i]; //store top\n m[first][i] = m[last - i][first]; //top = left\n m[last - i][first] = m[last][last - i]; //left = bottom\n m[last][last - i] = m[i][last]; //bottom = right\n m[i][last] = top; //right = top\n }\n }\n return m;\n}\n</code></pre>\n"
},
{
"answer_id": 28610081,
"author": "ustmaestro",
"author_id": 2624626,
"author_profile": "https://Stackoverflow.com/users/2624626",
"pm_score": 2,
"selected": false,
"text": "<p>C# code to rotate [n,m] 2D arrays 90 deg right</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace MatrixProject\n{\n // mattrix class\n\n class Matrix{\n private int rows;\n private int cols;\n private int[,] matrix;\n\n public Matrix(int n){\n this.rows = n;\n this.cols = n;\n this.matrix = new int[this.rows,this.cols];\n\n }\n\n public Matrix(int n,int m){\n this.rows = n;\n this.cols = m;\n\n this.matrix = new int[this.rows,this.cols];\n }\n\n public void Show()\n {\n for (var i = 0; i < this.rows; i++)\n {\n for (var j = 0; j < this.cols; j++) {\n Console.Write(\"{0,3}\", this.matrix[i, j]);\n }\n Console.WriteLine();\n } \n }\n\n public void ReadElements()\n {\n for (var i = 0; i < this.rows; i++)\n for (var j = 0; j < this.cols; j++)\n {\n Console.Write(\"element[{0},{1}]=\",i,j);\n this.matrix[i, j] = Convert.ToInt32(Console.ReadLine());\n } \n }\n\n\n // rotate [n,m] 2D array by 90 deg right\n public void Rotate90DegRight()\n {\n\n // create a mirror of current matrix\n int[,] mirror = this.matrix;\n\n // create a new matrix\n this.matrix = new int[this.cols, this.rows];\n\n for (int i = 0; i < this.rows; i++)\n {\n for (int j = 0; j < this.cols; j++)\n {\n this.matrix[j, this.rows - i - 1] = mirror[i, j];\n }\n }\n\n // replace cols count with rows count\n int tmp = this.rows;\n this.rows = this.cols;\n this.cols = tmp; \n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n Matrix myMatrix = new Matrix(3,4);\n Console.WriteLine(\"Enter matrix elements:\");\n myMatrix.ReadElements();\n Console.WriteLine(\"Matrix elements are:\");\n myMatrix.Show();\n myMatrix.Rotate90DegRight();\n Console.WriteLine(\"Matrix rotated at 90 deg are:\");\n myMatrix.Show();\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code> Enter matrix elements:\n element[0,0]=1\n element[0,1]=2\n element[0,2]=3\n element[0,3]=4\n element[1,0]=5\n element[1,1]=6\n element[1,2]=7\n element[1,3]=8\n element[2,0]=9\n element[2,1]=10\n element[2,2]=11\n element[2,3]=12\n Matrix elements are:\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n Matrix rotated at 90 deg are:\n 9 5 1\n 10 6 2\n 11 7 3\n 12 8 4\n</code></pre>\n"
},
{
"answer_id": 31079886,
"author": "Shiva",
"author_id": 5054208,
"author_profile": "https://Stackoverflow.com/users/5054208",
"pm_score": -1,
"selected": false,
"text": "<pre><code>/* 90-degree clockwise:\n temp_array = left_col\n left_col = bottom_row\n bottom_row = reverse(right_col)\n reverse(right_col) = reverse(top_row)\n reverse(top_row) = temp_array\n*/\nvoid RotateClockwise90(int ** arr, int lo, int hi) {\n\n if (lo >= hi) \n return;\n\n for (int i=lo; i<hi; i++) {\n int j = lo+hi-i;\n int temp = arr[i][lo];\n arr[i][lo] = arr[hi][i];\n arr[hi][i] = arr[j][hi];\n arr[j][hi] = arr[lo][j];\n arr[lo][j] = temp;\n }\n\n RotateClockwise90(arr, lo+1, hi-1);\n}\n</code></pre>\n"
},
{
"answer_id": 31904916,
"author": "asad_nitp",
"author_id": 5066038,
"author_profile": "https://Stackoverflow.com/users/5066038",
"pm_score": -1,
"selected": false,
"text": "<p>In place clock wise 90 degrees rotation using vector of vectors..</p>\n\n<pre><code> #include<iostream>\n #include<vector>\n #include<algorithm>\n using namespace std;\n //Rotate a Matrix by 90 degrees\nvoid rotateMatrix(vector<vector<int> > &matrix){\n int n=matrix.size();\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n swap(matrix[i][j],matrix[j][i]);\n }\n }\n for(int i=0;i<n;i++){\n reverse(matrix[i].begin(),matrix[i].end());\n }\n }\n\n int main(){\n\n int n;\n cout<<\"enter the size of the matrix:\"<<endl;\n while (cin >> n) {\n vector< vector<int> > m;\n cout<<\"enter the elements\"<<endl;\n for (int i = 0; i < n; i++) {\n m.push_back(vector<int>(n));\n for (int j = 0; j < n; j++)\n scanf(\"%d\", &m[i][j]);\n }\n cout<<\"the rotated matrix is:\"<<endl;\n rotateMatrix(m);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++)\n cout << m[i][j] << ' ';\n cout << endl;\n }\n }\n return 0;\n }\n</code></pre>\n"
},
{
"answer_id": 32344382,
"author": "Shawn",
"author_id": 404760,
"author_profile": "https://Stackoverflow.com/users/404760",
"pm_score": 1,
"selected": false,
"text": "<p>Javascript solution for NxN matrix with runtime O(N^2) and memory O(1)</p>\n\n<pre><code> function rotate90(matrix){\n var length = matrix.length\n for(var row = 0; row < (length / 2); row++){\n for(var col = row; col < ( length - 1 - row); col++){\n var tmpVal = matrix[row][col];\n for(var i = 0; i < 4; i++){\n var rowSwap = col;\n var colSwap = (length - 1) - row;\n var poppedVal = matrix[rowSwap][colSwap];\n matrix[rowSwap][colSwap] = tmpVal;\n tmpVal = poppedVal;\n col = colSwap;\n row = rowSwap;\n }\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 32940678,
"author": "gmohim",
"author_id": 4856100,
"author_profile": "https://Stackoverflow.com/users/4856100",
"pm_score": -1,
"selected": false,
"text": "<p>This is an overrated interview question these days.</p>\n\n<p>My suggestion is: Do not let the interviewer confuse you with their crazy suggestion about solving this problem. Use the whiteboard to draw the indexing of input array then draw the indexing of output array. Samples of column indexing before and after rotation shown below:</p>\n\n<pre><code>30 --> 00\n20 --> 01\n10 --> 02\n00 --> 03\n\n31 --> 10\n21 --> 11\n11 --> 12\n01 --> 13\n</code></pre>\n\n<p>Notice the number pattern after rotation.</p>\n\n<p>Provided below a clean cut Java solution. It is tested, and it works:</p>\n\n<pre><code> Input:\n M A C P \n B N L D \n Y E T S \n I W R Z \n\n Output:\n I Y B M \n W E N A \n R T L C \n Z S D P \n\n/**\n * (c) @author \"G A N MOHIM\"\n * Oct 3, 2015\n * RotateArrayNintyDegree.java\n */\npackage rotatearray;\n\npublic class RotateArrayNintyDegree {\n\n public char[][] rotateArrayNinetyDegree(char[][] input) {\n int k; // k is used to generate index for output array\n\n char[][] output = new char[input.length] [input[0].length];\n\n for (int i = 0; i < input.length; i++) {\n k = 0;\n for (int j = input.length-1; j >= 0; j--) {\n output[i][k] = input[j][i]; // note how i is used as column index, and j as row\n k++;\n }\n }\n\n return output;\n }\n\n public void printArray(char[][] charArray) {\n for (int i = 0; i < charArray.length; i++) {\n for (int j = 0; j < charArray[0].length; j++) {\n System.out.print(charArray[i][j] + \" \");\n }\n System.out.println();\n }\n\n\n }\n\n public static void main(String[] args) {\n char[][] input = \n { {'M', 'A', 'C', 'P'},\n {'B', 'N', 'L', 'D'},\n {'Y', 'E', 'T', 'S'},\n {'I', 'W', 'R', 'Z'}\n };\n\n char[][] output = new char[input.length] [input[0].length];\n\n RotateArrayNintyDegree rotationObj = new RotateArrayNintyDegree();\n rotationObj.printArray(input);\n\n System.out.println(\"\\n\");\n output = rotationObj.rotateArrayNinetyDegree(input);\n rotationObj.printArray(output);\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 34534812,
"author": "Prateek Joshi",
"author_id": 4281711,
"author_profile": "https://Stackoverflow.com/users/4281711",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this in <strong>3 easy steps</strong>:</p>\n\n<p><strong>1</strong>)Suppose we have a matrix</p>\n\n<pre><code> 1 2 3\n 4 5 6\n 7 8 9\n</code></pre>\n\n<p><strong>2</strong>)Take the transpose of the matrix</p>\n\n<pre><code> 1 4 7\n 2 5 8\n 3 6 9\n</code></pre>\n\n<p><strong>3</strong>)Interchange rows to get rotated matrix</p>\n\n<pre><code> 3 6 9\n 2 5 8\n 1 4 7\n</code></pre>\n\n<p><strong><em>Java</em> source code</strong> for this:</p>\n\n<pre><code>public class MyClass {\n\n public static void main(String args[]) {\n Demo obj = new Demo();\n /*initial matrix to rotate*/\n int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };\n int[][] transpose = new int[3][3]; // matrix to store transpose\n\n obj.display(matrix); // initial matrix\n\n obj.rotate(matrix, transpose); // call rotate method\n System.out.println();\n obj.display(transpose); // display the rotated matix\n }\n}\n\nclass Demo { \n public void rotate(int[][] mat, int[][] tran) {\n\n /* First take the transpose of the matrix */\n for (int i = 0; i < mat.length; i++) {\n for (int j = 0; j < mat.length; j++) {\n tran[i][j] = mat[j][i]; \n }\n }\n\n /*\n * Interchange the rows of the transpose matrix to get rotated\n * matrix\n */\n for (int i = 0, j = tran.length - 1; i != j; i++, j--) {\n for (int k = 0; k < tran.length; k++) {\n swap(i, k, j, k, tran);\n }\n }\n }\n\n public void swap(int a, int b, int c, int d, int[][] arr) {\n int temp = arr[a][b];\n arr[a][b] = arr[c][d];\n arr[c][d] = temp; \n }\n\n /* Method to display the matrix */\n public void display(int[][] arr) {\n for (int i = 0; i < arr.length; i++) {\n for (int j = 0; j < arr.length; j++) {\n System.out.print(arr[i][j] + \" \");\n }\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>1 2 3 \n4 5 6 \n7 8 9 \n\n3 6 9 \n2 5 8 \n1 4 7 \n</code></pre>\n"
},
{
"answer_id": 35113512,
"author": "user4313807",
"author_id": 4313807,
"author_profile": "https://Stackoverflow.com/users/4313807",
"pm_score": -1,
"selected": false,
"text": "<p>Here it is in Java:</p>\n\n<pre><code>public static void rotateInPlace(int[][] m) {\n for(int layer = 0; layer < m.length/2; layer++){\n int first = layer;\n int last = m.length - 1 - first;\n for(int i = first; i < last; i ++){\n int offset = i - first;\n int top = m[first][i];\n m[first][i] = m[last - offset][first];\n m[last - offset][first] = m[last][last - offset];\n m[last][last - offset] = m[i][last];\n m[i][last] = top;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 35438327,
"author": "Jack",
"author_id": 828547,
"author_profile": "https://Stackoverflow.com/users/828547",
"pm_score": 8,
"selected": false,
"text": "<p>I’d like to add a little more detail. In this answer, key concepts are repeated, the pace is slow and intentionally repetitive. The solution provided here is not the most syntactically compact, it is however, intended for those who wish to learn what matrix rotation is and the resulting implementation.</p>\n<p>Firstly, what is a matrix? For the purposes of this answer, a matrix is just a grid where the width and height are the same. Note, the width and height of a matrix can be different, but for simplicity, this tutorial considers only matrices with equal width and height (<em>square matrices</em>). And yes, <em>matrices</em> is the plural of matrix.</p>\n<p>Example matrices are: 2×2, 3×3 or 5×5. Or, more generally, N×N. A 2×2 matrix will have 4 squares because 2×2=4. A 5×5 matrix will have 25 squares because 5×5=25. Each square is called an element or entry. We’ll represent each element with a period (<code>.</code>) in the diagrams below:</p>\n<p>2×2 matrix</p>\n<pre><code>. .\n. .\n</code></pre>\n<p>3×3 matrix</p>\n<pre><code>. . .\n. . .\n. . .\n</code></pre>\n<p>4×4 matrix</p>\n<pre><code>. . . .\n. . . .\n. . . .\n. . . .\n</code></pre>\n<p>So, what does it mean to rotate a matrix? Let’s take a 2×2 matrix and put some numbers in each element so the rotation can be observed:</p>\n<pre><code>0 1\n2 3\n</code></pre>\n<p>Rotating this by 90 degrees gives us:</p>\n<pre><code>2 0\n3 1\n</code></pre>\n<p>We literally turned the whole matrix once to the right just like turning the steering wheel of a car. It may help to think of “tipping” the matrix onto its right side. We want to write a function, in Python, that takes a matrix and rotates it once to the right. The function signature will be:</p>\n<pre><code>def rotate(matrix):\n # Algorithm goes here.\n</code></pre>\n<p>The matrix will be defined using a two-dimensional array:</p>\n<pre><code>matrix = [\n [0,1],\n [2,3]\n]\n</code></pre>\n<p>Therefore the first index position accesses the row. The second index position accesses the column:</p>\n<pre><code>matrix[row][column]\n</code></pre>\n<p>We’ll define a utility function to print a matrix.</p>\n<pre><code>def print_matrix(matrix):\n for row in matrix:\n print row\n</code></pre>\n<p>One method of rotating a matrix is to do it a layer at a time. But what is a layer? Think of an onion. Just like the layers of an onion, as each layer is removed, we move towards the center. Other analogies is a <a href=\"https://en.wikipedia.org/wiki/Matryoshka_doll\" rel=\"noreferrer\">Matryoshka doll</a> or a game of pass-the-parcel.</p>\n<p>The width and height of a matrix dictate the number of layers in that matrix. Let’s use different symbols for each layer:</p>\n<p>A 2×2 matrix has 1 layer</p>\n<pre><code>. .\n. .\n</code></pre>\n<p>A 3×3 matrix has 2 layers</p>\n<pre><code>. . .\n. x .\n. . .\n</code></pre>\n<p>A 4×4 matrix has 2 layers</p>\n<pre><code>. . . .\n. x x .\n. x x .\n. . . .\n</code></pre>\n<p>A 5×5 matrix has 3 layers</p>\n<pre><code>. . . . .\n. x x x .\n. x O x .\n. x x x .\n. . . . .\n</code></pre>\n<p>A 6×6 matrix has 3 layers</p>\n<pre><code>. . . . . .\n. x x x x .\n. x O O x .\n. x O O x .\n. x x x x .\n. . . . . .\n</code></pre>\n<p>A 7×7 matrix has 4 layers</p>\n<pre><code>. . . . . . .\n. x x x x x .\n. x O O O x .\n. x O - O x .\n. x O O O x .\n. x x x x x .\n. . . . . . .\n</code></pre>\n<p>You may notice that incrementing the width and height of a matrix by one, does not always increase the number of layers. Taking the above matrices and tabulating the layers and dimensions, we see the number of layers increases once for every two increments of width and height:</p>\n<pre><code>+-----+--------+\n| N×N | Layers |\n+-----+--------+\n| 1×1 | 1 |\n| 2×2 | 1 |\n| 3×3 | 2 |\n| 4×4 | 2 |\n| 5×5 | 3 |\n| 6×6 | 3 |\n| 7×7 | 4 |\n+-----+--------+\n</code></pre>\n<p>However, not all layers need rotating. A 1×1 matrix is the same before and after rotation. The central 1×1 layer is always the same before and after rotation no matter how large the overall matrix:</p>\n<pre><code>+-----+--------+------------------+\n| N×N | Layers | Rotatable Layers |\n+-----+--------+------------------+\n| 1×1 | 1 | 0 |\n| 2×2 | 1 | 1 |\n| 3×3 | 2 | 1 |\n| 4×4 | 2 | 2 |\n| 5×5 | 3 | 2 |\n| 6×6 | 3 | 3 |\n| 7×7 | 4 | 3 |\n+-----+--------+------------------+\n</code></pre>\n<p>Given N×N matrix, how can we programmatically determine the number of layers we need to rotate? If we divide the width or height by two and ignore the remainder we get the following results.</p>\n<pre><code>+-----+--------+------------------+---------+\n| N×N | Layers | Rotatable Layers | N/2 |\n+-----+--------+------------------+---------+\n| 1×1 | 1 | 0 | 1/2 = 0 |\n| 2×2 | 1 | 1 | 2/2 = 1 |\n| 3×3 | 2 | 1 | 3/2 = 1 |\n| 4×4 | 2 | 2 | 4/2 = 2 |\n| 5×5 | 3 | 2 | 5/2 = 2 |\n| 6×6 | 3 | 3 | 6/2 = 3 |\n| 7×7 | 4 | 3 | 7/2 = 3 |\n+-----+--------+------------------+---------+\n</code></pre>\n<p>Notice how <code>N/2</code> matches the number of layers that need to be rotated? Sometimes the number of rotatable layers is one less the total number of layers in the matrix. This occurs when the innermost layer is formed of only one element (i.e. a 1×1 matrix) and therefore need not be rotated. It simply gets ignored.</p>\n<p>We will undoubtedly need this information in our function to rotate a matrix, so let’s add it now:</p>\n<pre><code>def rotate(matrix):\n size = len(matrix)\n # Rotatable layers only.\n layer_count = size / 2\n</code></pre>\n<p>Now we know what layers are and how to determine the number of layers that actually need rotating, how do we isolate a single layer so we can rotate it? Firstly, we inspect a matrix from the outermost layer, inwards, to the innermost layer. A 5×5 matrix has three layers in total and two layers that need rotating:</p>\n<pre><code>. . . . .\n. x x x .\n. x O x .\n. x x x .\n. . . . .\n</code></pre>\n<p>Let’s look at columns first. The position of the columns defining the outermost layer, assuming we count from 0, are 0 and 4:</p>\n<pre><code>+--------+-----------+\n| Column | 0 1 2 3 4 |\n+--------+-----------+\n| | . . . . . |\n| | . x x x . |\n| | . x O x . |\n| | . x x x . |\n| | . . . . . |\n+--------+-----------+\n</code></pre>\n<p>0 and 4 are also the positions of the rows for the outermost layer.</p>\n<pre><code>+-----+-----------+\n| Row | |\n+-----+-----------+\n| 0 | . . . . . |\n| 1 | . x x x . |\n| 2 | . x O x . |\n| 3 | . x x x . |\n| 4 | . . . . . |\n+-----+-----------+\n</code></pre>\n<p>This will always be the case since the width and height are the same. Therefore we can define the column and row positions of a layer with just two values (rather than four).</p>\n<p>Moving inwards to the second layer, the position of the columns are 1 and 3. And, yes, you guessed it, it’s the same for rows. It’s important to understand we had to both increment and decrement the row and column positions when moving inwards to the next layer.</p>\n<pre><code>+-----------+---------+---------+---------+\n| Layer | Rows | Columns | Rotate? |\n+-----------+---------+---------+---------+\n| Outermost | 0 and 4 | 0 and 4 | Yes |\n| Inner | 1 and 3 | 1 and 3 | Yes |\n| Innermost | 2 | 2 | No |\n+-----------+---------+---------+---------+\n</code></pre>\n<p>So, to inspect each layer, we want a loop with both increasing and decreasing counters that represent moving inwards, starting from the outermost layer. We’ll call this our ‘layer loop’.</p>\n<pre><code>def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n\n for layer in range(0, layer_count):\n first = layer\n last = size - first - 1\n print 'Layer %d: first: %d, last: %d' % (layer, first, last)\n\n# 5x5 matrix\nmatrix = [\n [ 0, 1, 2, 3, 4],\n [ 5, 6, 6, 8, 9],\n [10,11,12,13,14],\n [15,16,17,18,19],\n [20,21,22,23,24]\n]\n\nrotate(matrix)\n</code></pre>\n<p>The code above loops through the (row and column) positions of any layers that need rotating.</p>\n<pre><code>Layer 0: first: 0, last: 4\nLayer 1: first: 1, last: 3\n</code></pre>\n<p>We now have a loop providing the positions of the rows and columns of each layer. The variables <code>first</code> and <code>last</code> identify the index position of the first and last rows and columns. Referring back to our row and column tables:</p>\n<pre><code>+--------+-----------+\n| Column | 0 1 2 3 4 |\n+--------+-----------+\n| | . . . . . |\n| | . x x x . |\n| | . x O x . |\n| | . x x x . |\n| | . . . . . |\n+--------+-----------+\n\n+-----+-----------+\n| Row | |\n+-----+-----------+\n| 0 | . . . . . |\n| 1 | . x x x . |\n| 2 | . x O x . |\n| 3 | . x x x . |\n| 4 | . . . . . |\n+-----+-----------+\n</code></pre>\n<p>So we can navigate through the layers of a matrix. Now we need a way of navigating within a layer so we can move elements around that layer. Note, elements never ‘jump’ from one layer to another, but they do move within their respective layers.</p>\n<p>Rotating each element in a layer rotates the entire layer. Rotating all layers in a matrix rotates the entire matrix. This sentence is very important, so please try your best to understand it before moving on.</p>\n<p>Now, we need a way of actually moving elements, i.e. rotate each element, and subsequently the layer, and ultimately the matrix. For simplicity, we’ll revert to a 3x3 matrix — that has one rotatable layer.</p>\n<pre><code>0 1 2\n3 4 5\n6 7 8\n</code></pre>\n<p>Our layer loop provides the indexes of the first and last columns, as well as first and last rows:</p>\n<pre><code>+-----+-------+\n| Col | 0 1 2 |\n+-----+-------+\n| | 0 1 2 |\n| | 3 4 5 |\n| | 6 7 8 |\n+-----+-------+\n\n+-----+-------+\n| Row | |\n+-----+-------+\n| 0 | 0 1 2 |\n| 1 | 3 4 5 |\n| 2 | 6 7 8 |\n+-----+-------+\n</code></pre>\n<p>Because our matrices are always square, we need just two variables, <code>first</code> and <code>last</code>, since index positions are the same for rows and columns.</p>\n<pre><code>def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n\n # Our layer loop i=0, i=1, i=2\n for layer in range(0, layer_count):\n\n first = layer\n last = size - first - 1\n \n # We want to move within a layer here.\n</code></pre>\n<p>The variables first and last can easily be used to reference the four corners of a matrix. This is because the corners themselves can be defined using various permutations of <code>first</code> and <code>last</code> (with no subtraction, addition or offset of those variables):</p>\n<pre><code>+---------------+-------------------+-------------+\n| Corner | Position | 3x3 Values |\n+---------------+-------------------+-------------+\n| top left | (first, first) | (0,0) |\n| top right | (first, last) | (0,2) |\n| bottom right | (last, last) | (2,2) |\n| bottom left | (last, first) | (2,0) |\n+---------------+-------------------+-------------+\n</code></pre>\n<p>For this reason, we start our rotation at the outer four corners — we’ll rotate those first. Let’s highlight them with <code>*</code>.</p>\n<pre><code>* 1 *\n3 4 5\n* 7 *\n</code></pre>\n<p>We want to swap each <code>*</code> with the <code>*</code> to the right of it. So let’s go ahead a print out our corners defined using only various permutations of <code>first</code> and <code>last</code>:</p>\n<pre><code>def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n for layer in range(0, layer_count):\n\n first = layer\n last = size - first - 1\n\n top_left = (first, first)\n top_right = (first, last)\n bottom_right = (last, last)\n bottom_left = (last, first)\n\n print 'top_left: %s' % (top_left)\n print 'top_right: %s' % (top_right)\n print 'bottom_right: %s' % (bottom_right)\n print 'bottom_left: %s' % (bottom_left)\n\nmatrix = [\n[0, 1, 2],\n[3, 4, 5],\n[6, 7, 8]\n]\n\nrotate(matrix)\n</code></pre>\n<p>Output should be:</p>\n<pre><code>top_left: (0, 0)\ntop_right: (0, 2)\nbottom_right: (2, 2)\nbottom_left: (2, 0)\n</code></pre>\n<p>Now we could quite easily swap each of the corners from within our layer loop:</p>\n<pre><code>def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n for layer in range(0, layer_count):\n \n first = layer\n last = size - first - 1\n\n top_left = matrix[first][first]\n top_right = matrix[first][last]\n bottom_right = matrix[last][last]\n bottom_left = matrix[last][first]\n\n # bottom_left -> top_left\n matrix[first][first] = bottom_left\n # top_left -> top_right\n matrix[first][last] = top_left\n # top_right -> bottom_right\n matrix[last][last] = top_right\n # bottom_right -> bottom_left\n matrix[last][first] = bottom_right\n\n\nprint_matrix(matrix)\nprint '---------'\nrotate(matrix)\nprint_matrix(matrix)\n</code></pre>\n<p>Matrix before rotating corners:</p>\n<pre><code>[0, 1, 2]\n[3, 4, 5]\n[6, 7, 8]\n</code></pre>\n<p>Matrix after rotating corners:</p>\n<pre><code>[6, 1, 0]\n[3, 4, 5]\n[8, 7, 2]\n</code></pre>\n<p>Great! We have successfully rotated each corner of the matrix. But, we haven’t rotated the elements in the middle of each layer. Clearly we need a way of iterating within a layer.</p>\n<p>The problem is, the only loop in our function so far (our layer loop), moves to the next layer on each iteration. Since our matrix has only one rotatable layer, the layer loop exits after rotating only the corners. Let’s look at what happens with a larger, 5×5 matrix (where two layers need rotating). The function code has been omitted, but it remains the same as above:</p>\n<pre><code>matrix = [\n[0, 1, 2, 3, 4],\n[5, 6, 7, 8, 9],\n[10, 11, 12, 13, 14],\n[15, 16, 17, 18, 19],\n[20, 21, 22, 23, 24]\n]\nprint_matrix(matrix)\nprint '--------------------'\nrotate(matrix)\nprint_matrix(matrix)\n</code></pre>\n<p>The output is:</p>\n<pre><code>[20, 1, 2, 3, 0]\n[ 5, 16, 7, 6, 9]\n[10, 11, 12, 13, 14]\n[15, 18, 17, 8, 19]\n[24, 21, 22, 23, 4]\n</code></pre>\n<p>It shouldn’t be a surprise that the corners of the outermost layer have been rotated, but, you may also notice the corners of the next layer (inwards) have also been rotated. This makes sense. We’ve written code to navigate through layers and also to rotate the corners of each layer. This feels like progress, but unfortunately we must take a step back. It’s just no good moving onto the next layer until the previous (outer) layer has been fully rotated. That is, until each element in the layer has been rotated. Rotating only the corners won’t do!</p>\n<p>Take a deep breath. We need another loop. A nested loop no less. The new, nested loop, will use the <code>first</code> and <code>last</code> variables, plus an offset to navigate within a layer. We’ll call this new loop our ‘element loop’. The element loop will visit each element along the top row, each element down the right side, each element along the bottom row and each element up the left side.</p>\n<ul>\n<li>Moving forwards along the top row requires the column\nindex to be incremented.</li>\n<li>Moving down the right side requires the row index to be\nincremented.</li>\n<li>Moving backwards along the bottom requires the column\nindex to be decremented.</li>\n<li>Moving up the left side requires the row index to be\ndecremented.</li>\n</ul>\n<p>This sounds complex, but it’s made easy because the number of times we increment and decrement to achieve the above remains the same along all four sides of the matrix. For example:</p>\n<ul>\n<li>Move 1 element across the top row.</li>\n<li>Move 1 element down the right side.</li>\n<li>Move 1 element backwards along the bottom row.</li>\n<li>Move 1 element up the left side.</li>\n</ul>\n<p>This means we can use a single variable in combination with the <code>first</code> and <code>last</code> variables to move within a layer. It may help to note that moving across the top row and down the right side both require incrementing. While moving backwards along the bottom and up the left side both require decrementing.</p>\n<pre><code>def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n \n # Move through layers (i.e. layer loop).\n for layer in range(0, layer_count):\n \n first = layer\n last = size - first - 1\n\n # Move within a single layer (i.e. element loop).\n for element in range(first, last):\n \n offset = element - first\n\n # 'element' increments column (across right)\n top = (first, element)\n # 'element' increments row (move down)\n right_side = (element, last)\n # 'last-offset' decrements column (across left)\n bottom = (last, last-offset)\n # 'last-offset' decrements row (move up)\n left_side = (last-offset, first)\n\n print 'top: %s' % (top)\n print 'right_side: %s' % (right_side)\n print 'bottom: %s' % (bottom)\n print 'left_side: %s' % (left_side)\n</code></pre>\n<p>Now we simply need to assign the top to the right side, right side to the bottom, bottom to the left side, and left side to the top. Putting this all together we get:</p>\n<pre><code>def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n\n for layer in range(0, layer_count):\n first = layer\n last = size - first - 1\n\n for element in range(first, last):\n offset = element - first\n\n top = matrix[first][element]\n right_side = matrix[element][last]\n bottom = matrix[last][last-offset]\n left_side = matrix[last-offset][first]\n\n matrix[first][element] = left_side\n matrix[element][last] = top\n matrix[last][last-offset] = right_side\n matrix[last-offset][first] = bottom\n</code></pre>\n<p>Given the matrix:</p>\n<pre><code>0, 1, 2 \n3, 4, 5 \n6, 7, 8 \n</code></pre>\n<p>Our <code>rotate</code> function results in:</p>\n<pre><code>6, 3, 0 \n7, 4, 1 \n8, 5, 2 \n</code></pre>\n"
},
{
"answer_id": 35527917,
"author": "Maaz Ashraf",
"author_id": 5956013,
"author_profile": "https://Stackoverflow.com/users/5956013",
"pm_score": -1,
"selected": false,
"text": "<p>This is simple C code to rotate an array 90degrees. Hope this helps. </p>\n\n<pre><code>#include <stdio.h>\n\nvoid main(){\nint arr[3][4] = {85, 2, 85, 4,\n 85, 6, 7, 85,\n 9, 85, 11, 12};\n\n\nint arr1[4][3];\n\nint i = 0, j = 0;\n\nfor(i=0;i<4;i++){\nint k = 2;//k = (number of columns in the new array arr1 - 1)\nfor(j=0;j<3;j++){\narr1[i][j]=arr[k][i];\nk--;\n}\n}\n\nint l, m;\nfor(l=0;l<4;l++){\nfor(m=0;m<3;m++){\nprintf(\"%d \", arr1[l][m]);\n}\nprintf(\"\\n\");\n}\n}//end main\n</code></pre>\n"
},
{
"answer_id": 37870786,
"author": "Dudi",
"author_id": 4572425,
"author_profile": "https://Stackoverflow.com/users/4572425",
"pm_score": -1,
"selected": false,
"text": "<p>My <strong>C#</strong> example code for the great Algorithm sent by @dimple:</p>\n\n<pre><code>/* Author: Dudi,\n * http://www.tutorialspoint.com/compile_csharp_online.php?PID=0Bw_CjBb95KQMYm5qU3VjVGNuZFU */\n\nusing System.IO;\nusing System;\n\nclass Program\n{\n static void Main()\n {\n Console.WriteLine(\"Rotating this matrix by 90+ degree:\");\n\n int[,] values=new int[3,3]{{1,2,3}, {4,5,6}, {7,8,9}};\n //int[,] values=new int[4,4]{{101,102,103, 104}, {105,106, 107,108}, {109, 110, 111, 112}, {113, 114, 115, 116}};\n\n print2dArray(ref values);\n transpose2dArray(ref values);\n //print2dArray(ref values);\n reverse2dArray(ref values);\n Console.WriteLine(\"Output:\");\n print2dArray(ref values);\n }\n\n static void print2dArray(ref int[,] matrix){\n int nLen = matrix.GetLength(0);\n int mLen = matrix.GetLength(1); \n for(int n=0; n<nLen; n++){\n for(int m=0; m<mLen; m++){\n Console.Write(matrix[n,m] +\"\\t\");\n }\n Console.WriteLine(); \n }\n Console.WriteLine();\n }\n\n static void transpose2dArray(ref int[,] matrix){\n int nLen = matrix.GetLength(0);\n int mLen = matrix.GetLength(1); \n for(int n=0; n<nLen; n++){\n for(int m=0; m<mLen; m++){\n if(n>m){\n int tmp = matrix[n,m];\n matrix[n,m] = matrix[m,n];\n matrix[m,n] = tmp;\n }\n }\n }\n }\n\n static void reverse2dArray(ref int[,] matrix){\n int nLen = matrix.GetLength(0);\n int mLen = matrix.GetLength(1);\n for(int n=0; n<nLen; n++){\n for(int m=0; m<mLen/2; m++){ \n int tmp = matrix[n,m];\n matrix[n,m] = matrix[n, mLen-1-m];\n matrix[n,mLen-1-m] = tmp;\n }\n }\n }\n}\n\n/*\nRotating this matrix by 90+ degree: \n1 2 3 \n4 5 6 \n7 8 9 \n\nOutput: \n7 4 1 \n8 5 2 \n9 6 3 \n*/\n</code></pre>\n"
},
{
"answer_id": 38027015,
"author": "Alexander Bekert",
"author_id": 1322703,
"author_profile": "https://Stackoverflow.com/users/1322703",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a C# static generic method that does the work for you. Variables are well-named, so you can easily catch the idea of the algorythm.</p>\n\n<pre><code>private static T[,] Rotate180 <T> (T[,] matrix)\n{\n var height = matrix.GetLength (0);\n var width = matrix.GetLength (1);\n var answer = new T[height, width];\n\n for (int y = 0; y < height / 2; y++)\n {\n int topY = y;\n int bottomY = height - 1 - y;\n for (int topX = 0; topX < width; topX++)\n {\n var bottomX = width - topX - 1;\n answer[topY, topX] = matrix[bottomY, bottomX];\n answer[bottomY, bottomX] = matrix[topY, topX];\n }\n }\n\n if (height % 2 == 0)\n return answer;\n\n var centerY = height / 2;\n for (int leftX = 0; leftX < Mathf.CeilToInt(width / 2f); leftX++)\n {\n var rightX = width - 1 - leftX;\n answer[centerY, leftX] = matrix[centerY, rightX];\n answer[centerY, rightX] = matrix[centerY, leftX];\n }\n\n return answer;\n}\n</code></pre>\n"
},
{
"answer_id": 38142398,
"author": "Lee.O.",
"author_id": 5976676,
"author_profile": "https://Stackoverflow.com/users/5976676",
"pm_score": -1,
"selected": false,
"text": "<pre><code> public static void rotateMatrix(int[,] matrix)\n {\n //C#, to rotate an N*N matrix in place\n int n = matrix.GetLength(0);\n int layers = n / 2;\n int temp, temp2;\n\n for (int i = 0; i < layers; i++) // for a 5 * 5 matrix, layers will be 2, since at layer three there would be only one element, (2,2), and we do not need to rotate it with itself \n {\n int offset = 0;\n while (offset < n - 2 * i - 1)\n {\n // top right <- top left \n temp = matrix[i + offset, n - i - 1]; //top right value when offset is zero\n matrix[i + offset, n - i - 1] = matrix[i, i + offset]; \n\n //bottom right <- top right \n temp2 = matrix[n - i - 1, n - i - 1 - offset]; //bottom right value when offset is zero\n matrix[n - i - 1, n - i - 1 - offset] = temp; \n\n //bottom left <- bottom right \n temp = matrix[n - i - 1 - offset, i];\n matrix[n - i - 1 - offset, i] = temp2; \n\n //top left <- bottom left \n matrix[i, i + offset] = temp; \n\n offset++;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 38518519,
"author": "ThinkTankShark",
"author_id": 5244684,
"author_profile": "https://Stackoverflow.com/users/5244684",
"pm_score": 1,
"selected": false,
"text": "<p>Great answers but for those who are looking for a DRY JavaScript code for this - both +90 Degrees and -90 Degrees:</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> // Input: 1 2 3\r\n // 4 5 6\r\n // 7 8 9\r\n\r\n // Transpose: \r\n // 1 4 7\r\n // 2 5 8\r\n // 3 6 9\r\n\r\n // Output: \r\n // +90 Degree:\r\n // 7 4 1\r\n // 8 5 2\r\n // 9 6 3\r\n\r\n // -90 Degree:\r\n // 3 6 9\r\n // 2 5 8\r\n // 1 4 7\r\n\r\n // Rotate +90\r\n function rotate90(matrix) {\r\n\r\n matrix = transpose(matrix);\r\n matrix.map(function(array) {\r\n array.reverse();\r\n });\r\n\r\n return matrix;\r\n }\r\n\r\n // Rotate -90\r\n function counterRotate90(matrix) {\r\n var result = createEmptyMatrix(matrix.length);\r\n matrix = transpose(matrix);\r\n var counter = 0;\r\n\r\n for (var i = matrix.length - 1; i >= 0; i--) {\r\n result[counter] = matrix[i];\r\n counter++;\r\n }\r\n\r\n return result;\r\n }\r\n\r\n // Create empty matrix\r\n function createEmptyMatrix(len) {\r\n var result = new Array();\r\n for (var i = 0; i < len; i++) {\r\n result.push([]);\r\n }\r\n return result;\r\n }\r\n\r\n // Transpose the matrix\r\n function transpose(matrix) {\r\n // make empty array\r\n var len = matrix.length;\r\n var result = createEmptyMatrix(len);\r\n\r\n for (var i = 0; i < matrix.length; i++) {\r\n for (var j = 0; j < matrix[i].length; j++) {\r\n var temp = matrix[i][j];\r\n result[j][i] = temp;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n\r\n\r\n // Test Cases\r\n var array1 = [\r\n [1, 2],\r\n [3, 4]\r\n ];\r\n var array2 = [\r\n [1, 2, 3],\r\n [4, 5, 6],\r\n [7, 8, 9]\r\n ];\r\n var array3 = [\r\n [1, 2, 3, 4],\r\n [5, 6, 7, 8],\r\n [9, 10, 11, 12],\r\n [13, 14, 15, 16]\r\n ];\r\n\r\n // +90 degress Rotation Tests\r\n\r\n var test1 = rotate90(array1);\r\n var test2 = rotate90(array2);\r\n var test3 = rotate90(array3);\r\n console.log(test1);\r\n console.log(test2);\r\n console.log(test3);\r\n\r\n // -90 degress Rotation Tests\r\n var test1 = counterRotate90(array1);\r\n var test2 = counterRotate90(array2);\r\n var test3 = counterRotate90(array3);\r\n console.log(test1);\r\n console.log(test2);\r\n console.log(test3);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 39923587,
"author": "Nicky Feller",
"author_id": 4313927,
"author_profile": "https://Stackoverflow.com/users/4313927",
"pm_score": -1,
"selected": false,
"text": "<p>Can be done recursively quite cleanly, here is my implementation in golang!</p>\n\n<p>rotate nxn matrix in go golang recursively in place with no additional memory</p>\n\n<pre><code>func rot90(a [][]int) {\n n := len(a)\n if n == 1 {\n return\n }\n for i := 0; i < n; i++ {\n a[0][i], a[n-1-i][n-1] = a[n-1-i][n-1], a[0][i]\n }\n rot90(a[1:])\n}\n</code></pre>\n"
},
{
"answer_id": 40628762,
"author": "Shrikant Dande",
"author_id": 2449053,
"author_profile": "https://Stackoverflow.com/users/2449053",
"pm_score": -1,
"selected": false,
"text": "<p>In Java </p>\n\n<pre><code>public class Matrix {\n/* Author Shrikant Dande */\nprivate static void showMatrix(int[][] arr,int rows,int col){\n\n for(int i =0 ;i<rows;i++){\n for(int j =0 ;j<col;j++){\n System.out.print(arr[i][j]+\" \");\n }\n System.out.println();\n }\n\n}\n\nprivate static void rotateMatrix(int[][] arr,int rows,int col){\n\n int[][] tempArr = new int[4][4];\n for(int i =0 ;i<rows;i++){\n for(int j =0 ;j<col;j++){\n tempArr[i][j] = arr[rows-1-j][i];\n System.out.print(tempArr[i][j]+\" \");\n }\n System.out.println();\n }\n\n}\npublic static void main(String[] args) {\n int[][] arr = { {1, 2, 3, 4},\n {5, 6, 7, 8},\n {9, 1, 2, 5},\n {7, 4, 8, 9}};\n int rows = 4,col = 4;\n\n showMatrix(arr, rows, col);\n System.out.println(\"------------------------------------------------\");\n rotateMatrix(arr, rows, col);\n\n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 44095272,
"author": "Qian Chen",
"author_id": 1663023,
"author_profile": "https://Stackoverflow.com/users/1663023",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a Javascript solution:</p>\n\n<pre><code>const transpose = m => m[0].map((x,i) => m.map(x => x[i]));\n\na: // original matrix\n123\n456\n789\n\ntranspose(a).reverse(); // rotate 90 degrees counter clockwise \n369\n258\n147\n\ntranspose(a.slice().reverse()); // rotate 90 degrees clockwise \n741\n852\n963\n\ntranspose(transpose(a.slice().reverse()).slice().reverse())\n// rotate 180 degrees \n987\n654\n321\n</code></pre>\n"
},
{
"answer_id": 44510769,
"author": "user_3380739",
"author_id": 3380739,
"author_profile": "https://Stackoverflow.com/users/3380739",
"pm_score": -1,
"selected": false,
"text": "<p>Try My library <a href=\"https://github.com/landawn/AbacusUtil\" rel=\"nofollow noreferrer\">AbacusUtil</a>:</p>\n\n<pre><code>@Test\npublic void test_42519() throws Exception {\n final IntMatrix matrix = IntMatrix.range(0, 16).reshape(4);\n\n N.println(\"======= original =======================\");\n matrix.println();\n // print out:\n // [0, 1, 2, 3]\n // [4, 5, 6, 7]\n // [8, 9, 10, 11]\n // [12, 13, 14, 15]\n\n N.println(\"======= rotate 90 ======================\");\n matrix.rotate90().println();\n // print out:\n // [12, 8, 4, 0]\n // [13, 9, 5, 1]\n // [14, 10, 6, 2]\n // [15, 11, 7, 3]\n\n N.println(\"======= rotate 180 =====================\");\n matrix.rotate180().println();\n // print out:\n // [15, 14, 13, 12]\n // [11, 10, 9, 8]\n // [7, 6, 5, 4]\n // [3, 2, 1, 0]\n\n N.println(\"======= rotate 270 ======================\");\n matrix.rotate270().println();\n // print out:\n // [3, 7, 11, 15]\n // [2, 6, 10, 14]\n // [1, 5, 9, 13]\n // [0, 4, 8, 12]\n\n N.println(\"======= transpose =======================\");\n matrix.transpose().println();\n // print out:\n // [0, 4, 8, 12]\n // [1, 5, 9, 13]\n // [2, 6, 10, 14]\n // [3, 7, 11, 15]\n\n final IntMatrix bigMatrix = IntMatrix.range(0, 10000_0000).reshape(10000);\n\n // It take about 2 seconds to rotate 10000 X 10000 matrix.\n Profiler.run(1, 2, 3, \"sequential\", () -> bigMatrix.rotate90()).printResult();\n\n // Want faster? Go parallel. 1 second to rotate 10000 X 10000 matrix.\n final int[][] a = bigMatrix.array();\n final int[][] c = new int[a[0].length][a.length];\n final int n = a.length;\n final int threadNum = 4;\n\n Profiler.run(1, 2, 3, \"parallel\", () -> {\n IntStream.range(0, n).parallel(threadNum).forEach(i -> {\n for (int j = 0; j < n; j++) {\n c[i][j] = a[n - j - 1][i];\n }\n });\n }).printResult();\n}\n</code></pre>\n"
},
{
"answer_id": 44940034,
"author": "Vladimir Ramik",
"author_id": 4644312,
"author_profile": "https://Stackoverflow.com/users/4644312",
"pm_score": 1,
"selected": false,
"text": "<p><strong>PHP Solution</strong> for clockwise & counterclockwise</p>\n\n<pre><code>$aMatrix = array(\n array( 1, 2, 3 ),\n array( 4, 5, 6 ),\n array( 7, 8, 9 )\n );\n\nfunction CounterClockwise( $aMatrix )\n{\n $iCount = count( $aMatrix );\n $aReturn = array();\n for( $y = 0; $y < $iCount; ++$y )\n {\n for( $x = 0; $x < $iCount; ++$x )\n {\n $aReturn[ $iCount - $x - 1 ][ $y ] = $aMatrix[ $y ][ $x ];\n }\n }\n return $aReturn;\n}\n\nfunction Clockwise( $aMatrix )\n{\n $iCount = count( $aMatrix );\n $aReturn = array();\n for( $y = 0; $y < $iCount; ++$y )\n {\n for( $x = 0; $x < $iCount; ++$x )\n {\n $aReturn[ $x ][ $iCount - $y - 1 ] = $aMatrix[ $y ][ $x ];\n }\n }\n return $aReturn;\n}\n\nfunction printMatrix( $aMatrix )\n{\n $iCount = count( $aMatrix );\n for( $x = 0; $x < $iCount; ++$x )\n {\n for( $y = 0; $y < $iCount; ++$y )\n {\n echo $aMatrix[ $x ][ $y ];\n echo \" \";\n }\n echo \"\\n\";\n }\n}\nprintMatrix( $aMatrix );\necho \"\\n\";\n$aNewMatrix = CounterClockwise( $aMatrix );\nprintMatrix( $aNewMatrix );\necho \"\\n\";\n$aNewMatrix = Clockwise( $aMatrix );\nprintMatrix( $aNewMatrix );\n</code></pre>\n"
},
{
"answer_id": 49087988,
"author": "Tom",
"author_id": 882436,
"author_profile": "https://Stackoverflow.com/users/882436",
"pm_score": 1,
"selected": false,
"text": "<p>C code for matrix transpose & rotate (+/-90, +/-180)</p>\n\n<ul>\n<li>Supports square and non-square matrices, has in-place and copy features</li>\n<li>Supports both 2D arrays and 1D pointers with logical rows/cols</li>\n<li>Unit tests; see tests for examples of usage</li>\n<li>tested gcc -std=c90 -Wall -pedantic, MSVC17</li>\n</ul>\n\n<p>`</p>\n\n<pre><code>#include <stdlib.h>\n#include <memory.h>\n#include <assert.h>\n\n/* \n Matrix transpose & rotate (+/-90, +/-180)\n Supports both 2D arrays and 1D pointers with logical rows/cols\n Supports square and non-square matrices, has in-place and copy features\n See tests for examples of usage\n tested gcc -std=c90 -Wall -pedantic, MSVC17\n*/\n\ntypedef int matrix_data_t; /* matrix data type */\n\nvoid transpose(const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);\nvoid transpose_inplace(matrix_data_t* data, int n );\nvoid rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);\nvoid rotate_inplace(int direction, matrix_data_t* data, int n);\nvoid reverse_rows(matrix_data_t* data, int rows, int cols);\nvoid reverse_cols(matrix_data_t* data, int rows, int cols);\n\n/* test/compare fn */\nint test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols );\n\n/* TESTS/USAGE */\nvoid transpose_test() {\n\n matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };/* 3x3 square, odd length side */\n matrix_data_t sq3x3_cpy[9];\n matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };/* 2D 3x3 square */\n matrix_data_t sq3x3_2D_copy[3][3];\n\n /* expected test values */\n const matrix_data_t sq3x3_orig[9] = { 0,1,2,3,4,5,6,7,8 };\n const matrix_data_t sq3x3_transposed[9] = { 0,3,6,1,4,7,2,5,8};\n\n matrix_data_t sq4x4[16]= { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };/* 4x4 square, even length*/\n const matrix_data_t sq4x4_orig[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };\n const matrix_data_t sq4x4_transposed[16] = { 0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15 };\n\n /* 2x3 rectangle */\n const matrix_data_t r2x3_orig[6] = { 0,1,2,3,4,5 };\n const matrix_data_t r2x3_transposed[6] = { 0,3,1,4,2,5 };\n matrix_data_t r2x3_copy[6];\n\n matrix_data_t r2x3_2D[2][3] = { {0,1,2},{3,4,5} }; /* 2x3 2D rectangle */\n matrix_data_t r2x3_2D_t[3][2];\n\n /* matrix_data_t r3x2[6] = { 0,1,2,3,4,5 }; */\n matrix_data_t r3x2_copy[6];\n /* 3x2 rectangle */\n const matrix_data_t r3x2_orig[6] = { 0,1,2,3,4,5 };\n const matrix_data_t r3x2_transposed[6] = { 0,2,4,1,3,5 };\n\n matrix_data_t r6x1[6] = { 0,1,2,3,4,5 }; /* 6x1 */\n matrix_data_t r6x1_copy[6];\n\n matrix_data_t r1x1[1] = { 0 }; /*1x1*/\n matrix_data_t r1x1_copy[1];\n\n /* 3x3 tests, 2D array tests */\n transpose_inplace(sq3x3, 3); /* transpose in place */\n assert(!test_cmp(sq3x3, sq3x3_transposed, 3, 3));\n transpose_inplace(sq3x3, 3); /* transpose again */\n assert(!test_cmp(sq3x3, sq3x3_orig, 3, 3));\n\n transpose(sq3x3, sq3x3_cpy, 3, 3); /* transpose copy 3x3*/\n assert(!test_cmp(sq3x3_cpy, sq3x3_transposed, 3, 3));\n\n transpose((matrix_data_t*)sq3x3_2D, (matrix_data_t*)sq3x3_2D_copy, 3, 3); /* 2D array transpose/copy */\n assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_transposed, 3, 3));\n transpose_inplace((matrix_data_t*)sq3x3_2D_copy, 3); /* 2D array transpose in place */\n assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_orig, 3, 3));\n\n /* 4x4 tests */\n transpose_inplace(sq4x4, 4); /* transpose in place */\n assert(!test_cmp(sq4x4, sq4x4_transposed, 4,4));\n transpose_inplace(sq4x4, 4); /* transpose again */\n assert(!test_cmp(sq4x4, sq4x4_orig, 3, 3));\n\n /* 2x3,3x2 tests */\n transpose(r2x3_orig, r2x3_copy, 2, 3);\n assert(!test_cmp(r2x3_copy, r2x3_transposed, 3, 2));\n\n transpose(r3x2_orig, r3x2_copy, 3, 2);\n assert(!test_cmp(r3x2_copy, r3x2_transposed, 2,3));\n\n /* 2D array */\n transpose((matrix_data_t*)r2x3_2D, (matrix_data_t*)r2x3_2D_t, 2, 3);\n assert(!test_cmp((matrix_data_t*)r2x3_2D_t, r2x3_transposed, 3,2));\n\n /* Nx1 test, 1x1 test */\n transpose(r6x1, r6x1_copy, 6, 1);\n assert(!test_cmp(r6x1_copy, r6x1, 1, 6));\n\n transpose(r1x1, r1x1_copy, 1, 1);\n assert(!test_cmp(r1x1_copy, r1x1, 1, 1));\n\n}\n\nvoid rotate_test() {\n\n /* 3x3 square */\n const matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };\n const matrix_data_t sq3x3_r90[9] = { 6,3,0,7,4,1,8,5,2 };\n const matrix_data_t sq3x3_180[9] = { 8,7,6,5,4,3,2,1,0 };\n const matrix_data_t sq3x3_l90[9] = { 2,5,8,1,4,7,0,3,6 };\n matrix_data_t sq3x3_copy[9];\n\n /* 3x3 square, 2D */\n matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };\n\n /* 4x4, 2D */\n matrix_data_t sq4x4[4][4] = { { 0,1,2,3 },{ 4,5,6,7 },{ 8,9,10,11 },{ 12,13,14,15 } };\n matrix_data_t sq4x4_copy[4][4];\n const matrix_data_t sq4x4_r90[16] = { 12,8,4,0,13,9,5,1,14,10,6,2,15,11,7,3 };\n const matrix_data_t sq4x4_l90[16] = { 3,7,11,15,2,6,10,14,1,5,9,13,0,4,8,12 };\n const matrix_data_t sq4x4_180[16] = { 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 };\n\n matrix_data_t r6[6] = { 0,1,2,3,4,5 }; /* rectangle with area of 6 (1x6,2x3,3x2, or 6x1) */\n matrix_data_t r6_copy[6];\n const matrix_data_t r1x6_r90[6] = { 0,1,2,3,4,5 };\n const matrix_data_t r1x6_l90[6] = { 5,4,3,2,1,0 };\n const matrix_data_t r1x6_180[6] = { 5,4,3,2,1,0 };\n\n const matrix_data_t r2x3_r90[6] = { 3,0,4,1,5,2 };\n const matrix_data_t r2x3_l90[6] = { 2,5,1,4,0,3 };\n const matrix_data_t r2x3_180[6] = { 5,4,3,2,1,0 };\n\n const matrix_data_t r3x2_r90[6] = { 4,2,0,5,3,1 };\n const matrix_data_t r3x2_l90[6] = { 1,3,5,0,2,4 };\n const matrix_data_t r3x2_180[6] = { 5,4,3,2,1,0 };\n\n const matrix_data_t r6x1_r90[6] = { 5,4,3,2,1,0 };\n const matrix_data_t r6x1_l90[6] = { 0,1,2,3,4,5 };\n const matrix_data_t r6x1_180[6] = { 5,4,3,2,1,0 };\n\n /* sq3x3 tests */\n rotate(90, sq3x3, sq3x3_copy, 3, 3); /* +90 */\n assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));\n rotate(-90, sq3x3, sq3x3_copy, 3, 3); /* -90 */\n assert(!test_cmp(sq3x3_copy, sq3x3_l90, 3, 3));\n rotate(180, sq3x3, sq3x3_copy, 3, 3); /* 180 */\n assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));\n /* sq3x3 in-place rotations */\n memcpy( sq3x3_copy, sq3x3, 3 * 3 * sizeof(matrix_data_t));\n rotate_inplace(90, sq3x3_copy, 3);\n assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));\n rotate_inplace(-90, sq3x3_copy, 3);\n assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3)); /* back to 0 orientation */\n rotate_inplace(180, sq3x3_copy, 3);\n assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));\n rotate_inplace(-180, sq3x3_copy, 3);\n assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3));\n rotate_inplace(180, (matrix_data_t*)sq3x3_2D, 3);/* 2D test */\n assert(!test_cmp((matrix_data_t*)sq3x3_2D, sq3x3_180, 3, 3));\n\n /* sq4x4 */\n rotate(90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_r90, 4, 4));\n rotate(-90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_l90, 4, 4));\n rotate(180, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_180, 4, 4));\n\n /* r6 as 1x6 */\n rotate(90, r6, r6_copy, 1, 6);\n assert(!test_cmp(r6_copy, r1x6_r90, 1, 6));\n rotate(-90, r6, r6_copy, 1, 6);\n assert(!test_cmp(r6_copy, r1x6_l90, 1, 6));\n rotate(180, r6, r6_copy, 1, 6);\n assert(!test_cmp(r6_copy, r1x6_180, 1, 6));\n\n /* r6 as 2x3 */\n rotate(90, r6, r6_copy, 2, 3);\n assert(!test_cmp(r6_copy, r2x3_r90, 2, 3));\n rotate(-90, r6, r6_copy, 2, 3);\n assert(!test_cmp(r6_copy, r2x3_l90, 2, 3));\n rotate(180, r6, r6_copy, 2, 3);\n assert(!test_cmp(r6_copy, r2x3_180, 2, 3));\n\n /* r6 as 3x2 */\n rotate(90, r6, r6_copy, 3, 2);\n assert(!test_cmp(r6_copy, r3x2_r90, 3, 2));\n rotate(-90, r6, r6_copy, 3, 2);\n assert(!test_cmp(r6_copy, r3x2_l90, 3, 2));\n rotate(180, r6, r6_copy, 3, 2);\n assert(!test_cmp(r6_copy, r3x2_180, 3, 2));\n\n /* r6 as 6x1 */\n rotate(90, r6, r6_copy, 6, 1);\n assert(!test_cmp(r6_copy, r6x1_r90, 6, 1));\n rotate(-90, r6, r6_copy, 6, 1);\n assert(!test_cmp(r6_copy, r6x1_l90, 6, 1));\n rotate(180, r6, r6_copy, 6, 1);\n assert(!test_cmp(r6_copy, r6x1_180, 6, 1));\n}\n\n/* test comparison fn, return 0 on match else non zero */\nint test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols) {\n\n int r, c;\n\n for (r = 0; r < rows; ++r) {\n for (c = 0; c < cols; ++c) {\n if ((lhs + r * cols)[c] != (rhs + r * cols)[c])\n return -1;\n }\n }\n return 0;\n}\n\n/*\nReverse values in place of each row in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols\n[A B C] -> [C B A]\n[D E F] [F E D]\n*/\nvoid reverse_rows(matrix_data_t* data, int rows, int cols) {\n\n int r, c;\n matrix_data_t temp;\n matrix_data_t* pRow = NULL;\n\n for (r = 0; r < rows; ++r) {\n pRow = (data + r * cols);\n for (c = 0; c < (int)(cols / 2); ++c) { /* explicit truncate */\n temp = pRow[c];\n pRow[c] = pRow[cols - 1 - c];\n pRow[cols - 1 - c] = temp;\n }\n }\n}\n\n/*\nReverse values in place of each column in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols\n[A B C] -> [D E F]\n[D E F] [A B C]\n*/\nvoid reverse_cols(matrix_data_t* data, int rows, int cols) {\n\n int r, c;\n matrix_data_t temp;\n matrix_data_t* pRowA = NULL;\n matrix_data_t* pRowB = NULL;\n\n for (c = 0; c < cols; ++c) {\n for (r = 0; r < (int)(rows / 2); ++r) { /* explicit truncate */\n pRowA = data + r * cols;\n pRowB = data + cols * (rows - 1 - r);\n temp = pRowA[c];\n pRowA[c] = pRowB[c];\n pRowB[c] = temp;\n }\n }\n}\n\n/* Transpose NxM matrix to MxN matrix in O(n) time */\nvoid transpose(const matrix_data_t* src, matrix_data_t* dst, int N, int M) {\n\n int i;\n for (i = 0; i<N*M; ++i) dst[(i%M)*N + (i / M)] = src[i]; /* one-liner version */\n\n /*\n expanded version of one-liner: calculate XY based on array index, then convert that to YX array index\n int i,j,x,y;\n for (i = 0; i < N*M; ++i) {\n x = i % M;\n y = (int)(i / M);\n j = x * N + y;\n dst[j] = src[i];\n }\n */\n\n /*\n nested for loop version\n using ptr arithmetic to get proper row/column\n this is really just dst[col][row]=src[row][col]\n\n int r, c;\n\n for (r = 0; r < rows; ++r) {\n for (c = 0; c < cols; ++c) {\n (dst + c * rows)[r] = (src + r * cols)[c];\n }\n }\n */\n}\n\n/*\nTranspose NxN matrix in place\n*/\nvoid transpose_inplace(matrix_data_t* data, int N ) {\n\n int r, c;\n matrix_data_t temp;\n\n for (r = 0; r < N; ++r) {\n for (c = r; c < N; ++c) { /*start at column=row*/\n /* using ptr arithmetic to get proper row/column */\n /* this is really just\n temp=dst[col][row];\n dst[col][row]=src[row][col];\n src[row][col]=temp;\n */\n temp = (data + c * N)[r];\n (data + c * N)[r] = (data + r * N)[c];\n (data + r * N)[c] = temp;\n }\n }\n}\n\n/*\nRotate 1D or 2D src matrix to dst matrix in a direction (90,180,-90)\nPrecondition: src and dst are 2d matrices with dimensions src[rows][cols] and dst[cols][rows] or 1D pointers with logical rows/cols\n*/\nvoid rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols) {\n\n switch (direction) {\n case -90:\n transpose(src, dst, rows, cols);\n reverse_cols(dst, cols, rows);\n break;\n case 90:\n transpose(src, dst, rows, cols);\n reverse_rows(dst, cols, rows);\n break;\n case 180:\n case -180:\n /* bit copy to dst, use in-place reversals */\n memcpy(dst, src, rows*cols*sizeof(matrix_data_t));\n reverse_cols(dst, cols, rows);\n reverse_rows(dst, cols, rows);\n break;\n }\n}\n\n/*\nRotate array in a direction.\nArray must be NxN 2D or 1D array with logical rows/cols\nDirection can be (90,180,-90,-180)\n*/\nvoid rotate_inplace( int direction, matrix_data_t* data, int n) {\n\n switch (direction) {\n case -90:\n transpose_inplace(data, n);\n reverse_cols(data, n, n);\n break;\n case 90:\n transpose_inplace(data, n);\n reverse_rows(data, n, n);\n break;\n case 180:\n case -180:\n reverse_cols(data, n, n);\n reverse_rows(data, n, n);\n break;\n }\n}\n</code></pre>\n\n<p>`</p>\n"
},
{
"answer_id": 49619504,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Based on the plethora of other answers, I came up with this in C#:</p>\n\n<pre><code>/// <param name=\"rotation\">The number of rotations (if negative, the <see cref=\"Matrix{TValue}\"/> is rotated counterclockwise; \n/// otherwise, it's rotated clockwise). A single (positive) rotation is equivalent to 90° or -270°; a single (negative) rotation is \n/// equivalent to -90° or 270°. Matrices may be rotated by 90°, 180°, or 270° only (or multiples thereof).</param>\n/// <returns></returns>\npublic Matrix<TValue> Rotate(int rotation)\n{\n var result = default(Matrix<TValue>);\n\n //This normalizes the requested rotation (for instance, if 10 is specified, the rotation is actually just +-2 or +-180°, but all \n //correspond to the same rotation).\n var d = rotation.ToDouble() / 4d;\n d = d - (int)d;\n\n var degree = (d - 1d) * 4d;\n\n //This gets the type of rotation to make; there are a total of four unique rotations possible (0°, 90°, 180°, and 270°).\n //Each correspond to 0, 1, 2, and 3, respectively (or 0, -1, -2, and -3, if in the other direction). Since\n //1 is equivalent to -3 and so forth, we combine both cases into one. \n switch (degree)\n {\n case -3:\n case +1:\n degree = 3;\n break;\n case -2:\n case +2:\n degree = 2;\n break;\n case -1:\n case +3:\n degree = 1;\n break;\n case -4:\n case 0:\n case +4:\n degree = 0;\n break;\n }\n switch (degree)\n {\n //The rotation is 0, +-180°\n case 0:\n case 2:\n result = new TValue[Rows, Columns];\n break;\n //The rotation is +-90°\n case 1:\n case 3:\n result = new TValue[Columns, Rows];\n break;\n }\n\n for (uint i = 0; i < Columns; ++i)\n {\n for (uint j = 0; j < Rows; ++j)\n {\n switch (degree)\n {\n //If rotation is 0°\n case 0:\n result._values[j][i] = _values[j][i];\n break;\n //If rotation is -90°\n case 1:\n //Transpose, then reverse each column OR reverse each row, then transpose\n result._values[i][j] = _values[j][Columns - i - 1];\n break;\n //If rotation is +-180°\n case 2:\n //Reverse each column, then reverse each row\n result._values[(Rows - 1) - j][(Columns - 1) - i] = _values[j][i];\n break;\n //If rotation is +90°\n case 3:\n //Transpose, then reverse each row\n result._values[i][j] = _values[Rows - j - 1][i];\n break;\n }\n }\n }\n return result;\n}\n</code></pre>\n\n<p>Where <code>_values</code> corresponds to a private two-dimensional array defined by <code>Matrix<TValue></code> (in the form of <code>[][]</code>). <code>result = new TValue[Columns, Rows]</code> is possible via implicit operator overload and converts the two-dimensional array to <code>Matrix<TValue></code>.\nThe two properties <code>Columns</code> and <code>Rows</code> are public properties that get the number of columns and rows of the current instance:</p>\n\n<pre><code>public uint Columns \n => (uint)_values[0].Length;\n\npublic uint Rows \n => (uint)_values.Length;\n</code></pre>\n\n<p>Assuming, of course, that you prefer to work with unsigned indices ;-)</p>\n\n<p>All of this allows you to specify how many times it should be rotated and whether it should be rotated left (if less than zero) or right (if greater than zero). You can improve this to check for rotation in actual degrees, but then you'd want to throw an exception if the value isn't a multiple of 90. With that input, you could change the method accordingly:</p>\n\n<pre><code>public Matrix<TValue> Rotate(int rotation)\n{\n var _rotation = (double)rotation / 90d;\n\n if (_rotation - Math.Floor(_rotation) > 0)\n {\n throw new NotSupportedException(\"A matrix may only be rotated by multiples of 90.\").\n }\n\n rotation = (int)_rotation;\n ...\n}\n</code></pre>\n\n<p>Since a degree is more accurately expressed by <code>double</code> than <code>int</code>, but a matrix can only rotate in multiples of 90, it is far more intuitive to make the argument correspond to something else that can be accurately represented by the data structure used. <code>int</code> is perfect because it can tell you how many times to rotate it up to a certain unit (90) as well as the direction. <code>double</code> may very well be able to tell you that also, but it also includes values that aren't supported by this operation (which is inherently counter-intuitive).</p>\n"
},
{
"answer_id": 50540508,
"author": "Crashalot",
"author_id": 144088,
"author_profile": "https://Stackoverflow.com/users/144088",
"pm_score": 0,
"selected": false,
"text": "<p>Based on the community wiki algorithm and <a href=\"https://stackoverflow.com/a/32922962/144088\">this SO answer</a> for transposing arrays, here is a Swift 4 version to rotate some 2D array 90 degrees counter-clockwise. This assumes <code>matrix</code> is a 2D array:</p>\n\n<pre><code>func rotate(matrix: [[Int]]) -> [[Int]] {\n let transposedPoints = transpose(input: matrix)\n let rotatedPoints = transposedPoints.map{ Array($0.reversed()) }\n return rotatedPoints\n}\n\n\nfileprivate func transpose<T>(input: [[T]]) -> [[T]] {\n if input.isEmpty { return [[T]]() }\n let count = input[0].count\n var out = [[T]](repeating: [T](), count: count)\n for outer in input {\n for (index, inner) in outer.enumerated() {\n out[index].append(inner)\n }\n }\n\n return out\n}\n</code></pre>\n"
},
{
"answer_id": 50983147,
"author": "Toomtarm Kung",
"author_id": 1483126,
"author_profile": "https://Stackoverflow.com/users/1483126",
"pm_score": 0,
"selected": false,
"text": "<p>This solution doesn't care square or rectangle dimension, you can rotate 4x5 or 5x4 or even 4x4, it doesn't care the size as well.\nNote that this implementation creates a new array every time you call rotate90 method, it doesn't mutate the original array at all.</p>\n\n<pre><code>public static void main(String[] args) {\n int[][] a = new int[][] { \n { 1, 2, 3, 4 }, \n { 5, 6, 7, 8 }, \n { 9, 0, 1, 2 }, \n { 3, 4, 5, 6 }, \n { 7, 8, 9, 0 } \n };\n int[][] rotate180 = rotate90(rotate90(a));\n print(rotate180);\n}\n\nstatic int[][] rotate90(int[][] a) {\n int[][] ret = new int[a[0].length][a.length];\n for (int i = 0; i < a.length; i++) {\n for (int j = 0; j < a[i].length; j++) {\n ret[j][a.length - i - 1] = a[i][j];\n }\n }\n return ret;\n}\n\nstatic void print(int[][] array) {\n for (int i = 0; i < array.length; i++) {\n System.out.print(\"[\");\n for (int j = 0; j < array[i].length; j++) {\n System.out.print(array[i][j]);\n System.out.print(\" \");\n }\n System.out.println(\"]\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 61812224,
"author": "advncd",
"author_id": 996926,
"author_profile": "https://Stackoverflow.com/users/996926",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to do this with a <strong>single loop</strong>. The time complexity seems like <strong>O(K)</strong> where K is all items of the array. \nHere's how I did it in JavaScript:</p>\n\n<p>First off, we represent the n^2 matrix with a single array. Then, iterate through it like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * Rotates matrix 90 degrees clockwise\n * @param arr: the source array\n * @param n: the array side (array is square n^2)\n */\nfunction rotate (arr, n) {\n var rotated = [], indexes = []\n\n for (var i = 0; i < arr.length; i++) {\n if (i < n)\n indexes[i] = i * n + (n - 1)\n else\n indexes[i] = indexes[i - n] - 1\n\n rotated[indexes[i]] = arr[i]\n }\n return rotated\n}\n</code></pre>\n\n<p>Basically, we transform the source array indexes:</p>\n\n<p><code>[0,1,2,3,4,5,6,7,8]</code> => <code>[2,5,8,1,4,7,0,3,6]</code></p>\n\n<p>Then, using this transformed <code>indexes</code> array, we place the actual values in the final <code>rotated</code> array.</p>\n\n<p>Here are some test cases:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>//n=3\nrotate([\n 1, 2, 3,\n 4, 5, 6,\n 7, 8, 9], 3))\n\n//result:\n[7, 4, 1,\n 8, 5, 2,\n 9, 6, 3]\n\n\n//n=4\nrotate([\n 1, 2, 3, 4,\n 5, 6, 7, 8,\n 9, 10, 11, 12,\n 13, 14, 15, 16], 4))\n\n//result:\n[13, 9, 5, 1,\n 14, 10, 6, 2,\n 15, 11, 7, 3,\n 16, 12, 8, 4]\n\n\n//n=5\nrotate([\n 1, 2, 3, 4, 5,\n 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15,\n 16, 17, 18, 19, 20,\n 21, 22, 23, 24, 25], 5))\n\n//result:\n[21, 16, 11, 6, 1, \n 22, 17, 12, 7, 2, \n 23, 18, 13, 8, 3, \n 24, 19, 14, 9, 4, \n 25, 20, 15, 10, 5]\n</code></pre>\n"
},
{
"answer_id": 63046730,
"author": "Meow",
"author_id": 1509571,
"author_profile": "https://Stackoverflow.com/users/1509571",
"pm_score": 0,
"selected": false,
"text": "<p>In <a href=\"http://eigen.tuxfamily.org/\" rel=\"nofollow noreferrer\">Eigen</a> (C++):</p>\n<pre><code>Eigen::Matrix2d mat;\nmat << 1, 2,\n 3, 4;\nstd::cout << mat << "\\n\\n";\n\nEigen::Matrix2d r_plus_90 = mat.transpose().rowwise().reverse();\nstd::cout << r_plus_90 << "\\n\\n";\n\nEigen::Matrix2d r_minus_90 = mat.transpose().colwise().reverse();\nstd::cout << r_minus_90 << "\\n\\n";\n\nEigen::Matrix2d r_180 = mat.colwise().reverse().rowwise().reverse(); // +180 same as -180\nstd::cout << r_180 << "\\n\\n";\n</code></pre>\n<p>Output:</p>\n<pre><code>1 2\n3 4\n\n3 1\n4 2\n\n2 4\n1 3\n\n4 3\n2 1\n</code></pre>\n"
},
{
"answer_id": 63949048,
"author": "Kapil",
"author_id": 7283174,
"author_profile": "https://Stackoverflow.com/users/7283174",
"pm_score": 3,
"selected": false,
"text": "<p>A common method to rotate a 2D array clockwise or anticlockwise.</p>\n<ul>\n<li>clockwise rotate\n<ul>\n<li>first reverse up to down, then swap the symmetry\n<pre><code>1 2 3 7 8 9 7 4 1\n4 5 6 => 4 5 6 => 8 5 2\n7 8 9 1 2 3 9 6 3\n</code></pre>\n</li>\n</ul>\n</li>\n</ul>\n<pre><code>void rotate(vector<vector<int> > &matrix) {\n reverse(matrix.begin(), matrix.end());\n for (int i = 0; i < matrix.size(); ++i) {\n for (int j = i + 1; j < matrix[i].size(); ++j)\n swap(matrix[i][j], matrix[j][i]);\n }\n}\n</code></pre>\n<ul>\n<li>anticlockwise rotate\n<ul>\n<li>first reverse left to right, then swap the symmetry\n<pre><code>1 2 3 3 2 1 3 6 9\n4 5 6 => 6 5 4 => 2 5 8\n7 8 9 9 8 7 1 4 7\n</code></pre>\n</li>\n</ul>\n</li>\n</ul>\n<pre><code>void anti_rotate(vector<vector<int> > &matrix) {\n for (auto vi : matrix) reverse(vi.begin(), vi.end());\n for (int i = 0; i < matrix.size(); ++i) {\n for (int j = i + 1; j < matrix[i].size(); ++j)\n swap(matrix[i][j], matrix[j][i]);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67960479,
"author": "Michael Dunne",
"author_id": 6171525,
"author_profile": "https://Stackoverflow.com/users/6171525",
"pm_score": 2,
"selected": false,
"text": "<p>In python:</p>\n<pre><code>import numpy as np\n\na = np.array(\n [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 0, 1, 2],\n [3, 4, 5, 6]\n ]\n)\n\nprint(a)\nprint(b[::-1, :].T)\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] | Inspired by [Raymond Chen's post](https://devblogs.microsoft.com/oldnewthing/20080902-00/?p=21003), say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.
```
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
```
Becomes:
```
[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
```
**Update**: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000? | Here it is in C#
```csharp
int[,] array = new int[4,4] {
{ 1,2,3,4 },
{ 5,6,7,8 },
{ 9,0,1,2 },
{ 3,4,5,6 }
};
int[,] rotated = RotateMatrix(array, 4);
static int[,] RotateMatrix(int[,] matrix, int n) {
int[,] ret = new int[n, n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ret[i, j] = matrix[n - j - 1, i];
}
}
return ret;
}
``` |
42,531 | <p>Looking for an example that:</p>
<ol>
<li>Launches an EXE</li>
<li>Waits for the EXE to finish.</li>
<li>Properly closes all the handles when the executable finishes.</li>
</ol>
| [
{
"answer_id": 42543,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 5,
"selected": false,
"text": "<p>There is an example at <a href=\"http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx\" rel=\"noreferrer\"><a href=\"http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx</a></a></p>\n\n<p>Just replace the <code>argv[1]</code> with your constant or variable containing the program.</p>\n\n<pre><code>#include <windows.h>\n#include <stdio.h>\n#include <tchar.h>\n\nvoid _tmain( int argc, TCHAR *argv[] )\n{\n STARTUPINFO si;\n PROCESS_INFORMATION pi;\n\n ZeroMemory( &si, sizeof(si) );\n si.cb = sizeof(si);\n ZeroMemory( &pi, sizeof(pi) );\n\n if( argc != 2 )\n {\n printf(\"Usage: %s [cmdline]\\n\", argv[0]);\n return;\n }\n\n // Start the child process. \n if( !CreateProcess( NULL, // No module name (use command line)\n argv[1], // Command line\n NULL, // Process handle not inheritable\n NULL, // Thread handle not inheritable\n FALSE, // Set handle inheritance to FALSE\n 0, // No creation flags\n NULL, // Use parent's environment block\n NULL, // Use parent's starting directory \n &si, // Pointer to STARTUPINFO structure\n &pi ) // Pointer to PROCESS_INFORMATION structure\n ) \n {\n printf( \"CreateProcess failed (%d).\\n\", GetLastError() );\n return;\n }\n\n // Wait until child process exits.\n WaitForSingleObject( pi.hProcess, INFINITE );\n\n // Close process and thread handles. \n CloseHandle( pi.hProcess );\n CloseHandle( pi.hThread );\n}\n</code></pre>\n"
},
{
"answer_id": 42544,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 7,
"selected": true,
"text": "<p>Something like this:</p>\n\n<pre><code>STARTUPINFO info={sizeof(info)};\nPROCESS_INFORMATION processInfo;\nif (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))\n{\n WaitForSingleObject(processInfo.hProcess, INFINITE);\n CloseHandle(processInfo.hProcess);\n CloseHandle(processInfo.hThread);\n}\n</code></pre>\n"
},
{
"answer_id": 42583,
"author": "Mike Ellery",
"author_id": 1362,
"author_profile": "https://Stackoverflow.com/users/1362",
"pm_score": 3,
"selected": false,
"text": "<p>if your exe happens to be a console app, you might be interested in reading the stdout and stderr -- for that, I'll humbly refer you to this example:</p>\n\n<p><a href=\"http://support.microsoft.com/default.aspx?scid=kb;EN-US;q190351\" rel=\"noreferrer\">http://support.microsoft.com/default.aspx?scid=kb;EN-US;q190351</a></p>\n\n<p>It's a bit of a mouthful of code, but I've used variations of this code to spawn and read.</p>\n"
},
{
"answer_id": 42729,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 3,
"selected": false,
"text": "<p>On a semi-related note, if you want to start a process that has more privileges than your current process (say, launching an admin app, which requires Administrator rights, from the main app running as a normal user), you can't do so using CreateProcess() on Vista since it won't trigger the UAC dialog (assuming it is enabled). The UAC dialog is triggered when using ShellExecute(), though.</p>\n"
},
{
"answer_id": 99645,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 4,
"selected": false,
"text": "<p>If you application is a Windows GUI application then using the code below to do the waiting is not ideal as messages for your application will not be getting processing. To the user it will look like your application has hung.</p>\n\n<pre><code>WaitForSingleObject(&processInfo.hProcess, INFINITE)\n</code></pre>\n\n<p>Something like the <strong><em>untested</em></strong> code below might be better as it will keep processing the windows message queue and your application will remain responsive:</p>\n\n<pre><code>//-- wait for the process to finish\nwhile (true)\n{\n //-- see if the task has terminated\n DWORD dwExitCode = WaitForSingleObject(ProcessInfo.hProcess, 0);\n\n if ( (dwExitCode == WAIT_FAILED )\n || (dwExitCode == WAIT_OBJECT_0 )\n || (dwExitCode == WAIT_ABANDONED) )\n {\n DWORD dwExitCode;\n\n //-- get the process exit code\n GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);\n\n //-- the task has ended so close the handle\n CloseHandle(ProcessInfo.hThread);\n CloseHandle(ProcessInfo.hProcess);\n\n //-- save the exit code\n lExitCode = dwExitCode;\n\n return;\n }\n else\n {\n //-- see if there are any message that need to be processed\n while (PeekMessage(&message.msg, 0, 0, 0, PM_NOREMOVE))\n {\n if (message.msg.message == WM_QUIT)\n {\n return;\n }\n\n //-- process the message queue\n if (GetMessage(&message.msg, 0, 0, 0))\n {\n //-- process the message\n TranslateMessage(&pMessage->msg);\n DispatchMessage(&pMessage->msg);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 340042,
"author": "Bob Moore",
"author_id": 9368,
"author_profile": "https://Stackoverflow.com/users/9368",
"pm_score": 2,
"selected": false,
"text": "<p>Bear in mind that using <code>WaitForSingleObject</code> can get you into trouble in this scenario. The following is snipped from a tip on my website:</p>\n\n<blockquote>\n <p>The problem arises because your application has a window but isn't pumping messages. If the spawned application invokes SendMessage with one of the broadcast targets (<em>HWND_BROADCAST</em> or <em>HWND_TOPMOST</em>), then the SendMessage won't return to the new application until all applications have handled the message - but your app can't handle the message because it isn't pumping messages.... so the new app locks up, so your wait never succeeds.... DEADLOCK.</p>\n</blockquote>\n\n<p>If you have absolute control over the spawned application, then there are measures you can take, such as using SendMessageTimeout rather than SendMessage (e.g. for DDE initiations, if anybody is still using that). But there are situations which cause implicit SendMessage broadcasts over which you have no control, such as using the SetSysColors API for instance.</p>\n\n<p>The only safe ways round this are:</p>\n\n<ol>\n<li>split off the Wait into a separate thread, or </li>\n<li>use a timeout on the Wait and use PeekMessage in your Wait loop to ensure that you pump messages, or </li>\n<li>use the <code>MsgWaitForMultipleObjects</code> API.</li>\n</ol>\n"
},
{
"answer_id": 5862370,
"author": "pcunite",
"author_id": 645583,
"author_profile": "https://Stackoverflow.com/users/645583",
"pm_score": 3,
"selected": false,
"text": "<p>Perhaps this is the most complete?\n<a href=\"http://goffconcepts.com/techarticles/createprocess.html\" rel=\"nofollow noreferrer\">http://goffconcepts.com/techarticles/createprocess.html</a></p>\n"
},
{
"answer_id": 46831649,
"author": "Blue7",
"author_id": 3052832,
"author_profile": "https://Stackoverflow.com/users/3052832",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a new example that works on windows 10. When using the windows10 sdk you have to use CreateProcessW instead. This example is commented and hopefully self explanatory.</p>\n\n<pre><code>#ifdef _WIN32\n#include <Windows.h>\n#include <iostream>\n#include <stdio.h>\n#include <tchar.h>\n#include <cstdlib>\n#include <string>\n#include <algorithm>\n\nclass process\n{\npublic:\n\n static PROCESS_INFORMATION launchProcess(std::string app, std::string arg)\n {\n\n // Prepare handles.\n STARTUPINFO si;\n PROCESS_INFORMATION pi; // The function returns this\n ZeroMemory( &si, sizeof(si) );\n si.cb = sizeof(si);\n ZeroMemory( &pi, sizeof(pi) );\n\n //Prepare CreateProcess args\n std::wstring app_w(app.length(), L' '); // Make room for characters\n std::copy(app.begin(), app.end(), app_w.begin()); // Copy string to wstring.\n\n std::wstring arg_w(arg.length(), L' '); // Make room for characters\n std::copy(arg.begin(), arg.end(), arg_w.begin()); // Copy string to wstring.\n\n std::wstring input = app_w + L\" \" + arg_w;\n wchar_t* arg_concat = const_cast<wchar_t*>( input.c_str() );\n const wchar_t* app_const = app_w.c_str();\n\n // Start the child process.\n if( !CreateProcessW(\n app_const, // app path\n arg_concat, // Command line (needs to include app path as first argument. args seperated by whitepace)\n NULL, // Process handle not inheritable\n NULL, // Thread handle not inheritable\n FALSE, // Set handle inheritance to FALSE\n 0, // No creation flags\n NULL, // Use parent's environment block\n NULL, // Use parent's starting directory\n &si, // Pointer to STARTUPINFO structure\n &pi ) // Pointer to PROCESS_INFORMATION structure\n )\n {\n printf( \"CreateProcess failed (%d).\\n\", GetLastError() );\n throw std::exception(\"Could not create child process\");\n }\n else\n {\n std::cout << \"[ ] Successfully launched child process\" << std::endl;\n }\n\n // Return process handle\n return pi;\n }\n\n static bool checkIfProcessIsActive(PROCESS_INFORMATION pi)\n {\n // Check if handle is closed\n if ( pi.hProcess == NULL )\n {\n printf( \"Process handle is closed or invalid (%d).\\n\", GetLastError());\n return FALSE;\n }\n\n // If handle open, check if process is active\n DWORD lpExitCode = 0;\n if( GetExitCodeProcess(pi.hProcess, &lpExitCode) == 0)\n {\n printf( \"Cannot return exit code (%d).\\n\", GetLastError() );\n throw std::exception(\"Cannot return exit code\");\n }\n else\n {\n if (lpExitCode == STILL_ACTIVE)\n {\n return TRUE;\n }\n else\n {\n return FALSE;\n }\n }\n }\n\n static bool stopProcess( PROCESS_INFORMATION &pi)\n {\n // Check if handle is invalid or has allready been closed\n if ( pi.hProcess == NULL )\n {\n printf( \"Process handle invalid. Possibly allready been closed (%d).\\n\");\n return 0;\n }\n\n // Terminate Process\n if( !TerminateProcess(pi.hProcess,1))\n {\n printf( \"ExitProcess failed (%d).\\n\", GetLastError() );\n return 0;\n }\n\n // Wait until child process exits.\n if( WaitForSingleObject( pi.hProcess, INFINITE ) == WAIT_FAILED)\n {\n printf( \"Wait for exit process failed(%d).\\n\", GetLastError() );\n return 0;\n }\n\n // Close process and thread handles.\n if( !CloseHandle( pi.hProcess ))\n {\n printf( \"Cannot close process handle(%d).\\n\", GetLastError() );\n return 0;\n }\n else\n {\n pi.hProcess = NULL;\n }\n\n if( !CloseHandle( pi.hThread ))\n {\n printf( \"Cannot close thread handle (%d).\\n\", GetLastError() );\n return 0;\n }\n else\n {\n pi.hProcess = NULL;\n }\n return 1;\n }\n};//class process\n#endif //win32\n</code></pre>\n"
},
{
"answer_id": 70626460,
"author": "reem_mikulsky",
"author_id": 15799356,
"author_profile": "https://Stackoverflow.com/users/15799356",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a solution for <code>CreateProcessA</code></p>\n<pre><code>STARTUPINFOW initInfo = { 0 };\ninitInfo.cb = sizeof(initInfo);\nPROCESS_INFORMATION procInfo = { 0 };\n\nCreateProcessA(PATH_FOR_EXE, NULL, NULL, NULL, FALSE, 0, NULL, NULL, (LPSTARTUPINFOA)&initInfo, &procInfo);\n</code></pre>\n"
},
{
"answer_id": 71851383,
"author": "Giver Khadka",
"author_id": 10586192,
"author_profile": "https://Stackoverflow.com/users/10586192",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <Windows.h>\nvoid my_cmd()\n{\n STARTUPINFO si;\n PROCESS_INFORMATION pi;\n ZeroMemory(&si, sizeof(si));\n si.cb = sizeof(si);\n ZeroMemory(&pi, sizeof(pi));\n // CMD command here\n char arg[] = "cmd.exe /c E:/Softwares/program.exe";\n // Convert char string to required LPWSTR string\n wchar_t text[500];\n mbstowcs(text, arg, strlen(arg) + 1);\n LPWSTR command = text;\n // Run process\n CreateProcess (NULL, command, NULL, NULL, 0, \n CREATE_NO_WINDOW, NULL, NULL, &si, &pi);\n}\n</code></pre>\n<p>This works fine for me. No popup windows and cmd command runs as expected. Just needed to convert the CHAR pointer into WCHAR pointer and add extra "cmd.exe /c" before every command.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | Looking for an example that:
1. Launches an EXE
2. Waits for the EXE to finish.
3. Properly closes all the handles when the executable finishes. | Something like this:
```
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
``` |
42,566 | <p>I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?</p>
<p>Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):</p>
<blockquote>
<p>The [below] code does NOT make a
connection or send any packets (to
64.233.187.99 which is google). Since UDP is a stateless protocol connect()
merely makes a system call which
figures out how to route the packets
based on the address and what
interface (and therefore IP address)
it should bind to. addr() returns an
array containing the family (AF_INET),
local port, and local address (which
is what we want) of the socket.</p>
</blockquote>
| [
{
"answer_id": 42595,
"author": "Craig",
"author_id": 1611,
"author_profile": "https://Stackoverflow.com/users/1611",
"pm_score": 0,
"selected": false,
"text": "<p>try: <a href=\"http://apidock.com/rails/v2.3.8/ActionController/Request/remote_ip\" rel=\"nofollow noreferrer\">Request.remote_ip</a></p>\n\n<blockquote>\n <p>remote_ip()</p>\n \n <p>Determine originating IP address. REMOTE_ADDR is the standard but will\n fail if the user is behind a proxy. HTTP_CLIENT_IP and/or\n HTTP_X_FORWARDED_FOR are set by proxies so check for these if\n REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma- delimited\n list in the case of multiple chained proxies; the last address which\n is not trusted is the originating IP.</p>\n</blockquote>\n\n<p>Update:\nOops, sorry I misread the documentation.</p>\n"
},
{
"answer_id": 42624,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 5,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>host = `hostname`.strip # Get the hostname from the shell and removing trailing \\n\nputs host # Output the hostname\n</code></pre>\n"
},
{
"answer_id": 42736,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 1,
"selected": false,
"text": "<p>You will likely find yourself having multiple IP addresses on each machine (127.0.0.1, 192.168.0.1, etc). If you are using *NIX as your OS, I'd suggest using <code>hostname</code>, and then running a DNS look up on that. You should be able to use /etc/hosts to define the local hostname to resolve to the IP address for that machine. There is similar functionality on Windows, but I haven't used it since Windows 95 was the bleeding edge.</p>\n\n<p>The other option would be to hit a lookup service like <a href=\"http://whatismyip.com/automation/n09230945.asp\" rel=\"nofollow noreferrer\">WhatIsMyIp.com</a>. These guys will kick back your real-world IP address to you. This is also something that you can easily setup with a Perl script on a local server if you prefer. I believe 3 lines or so of code to output the remote IP from %ENV should cover you.</p>\n"
},
{
"answer_id": 42923,
"author": "titanous",
"author_id": 399,
"author_profile": "https://Stackoverflow.com/users/399",
"pm_score": 7,
"selected": true,
"text": "<p>From <a href=\"http://coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/\" rel=\"noreferrer\">coderrr.wordpress.com</a>:</p>\n\n<pre><code>require 'socket'\n\ndef local_ip\n orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily\n\n UDPSocket.open do |s|\n s.connect '64.233.187.99', 1\n s.addr.last\n end\nensure\n Socket.do_not_reverse_lookup = orig\nend\n\n# irb:0> local_ip\n# => \"192.168.0.127\"\n</code></pre>\n"
},
{
"answer_id": 1535556,
"author": "Tim Peters",
"author_id": 180800,
"author_profile": "https://Stackoverflow.com/users/180800",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Hostname</strong></p>\n\n<p>A simple way to just get the hostname in Ruby is:</p>\n\n<pre><code>require 'socket'\nhostname = Socket.gethostname\n</code></pre>\n\n<p>The catch is that this relies on the host knowing its own name because it uses either the <code>gethostname</code> or <code>uname</code> system call, so it will not work for the original problem. </p>\n\n<p>Functionally this is identical to the <code>hostname</code> answer, without invoking an external program. The hostname may or may not be fully qualified, depending on the machine's configuration.</p>\n\n<hr>\n\n<p><strong>IP Address</strong></p>\n\n<p>Since ruby 1.9, you can also use the Socket library to get a list of local addresses. <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/Socket.html#method-c-ip_address_list\" rel=\"noreferrer\"><code>ip_address_list</code></a> returns an array of <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/Addrinfo.html\" rel=\"noreferrer\">AddrInfo</a> objects. How you choose from it will depend on what you want to do and how many interfaces you have, but here's an example which simply selects the first non-loopback IPV4 IP address as a string:</p>\n\n<pre><code>require 'socket'\nip_address = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address\n</code></pre>\n"
},
{
"answer_id": 1619840,
"author": "Sai",
"author_id": 102580,
"author_profile": "https://Stackoverflow.com/users/102580",
"pm_score": 2,
"selected": false,
"text": "<p>Put the highlighted part in backticks:</p>\n\n<pre><code>`dig #{request.host} +short`.strip # dig gives a newline at the end\n</code></pre>\n\n<p>Or just <code>request.host</code> if you don't care whether it's an IP or not.</p>\n"
},
{
"answer_id": 3246800,
"author": "Salil",
"author_id": 297087,
"author_profile": "https://Stackoverflow.com/users/297087",
"pm_score": 3,
"selected": false,
"text": "<p>Simplest is <a href=\"http://api.rubyonrails.org/classes/ActionController/Request.html#M000521\" rel=\"noreferrer\"><code>host_with_port</code></a> in controller.rb</p>\n\n<pre><code>host_port= request.host_with_port\n</code></pre>\n"
},
{
"answer_id": 4726312,
"author": "hacintosh",
"author_id": 50029,
"author_profile": "https://Stackoverflow.com/users/50029",
"pm_score": 2,
"selected": false,
"text": "<p>The accepted answer works but you have to create a socket for every request and it does not work if the server is on a local network and/or not connected to the internet. The below, I believe will always work since it is parsing the request header.</p>\n\n<pre><code>request.env[\"SERVER_ADDR\"]\n</code></pre>\n"
},
{
"answer_id": 5030162,
"author": "D-D-Doug",
"author_id": 462965,
"author_profile": "https://Stackoverflow.com/users/462965",
"pm_score": 3,
"selected": false,
"text": "<p>This IP address used here is Google's, but you can use any accessible IP.</p>\n\n<pre><code>require \"socket\"\nlocal_ip = UDPSocket.open {|s| s.connect(\"64.233.187.99\", 1); s.addr.last}\n</code></pre>\n"
},
{
"answer_id": 7809076,
"author": "Claudio Floreani",
"author_id": 985792,
"author_profile": "https://Stackoverflow.com/users/985792",
"pm_score": 4,
"selected": false,
"text": "<p>A server typically has more than one interface, at least one private and one public.</p>\n\n<p>Since all the answers here deal with this simple scenario, a cleaner way is to ask Socket for the current <code>ip_address_list()</code> as in:</p>\n\n<pre><code>require 'socket'\n\ndef my_first_private_ipv4\n Socket.ip_address_list.detect{|intf| intf.ipv4_private?}\nend\n\ndef my_first_public_ipv4\n Socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}\nend\n</code></pre>\n\n<p>Both return an Addrinfo object, so if you need a string you can use the <code>ip_address()</code> method, as in:</p>\n\n<pre><code>ip= my_first_public_ipv4.ip_address unless my_first_public_ipv4.nil?\n</code></pre>\n\n<p>You can easily work out the more suitable solution to your case changing the Addrinfo methods used to filter the required interface address.</p>\n"
},
{
"answer_id": 8174503,
"author": "Kevin Krauss",
"author_id": 1052717,
"author_profile": "https://Stackoverflow.com/users/1052717",
"pm_score": 1,
"selected": false,
"text": "<pre><code>io = IO.popen('hostname')\nhostname = io.readlines\n\nio = IO.popen('ifconfig')\nifconfig = io.readlines\nip = ifconfig[11].scan(/\\ \\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\ /)\n</code></pre>\n\n<p>The couple of answers with <code>require 'socket'</code> look good. The ones with request.blah_blah_blah\nassume that you are using Rails. </p>\n\n<p>IO should be available all the time. The only problem with this script would be that if <code>ifconfig</code> is output in a different manor on your systems, then you would get different results for the IP. The hostname look up should be solid as Sears. </p>\n"
},
{
"answer_id": 12632929,
"author": "Tilo",
"author_id": 677684,
"author_profile": "https://Stackoverflow.com/users/677684",
"pm_score": 2,
"selected": false,
"text": "<p>Similar to the answer using <code>hostname</code>, using the external <code>uname</code> command on UNIX/LINUX:</p>\n\n<pre><code>hostname = `uname -n`.chomp.sub(/\\..*/,'') # stripping off \"\\n\" and the network name if present\n</code></pre>\n\n<p>for the IP addresses in use (your machine could have multiple network interfaces),\nyou could use something like this:</p>\n\n<pre><code> # on a Mac:\n ip_addresses = `ifconfig | grep 'inet ' | grep -v 127.0.0.1 | cut -d' ' -f 2`.split\n => ['10.2.21.122','10.8.122.12']\n\n # on Linux:\n ip_addresses = `ifconfig -a | grep 'inet ' | grep -v 127.0.0.1 | cut -d':' -f 2 | cut -d' ' -f 1`.split\n => ['10.2.21.122','10.8.122.12']\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] | I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?
Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):
>
> The [below] code does NOT make a
> connection or send any packets (to
> 64.233.187.99 which is google). Since UDP is a stateless protocol connect()
> merely makes a system call which
> figures out how to route the packets
> based on the address and what
> interface (and therefore IP address)
> it should bind to. addr() returns an
> array containing the family (AF\_INET),
> local port, and local address (which
> is what we want) of the socket.
>
>
> | From [coderrr.wordpress.com](http://coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/):
```
require 'socket'
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
# irb:0> local_ip
# => "192.168.0.127"
``` |
42,575 | <p>We're currently using Lucene 2.1.0 for our site search and we've hit a difficult problem: one of our index fields is being ignored during a targeted search. Here is the code for adding the field to a document in our index:</p>
<pre><code>// Add market_local to index
contactDocument.add(
new Field(
"market_local"
, StringUtils.objectToString(
currClip.get(
"market_local"
)
)
, Field.Store.YES
, Field.Index.UN_TOKENIZED
)
);
</code></pre>
<p>Running a query ( * ) against the index will return the following results:</p>
<pre><code>Result 1:
title: Foo Bar
market_local: Local
Result 2:
title: Bar Foo
market_local: National
</code></pre>
<p>Running a targeted query:</p>
<pre><code>+( market_local:Local )
</code></pre>
<p>won't find any results.</p>
<p>I realize this is a highly specific question, I'm just trying to get information on where to start debugging this issue, as I'm a Lucene newbie.</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>Installed Luke, checking out latest index... the Field <em>market_local</em> is available in searches, so if I execute something like:</p>
<pre><code>market_local:Local
</code></pre>
<p>The search works correctly (in Luke). I'm going over our Analyzer code now, is there any way I could chalk this issue up to the fact that our search application is using Lucene 2.1.0 and the latest version of Luke is using 2.3.0?</p>
| [
{
"answer_id": 42734,
"author": "Darren Hague",
"author_id": 4450,
"author_profile": "https://Stackoverflow.com/users/4450",
"pm_score": 4,
"selected": true,
"text": "<p>For debugging Lucene, the best tool to use is <a href=\"http://www.getopt.org/luke/\" rel=\"noreferrer\">Luke</a>, which lets you poke around in the index itself to see what got indexed, carry out searches, etc. I recommend downloading it, pointing it at your index, and seeing what's in there.</p>\n"
},
{
"answer_id": 43530,
"author": "Martin McNulty",
"author_id": 4507,
"author_profile": "https://Stackoverflow.com/users/4507",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://wiki.apache.org/lucene-java/LuceneFAQ#head-3558e5121806fb4fce80fc022d889484a9248b71\" rel=\"nofollow noreferrer\">section on \"Why am I getting no hits?\"</a> in the Lucene FAQ has some suggestions you might find useful. You're using Field.Index.UN_TOKENIZED, so no Analyzer will be used for indexing (I think). If you're using an Analyzer when you're searching then that might be the root of your problem - the indexing and searching Analyzers should be the same to make sure you get the right hits.</p>\n"
},
{
"answer_id": 43546,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 1,
"selected": false,
"text": "<p>Another simple thing to do would be to use a debugger or logging statement to check the value of </p>\n\n<blockquote>\n <p>StringUtils.objectToString(currClip.get(\"market_local\"))</p>\n</blockquote>\n\n<p>to make sure it is what you think it is.</p>\n"
},
{
"answer_id": 150939,
"author": "Kai Chan",
"author_id": 23589,
"author_profile": "https://Stackoverflow.com/users/23589",
"pm_score": 1,
"selected": false,
"text": "<p>Luke is bundled with Lucene, but you can tell Luke to use another version of Lucene. Say \"lucene-core-2.1.0.jar\" contains Lucene 2.1.0 that you want to use and \"luke.jar\" contains Luke with Lucene 2.3.0. Then you can start Luke with the following command.</p>\n\n<blockquote>\n <p>java -classpath lucene-core-2.1.0.jar;luke.jar org.getopt.luke.Luke</p>\n</blockquote>\n\n<p>(The trick is to put your version of Lucene before Luke on the classpath. Also, This is on Windows. On Unix, replace \";\" with \":\".)</p>\n\n<p>As you can check in Luke,</p>\n\n<blockquote>\n <p>+( market_local:Local )</p>\n</blockquote>\n\n<p>gets rewritten to</p>\n\n<blockquote>\n <p>market_local:Local</p>\n</blockquote>\n\n<p>if <a href=\"http://lucene.apache.org/java/2_3_2/api/org/apache/lucene/search/Query.html#rewrite(org.apache.lucene.index.IndexReader)\" rel=\"nofollow noreferrer\">the rewrite(IndexReader) method of the Query object</a> is called. The two queries should be equivalent so there might be a bug in 2.1. If you have to use 2.1, you can try to manually call that method before passing the Query object to the IndexSearcher.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302/"
] | We're currently using Lucene 2.1.0 for our site search and we've hit a difficult problem: one of our index fields is being ignored during a targeted search. Here is the code for adding the field to a document in our index:
```
// Add market_local to index
contactDocument.add(
new Field(
"market_local"
, StringUtils.objectToString(
currClip.get(
"market_local"
)
)
, Field.Store.YES
, Field.Index.UN_TOKENIZED
)
);
```
Running a query ( \* ) against the index will return the following results:
```
Result 1:
title: Foo Bar
market_local: Local
Result 2:
title: Bar Foo
market_local: National
```
Running a targeted query:
```
+( market_local:Local )
```
won't find any results.
I realize this is a highly specific question, I'm just trying to get information on where to start debugging this issue, as I'm a Lucene newbie.
---
**UPDATE**
Installed Luke, checking out latest index... the Field *market\_local* is available in searches, so if I execute something like:
```
market_local:Local
```
The search works correctly (in Luke). I'm going over our Analyzer code now, is there any way I could chalk this issue up to the fact that our search application is using Lucene 2.1.0 and the latest version of Luke is using 2.3.0? | For debugging Lucene, the best tool to use is [Luke](http://www.getopt.org/luke/), which lets you poke around in the index itself to see what got indexed, carry out searches, etc. I recommend downloading it, pointing it at your index, and seeing what's in there. |
42,581 | <p>The Python docs say:</p>
<blockquote>
<p>re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...</p>
</blockquote>
<p>So what's going on when I get the following unexpected result?</p>
<pre><code>>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'
</code></pre>
| [
{
"answer_id": 42597,
"author": "Moe",
"author_id": 3051,
"author_profile": "https://Stackoverflow.com/users/3051",
"pm_score": 8,
"selected": true,
"text": "<p>Look at the definition of <a href=\"http://docs.python.org/library/re.html#re.sub\" rel=\"noreferrer\"><code>re.sub</code></a>:</p>\n\n<pre><code>re.sub(pattern, repl, string[, count, flags])\n</code></pre>\n\n<p>The 4th argument is the count, you are using <code>re.MULTILINE</code> (which is 8) as the count, not as a flag.</p>\n\n<p>Either use a named argument:</p>\n\n<pre><code>re.sub('^//', '', s, flags=re.MULTILINE)\n</code></pre>\n\n<p>Or compile the regex first:</p>\n\n<pre><code>re.sub(re.compile('^//', re.MULTILINE), '', s)\n</code></pre>\n"
},
{
"answer_id": 2517216,
"author": "Ferran",
"author_id": 301850,
"author_profile": "https://Stackoverflow.com/users/301850",
"pm_score": 4,
"selected": false,
"text": "<pre><code>re.sub('(?m)^//', '', s)\n</code></pre>\n"
},
{
"answer_id": 7248027,
"author": "pseudosudo",
"author_id": 600012,
"author_profile": "https://Stackoverflow.com/users/600012",
"pm_score": 3,
"selected": false,
"text": "<p>The full definition of <a href=\"http://docs.python.org/library/re.html#re.sub\" rel=\"noreferrer\"><code>re.sub</code></a> is:</p>\n\n<pre><code>re.sub(pattern, repl, string[, count, flags])\n</code></pre>\n\n<p>Which means that if you tell Python what the parameters are, then you can pass <code>flags</code> without passing <code>count</code>:</p>\n\n<pre><code>re.sub('^//', '', s, flags=re.MULTILINE)\n</code></pre>\n\n<p>or, more concisely:</p>\n\n<pre><code>re.sub('^//', '', s, flags=re.M)\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | The Python docs say:
>
> re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...
>
>
>
So what's going on when I get the following unexpected result?
```
>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'
``` | Look at the definition of [`re.sub`](http://docs.python.org/library/re.html#re.sub):
```
re.sub(pattern, repl, string[, count, flags])
```
The 4th argument is the count, you are using `re.MULTILINE` (which is 8) as the count, not as a flag.
Either use a named argument:
```
re.sub('^//', '', s, flags=re.MULTILINE)
```
Or compile the regex first:
```
re.sub(re.compile('^//', re.MULTILINE), '', s)
``` |
42,587 | <p>I have heard/read the term but don't quite understand what it means.</p>
<p>When should I use this technique and how would I use it? Can anyone provide a good code sample?</p>
| [
{
"answer_id": 42656,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 7,
"selected": true,
"text": "<p>The visitor pattern is a way of doing double-dispatch in an object-oriented way.</p>\n\n<p>It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time.</p>\n\n<p>Double dispatch is a special case of <strong>multiple dispatch</strong>. </p>\n\n<p>When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object.</p>\n\n<p>For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time.</p>\n\n<p>In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.</p>\n\n<p>Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters.</p>\n\n<p><strong>To do double-dispatch in C#</strong>, you can declare a method with a sole object argument and then specific methods with specific types:</p>\n\n<pre><code>using System.Linq; \n\nclass DoubleDispatch\n{ \n public T Foo<T>(object arg)\n { \n var method = from m in GetType().GetMethods()\n where m.Name == \"Foo\" \n && m.GetParameters().Length==1\n && arg.GetType().IsAssignableFrom\n (m.GetParameters()[0].GetType())\n && m.ReturnType == typeof(T)\n select m;\n\n return (T) method.Single().Invoke(this,new object[]{arg}); \n }\n\n public int Foo(int arg) { /* ... */ }\n\n static void Test() \n { \n object x = 5;\n Foo<int>(x); //should call Foo(int) via Foo<T>(object).\n }\n} \n</code></pre>\n"
},
{
"answer_id": 6274270,
"author": "Zenwalker",
"author_id": 785375,
"author_profile": "https://Stackoverflow.com/users/785375",
"pm_score": 4,
"selected": false,
"text": "<p>The code posted by Mark isn't complete and what ever is there isn't working. </p>\n\n<p>So tweaked and complete.</p>\n\n<pre><code>class DoubleDispatch\n{\n public T Foo<T>(object arg)\n {\n var method = from m in GetType().GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)\n where m.Name == \"Foo\"\n && m.GetParameters().Length == 1\n //&& arg.GetType().IsAssignableFrom\n // (m.GetParameters()[0].GetType())\n &&Type.GetType(m.GetParameters()[0].ParameterType.FullName).IsAssignableFrom(arg.GetType())\n && m.ReturnType == typeof(T)\n select m;\n\n\n return (T)method.Single().Invoke(this, new object[] { arg });\n }\n\n public int Foo(int arg)\n {\n return 10;\n }\n\n public string Foo(string arg)\n {\n return 5.ToString();\n }\n\n public static void Main(string[] args)\n {\n object x = 5;\n DoubleDispatch dispatch = new DoubleDispatch();\n\n Console.WriteLine(dispatch.Foo<int>(x));\n\n\n Console.WriteLine(dispatch.Foo<string>(x.ToString()));\n\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>Thanks Mark and others for nice explanation on Double Dispatcher pattern.</p>\n"
},
{
"answer_id": 45053773,
"author": "Micha Wiedenmann",
"author_id": 1671066,
"author_profile": "https://Stackoverflow.com/users/1671066",
"pm_score": 3,
"selected": false,
"text": "<p>C# 4 introduces the pseudo type <code>dynamic</code> which resolves the function call at runtime (instead of compile time). (That is, the runtime type of the expression is used). Double- (or multi-dispatch) can be simplified to:</p>\n\n<pre><code>class C { }\n\nstatic void Foo(C x) => Console.WriteLine(nameof(Foo));\nstatic void Foo(object x) => Console.WriteLine(nameof(Object));\n\npublic static void Main(string[] args)\n{\n object x = new C();\n\n Foo((dynamic)x); // prints: \"Foo\"\n Foo(x); // prints: \"Object\"\n}\n</code></pre>\n\n<p>Note also by using <code>dynamic</code> you prevent the static analyzer of the compiler to examine this part of the code. You should therefore carefully consider the use of <code>dynamic</code>.</p>\n"
},
{
"answer_id": 59370408,
"author": "bugs-x64",
"author_id": 12550816,
"author_profile": "https://Stackoverflow.com/users/12550816",
"pm_score": 0,
"selected": false,
"text": "<p>Full listing of working code</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Linq;\n\nnamespace TestConsoleApp\n{\n internal class Program\n {\n public static void Main(string[] args)\n {\n const int x = 5;\n var dispatch = new DoubleDispatch();\n\n Console.WriteLine(dispatch.Foo<int>(x));\n Console.WriteLine(dispatch.Foo<string>(x.ToString()));\n\n Console.ReadLine();\n }\n }\n\n public class DoubleDispatch\n {\n public T Foo<T>(T arg)\n {\n var method = GetType()\n .GetMethods()\n .Single(m =>\n m.Name == \"Foo\" &&\n m.GetParameters().Length == 1 &&\n arg.GetType().IsAssignableFrom(m.GetParameters()[0].ParameterType) &&\n m.ReturnType == typeof(T));\n\n return (T) method.Invoke(this, new object[] {arg});\n }\n\n public int Foo(int arg)\n {\n return arg;\n }\n\n public string Foo(string arg)\n {\n return arg;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 61877919,
"author": "MikeJ",
"author_id": 1413174,
"author_profile": "https://Stackoverflow.com/users/1413174",
"pm_score": 3,
"selected": false,
"text": "<p>The other answers use generics and the runtime type system. But to be clear the use of generics and runtime type system doesn't have anything to do with double dispatch. They can be used to implement it but double dispatch is just dependent on using the concrete type at runtime to dispatch calls. It's illustrated more clearly I think in <a href=\"https://en.wikipedia.org/wiki/Double_dispatch\" rel=\"noreferrer\">the wikipedia page</a>. I'll include the translated C++ code below. The key to this is the virtual CollideWith on SpaceShip and that it's overridden on ApolloSpacecraft. This is where the \"double\" dispatch takes place and the correct asteroid method is called for the given spaceship type.</p>\n\n<pre><code>class SpaceShip\n{\n public virtual void CollideWith(Asteroid asteroid)\n {\n asteroid.CollideWith(this);\n }\n}\n\nclass ApolloSpacecraft : SpaceShip\n{\n public override void CollideWith(Asteroid asteroid)\n {\n asteroid.CollideWith(this);\n }\n}\n\nclass Asteroid\n{\n public virtual void CollideWith(SpaceShip target)\n {\n Console.WriteLine(\"Asteroid hit a SpaceShip\");\n }\n\n public virtual void CollideWith(ApolloSpacecraft target)\n {\n Console.WriteLine(\"Asteroid hit ApolloSpacecraft\");\n }\n}\n\nclass ExplodingAsteroid : Asteroid\n{\n public override void CollideWith(SpaceShip target)\n {\n Console.WriteLine(\"ExplodingAsteroid hit a SpaceShip\");\n }\n\n public override void CollideWith(ApolloSpacecraft target)\n {\n Console.WriteLine(\"ExplodingAsteroid hit ApolloSpacecraft\");\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Asteroid[] asteroids = new Asteroid[] { new Asteroid(), new ExplodingAsteroid() };\n\n ApolloSpacecraft spacecraft = new ApolloSpacecraft();\n\n spacecraft.CollideWith(asteroids[0]);\n spacecraft.CollideWith(asteroids[1]);\n\n SpaceShip spaceShip = new SpaceShip();\n\n spaceShip.CollideWith(asteroids[0]);\n spaceShip.CollideWith(asteroids[1]);\n }\n}\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
] | I have heard/read the term but don't quite understand what it means.
When should I use this technique and how would I use it? Can anyone provide a good code sample? | The visitor pattern is a way of doing double-dispatch in an object-oriented way.
It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time.
Double dispatch is a special case of **multiple dispatch**.
When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object.
For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time.
In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.
Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters.
**To do double-dispatch in C#**, you can declare a method with a sole object argument and then specific methods with specific types:
```
using System.Linq;
class DoubleDispatch
{
public T Foo<T>(object arg)
{
var method = from m in GetType().GetMethods()
where m.Name == "Foo"
&& m.GetParameters().Length==1
&& arg.GetType().IsAssignableFrom
(m.GetParameters()[0].GetType())
&& m.ReturnType == typeof(T)
select m;
return (T) method.Single().Invoke(this,new object[]{arg});
}
public int Foo(int arg) { /* ... */ }
static void Test()
{
object x = 5;
Foo<int>(x); //should call Foo(int) via Foo<T>(object).
}
}
``` |
42,703 | <p>I am using sp_send_dbmail in SQL2005 to send an email with the results in an attachment. When the attachment is sent it is UCS-2 Encoded, I want it to be ANSI or UTF-8.</p>
<p>Here is the SQL</p>
<pre><code>EXEC msdb.dbo.sp_send_dbmail
@recipients = '[email protected]'
, @query = 'DECLARE @string_to_trim varchar(60);SET @string_to_trim = ''1234''; select rtrim(@string_to_trim), ''tom'''
, @query_result_header=0
, @subject = 'see attach'
, @body= 'temp body'
, @profile_name= N'wksql01tAdmin'
, @body_format = 'HTML'
,@query_result_separator = ','
,@query_attachment_filename = 'results.csv'
,@query_no_truncate = '0'
,@attach_query_result_as_file = 1
</code></pre>
<p>I have seen some comments on the internet that this is fixed with sql2005 SP2, but do not find it to be the case.</p>
| [
{
"answer_id": 42728,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": true,
"text": "<p>I think the only way to get around what you are seeing is to use BCP to dump the data to a flat file and then attach that file. Sorry I couldn't be more help. :(</p>\n"
},
{
"answer_id": 5783390,
"author": "bushtwig",
"author_id": 588229,
"author_profile": "https://Stackoverflow.com/users/588229",
"pm_score": 0,
"selected": false,
"text": "<p>In order to have the file be ANSI/UTF-8 </p>\n\n<p>alter the sp_send_dbmail that lives in the <code>msdb</code> with this line along with the other variables: <code>@ANSI_Attachment BIT = 0</code>\ni.e. </p>\n\n<pre><code>@mailitem_id INT = NULL OUTPUT,\n @ANSI_Attachment BIT = 0\n WITH EXECUTE AS 'dbo'\n</code></pre>\n\n<p>and then add this line to your call to sp_send_dbmail:</p>\n\n<pre><code>@ansi_attachment = 1\n</code></pre>\n\n<p>then it should give you an ansi attachment instead of unicode.</p>\n"
},
{
"answer_id": 14670451,
"author": "Gena",
"author_id": 2036703,
"author_profile": "https://Stackoverflow.com/users/2036703",
"pm_score": 4,
"selected": false,
"text": "<p>After some research on SQL Server 2008 R2:</p>\n\n<ol>\n<li><p>Add to <code>sp_send_dbmail</code>:</p>\n\n<pre><code>@ANSI_Attachment BIT = 0\nWITH EXECUTE AS 'dbo'\n</code></pre></li>\n<li><p>Replace</p>\n\n<pre><code>IF(@AttachmentsExist = 1)\n BEGIN\n.......\n END\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>IF(@AttachmentsExist = 1)\nBEGIN\n if (@ANSI_Attachment = 1) \n begin\n --Copy temp attachments to sysmail_attachments \n INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)\n SELECT @mailitem_id, filename, filesize, \n convert(varbinary(max), \n substring( -- remove BOM mark from unicode\n convert(varchar(max), CONVERT (nvarchar(max), attachment)), \n 2, DATALENGTH(attachment)/2\n )\n )\n\n FROM sysmail_attachments_transfer\n WHERE uid = @temp_table_uid\n end else begin\n --Copy temp attachments to sysmail_attachments \n INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)\n SELECT @mailitem_id, filename, filesize, attachment\n FROM sysmail_attachments_transfer\n WHERE uid = @temp_table_uid\n end\nEND\n</code></pre></li>\n</ol>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am using sp\_send\_dbmail in SQL2005 to send an email with the results in an attachment. When the attachment is sent it is UCS-2 Encoded, I want it to be ANSI or UTF-8.
Here is the SQL
```
EXEC msdb.dbo.sp_send_dbmail
@recipients = '[email protected]'
, @query = 'DECLARE @string_to_trim varchar(60);SET @string_to_trim = ''1234''; select rtrim(@string_to_trim), ''tom'''
, @query_result_header=0
, @subject = 'see attach'
, @body= 'temp body'
, @profile_name= N'wksql01tAdmin'
, @body_format = 'HTML'
,@query_result_separator = ','
,@query_attachment_filename = 'results.csv'
,@query_no_truncate = '0'
,@attach_query_result_as_file = 1
```
I have seen some comments on the internet that this is fixed with sql2005 SP2, but do not find it to be the case. | I think the only way to get around what you are seeing is to use BCP to dump the data to a flat file and then attach that file. Sorry I couldn't be more help. :( |
42,710 | <p>I need to implement a 4-to-1 function in Veriog. The input is 4 bits, a number from 0-15. The output is a single bit, 0 or 1. Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not. I want vcs to successfully optimizing the code and also have it be as short/neat as possible. My solution so far:</p>
<pre><code>wire [3:0] a;
wire b;
wire [15:0] c;
assign c = 16'b0100110010111010; //for example but could be any constant
assign b = c[a];
</code></pre>
<p>Having to declare c is ugly and I don't know if vcs will recognize the K-map there. Will this work as well as a case statement or an assignment in conjunctive normal form?</p>
| [
{
"answer_id": 43143,
"author": "DMC",
"author_id": 3148,
"author_profile": "https://Stackoverflow.com/users/3148",
"pm_score": 2,
"selected": false,
"text": "<p>My preference - if it makes sense for your problem - is for a case statement that makes use of enums or `defines. Anything to make code review, maintenance and verification easier.</p>\n"
},
{
"answer_id": 43730,
"author": "Marty",
"author_id": 4131,
"author_profile": "https://Stackoverflow.com/users/4131",
"pm_score": 2,
"selected": false,
"text": "<p>I totally agree with Dallas. Use a case statement - it makes your intent clearer. The synthesis tool will build it as a look-up table (if it's parallel) and will optimise whatever it can.</p>\n\n<p>Also, I wouldn't worry so much about keeping your RTL code short. I'd shoot for clarity first. Synthesis tools are cleverer than you think...</p>\n"
},
{
"answer_id": 67913,
"author": "bengineerd",
"author_id": 10428,
"author_profile": "https://Stackoverflow.com/users/10428",
"pm_score": 4,
"selected": true,
"text": "<p>What you have is fine. A case statement would also work equally well. It's just a matter of how expressive you wish to be. </p>\n\n<p>Your solution, indexing, works fine if the select encodings don't have any special meaning (a memory address selector for example). If the select encodings do have some special semantic meaning to you the designer (and there aren't too many of them), then go with a case statement and enums.</p>\n\n<p>Synthesis wise, it doesn't matter which one you use. Any decent synthesis tool will produce the same result.</p>\n"
},
{
"answer_id": 99795,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 2,
"selected": false,
"text": "<p>For things like this, RTL clarity trumps all by a wide margin. SystemVerilog has special always block directives to make it clear when the block should synthesize to combinational logic, latches, or flops (and your synthesis tool should throw an error if you've written RTL that conflicts with that (e.g. not including all signals in the sensitivity list of an always block). Also be aware that the tool will probably replace whatever encoding you have with the most hardware-efficient encoding (the one that minimizes the area of your total design), unless the encoding itself propagates out to the pins of your top-level module.</p>\n\n<p>This advice goes in general, as well. Make your code easy to understand by humans, and it will probably be more understandable to the synthesis tool as well, which allows it to more effectively bring literally <i>thousands</i> of man-years of algorithms research to bear on your RTL.</p>\n\n<p>You can also code it using ternary operators if you like, but i'd prefer something like:</p>\n\n<pre><code>always_comb //or \"always @*\" if you don't have an SV-enabled tool flow\nbegin \n case(a)\n begin\n 4'b0000: b = 1'b0;\n 4'b0001: b = 1'b1;\n ...\n 4'b1111: b = 1'b0;\n //If you don't specify a \"default\" clause, your synthesis tool\n //Should scream at you if you didn't specify all cases,\n //Which is a good thing (tm)\n endcase //a\nend //always\n</code></pre>\n"
},
{
"answer_id": 195772,
"author": "Eyal",
"author_id": 4454,
"author_profile": "https://Stackoverflow.com/users/4454",
"pm_score": 1,
"selected": false,
"text": "<p>Apparently I am using a lousy synthesis tool. :-) I just synthesized both versions (just the module using a model based on fan-outs for wire delays) and the indexing version from the question gave better timing and area results than the case statements. Using Synopsys DC Z-2007.03-SP.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4454/"
] | I need to implement a 4-to-1 function in Veriog. The input is 4 bits, a number from 0-15. The output is a single bit, 0 or 1. Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not. I want vcs to successfully optimizing the code and also have it be as short/neat as possible. My solution so far:
```
wire [3:0] a;
wire b;
wire [15:0] c;
assign c = 16'b0100110010111010; //for example but could be any constant
assign b = c[a];
```
Having to declare c is ugly and I don't know if vcs will recognize the K-map there. Will this work as well as a case statement or an assignment in conjunctive normal form? | What you have is fine. A case statement would also work equally well. It's just a matter of how expressive you wish to be.
Your solution, indexing, works fine if the select encodings don't have any special meaning (a memory address selector for example). If the select encodings do have some special semantic meaning to you the designer (and there aren't too many of them), then go with a case statement and enums.
Synthesis wise, it doesn't matter which one you use. Any decent synthesis tool will produce the same result. |
42,762 | <p>Here is some code I could not get to format properly in markdown, this is straight C code, pasted into the text box with the '4 spaces' format to denote code:</p>
<pre><code>#define PRINT(x, format, ...) \
if ( x ) { \
if ( debug_fd != NULL ) { \
fprintf(debug_fd, format, ##__VA_ARGS__); \
} \
else { \
fprintf(stdout, format, ##__VA_ARGS__); \
} \
}
</code></pre>
<p>It seems as though the '\' causes the newlines to be ignored. Ok fine, I am used to this in bash, but if I put '\' the second one doesn't show up. As if the second one is absorbed. Am I missing something?</p>
| [
{
"answer_id": 42764,
"author": "Julio César",
"author_id": 2148,
"author_profile": "https://Stackoverflow.com/users/2148",
"pm_score": 2,
"selected": false,
"text": "<p>Add at least four spaces or a hard tab before each line of the code. Like this:</p>\n\n<pre><code>#define PRINT(x, format, ...) \\\nif ( x ) { \\\n if ( debug_fd != NULL ) { \\\n fprintf(debug_fd, format, ##VA_ARGS); \\\n} \\\nelse { \\\n fprintf(stdout, format, ##VA_ARGS); \\\n} \\\n}\n</code></pre>\n"
},
{
"answer_id": 42767,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "<pre><code>#define PRINT(x, format, ...)\nif ( x ) \n{\n if ( debug_fd != NULL ) \n { \n fprintf(debug_fd, format, ##VA_ARGS); \n } \n else \n { \n fprintf(stdout, format, ##VA_ARGS); \n } \n}\n</code></pre>\n"
},
{
"answer_id": 42776,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 3,
"selected": true,
"text": "<p>You can also use the HTML tags <pre><code> in succession. I find this easier for pasting code into the window.</p>\n\n<p><pre><code>#define PRINT(x, format, ...)\nif ( x ) \n{\n if ( debug_fd != NULL ) \n { \n fprintf(debug_fd, format, ##VA_ARGS); \n } \n else \n { \n fprintf(stdout, format, ##VA_ARGS); \n } \n}</pre></code></p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3663/"
] | Here is some code I could not get to format properly in markdown, this is straight C code, pasted into the text box with the '4 spaces' format to denote code:
```
#define PRINT(x, format, ...) \
if ( x ) { \
if ( debug_fd != NULL ) { \
fprintf(debug_fd, format, ##__VA_ARGS__); \
} \
else { \
fprintf(stdout, format, ##__VA_ARGS__); \
} \
}
```
It seems as though the '\' causes the newlines to be ignored. Ok fine, I am used to this in bash, but if I put '\' the second one doesn't show up. As if the second one is absorbed. Am I missing something? | You can also use the HTML tags <pre><code> in succession. I find this easier for pasting code into the window.
```
#define PRINT(x, format, ...)
if ( x )
{
if ( debug_fd != NULL )
{
fprintf(debug_fd, format, ##VA_ARGS);
}
else
{
fprintf(stdout, format, ##VA_ARGS);
}
}
``` |
42,774 | <p>I'm using <kbd>Ctrl</kbd>+<kbd>Left</kbd> / <kbd>Ctrl</kbd>+<kbd>Right</kbd> in a GreaseMonkey script as a hotkey to turn back / forward pages. It seems to works fine, but I want to disable this behavior if I'm in a text edit area. I'm trying to use document.activeElement to get the page active element and test if it's an editable area, but it always returns "undefined".</p>
| [
{
"answer_id": 42807,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": true,
"text": "<p>document.activeElement works for me in FF3 but the following also works</p>\n\n<pre><code>(function() {\n\nvar myActiveElement;\ndocument.onkeypress = function(event) {\n if ((myActiveElement || document.activeElement || {}).tagName != 'INPUT')\n // do your magic\n};\nif (!document.activeElement) {\n var elements = document.getElementsByTagName('input');\n for(var i=0; i<elements.length; i++) {\n elements[i].addEventListener('focus',function() {\n myActiveElement = this;\n },false);\n elements[i].addEventListener('blur',function() {\n myActiveElement = null;\n },false);\n }\n}\n\n})();\n</code></pre>\n"
},
{
"answer_id": 409951,
"author": "thesmart",
"author_id": 20176,
"author_profile": "https://Stackoverflow.com/users/20176",
"pm_score": 0,
"selected": false,
"text": "<p>element.activeElement is part of HTML5 spec but is not supported by most browsers. It was first introduced by IE.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394/"
] | I'm using `Ctrl`+`Left` / `Ctrl`+`Right` in a GreaseMonkey script as a hotkey to turn back / forward pages. It seems to works fine, but I want to disable this behavior if I'm in a text edit area. I'm trying to use document.activeElement to get the page active element and test if it's an editable area, but it always returns "undefined". | document.activeElement works for me in FF3 but the following also works
```
(function() {
var myActiveElement;
document.onkeypress = function(event) {
if ((myActiveElement || document.activeElement || {}).tagName != 'INPUT')
// do your magic
};
if (!document.activeElement) {
var elements = document.getElementsByTagName('input');
for(var i=0; i<elements.length; i++) {
elements[i].addEventListener('focus',function() {
myActiveElement = this;
},false);
elements[i].addEventListener('blur',function() {
myActiveElement = null;
},false);
}
}
})();
``` |
42,793 | <p>What techniques do you know\use to create user-friendly GUI ? </p>
<p>I can name following techniques that I find especially useful: </p>
<ul>
<li>Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area)</li>
<li>Absence of "Save" button<br>
MS OneNote as an example.<br>
IM clients can save conversation history automatically</li>
<li>Integrated search<br>
Search not only through help files but rather make UI elements searchable.<br>
Vista made a good step toward such GUI.<br>
<a href="http://www.istartedsomething.com/20070124/scout-office-2007/" rel="nofollow noreferrer">Scout</a> addin Microsoft Office was a really great idea.</li>
<li>Context oriented UI (Ribbon bar in MS Office 2007)</li>
</ul>
<p>Do you implement something like listed techniques in your software?</p>
<p><strong>Edit:</strong><br>
As <a href="https://stackoverflow.com/questions/42793/gui-design-techinques-to-enhance-user-experience#42843">Ryan P</a> mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations.</p>
| [
{
"answer_id": 42843,
"author": "Ryan P",
"author_id": 1539,
"author_profile": "https://Stackoverflow.com/users/1539",
"pm_score": 0,
"selected": false,
"text": "<p>The best technique I found is to put your self in the users shoes. What would you like to see from the GUI and put that in front. This also gives you the ability to prioritize as those things should be done first then work from there.</p>\n\n<p>To do this I try to find \"layers of usefulness\" and add / subtract from the layers until it seems clean. Basically to find the layers I make a list of all the functions the GUI needs to have, all the functions it should have, and all the functions it would be neat to have. Then I group those so that every thing has logical ordering and the groupings become the \"layers\". From the layers I then add the most important functionality (or what would be used for Day to Day operation) and that becomes the most prominent part, and I work things into the feature around those items.</p>\n\n<p>One of the toughest things is navigation as you have so much to give the use how do you make it helpful and this is where the layers really help. It makes it easy to see how to layout menus, how other pieces interact, what pieces can be hidden, etc. </p>\n\n<p>I have found the easiest way to do this is to start by see what and how your users function on a day to day basis this which will make it easier to get in their shoes (even better is to do their job for a few days). Then make some demonstrations and put them in front of users even if they are Paper Prototypes (there is a book on this process called Paper Prototyping by Carolyn Snyder). Then begin building it and put it in front of users as it is built <em>often</em>. </p>\n\n<p>I will also recommended the book Designing Interfaces by Jenifer Tidwell published by O'Reilly</p>\n"
},
{
"answer_id": 42875,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 0,
"selected": false,
"text": "<p>The items in the list you presented are really situation dependent - they will vary from application to application. Some applications will need a save button, some won't. Some conditions will warrant a modal dialog box, some won't. </p>\n\n<p>My top rule for designing a usable interface: Follow existing UI conventions. Nothing confuses a user more than a UI that doesn't work like anything they've ever used. Lotus Notes has one of the worst user interfaces ever created, and it is almost entirely because they went against common UI conventions with just about everything that they did.</p>\n\n<p>If you're questioning how you should design a certain piece of your UI, think of a few standard/well-known applications that provide similar functionality and see how they do it.</p>\n"
},
{
"answer_id": 42880,
"author": "Rodrick Chapman",
"author_id": 3927,
"author_profile": "https://Stackoverflow.com/users/3927",
"pm_score": 0,
"selected": false,
"text": "<p>If your UI involves data entry or manipulation (typical of business apps) then I recommend affording your users the ability to act on <em>sets</em> of data items as much as possible. Also try to design in such a way that experienced users can interact with the UI in a very random, as opposed to sequential way (accelerator keys, hyperlinks, etc).</p>\n"
},
{
"answer_id": 42891,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 5,
"selected": false,
"text": "<p>If you do give the user a question, don't make it a yes/no question. Take the time to make a new form and put the verbs as choices like in mac. </p>\n\n<p>For example:</p>\n\n<pre><code> Would you like to save? \n Yes No\n</code></pre>\n\n<p>Should Be:</p>\n\n<pre><code> Would you like to save?\n Save Don't Save \n</code></pre>\n\n<p>There is a more detailed explanation <a href=\"http://www.usabilitypost.com/post/11-usability-tip-use-verbs-as-labels-on-buttons\" rel=\"noreferrer\">here.</a></p>\n"
},
{
"answer_id": 42929,
"author": "qwertyuu",
"author_id": 1261,
"author_profile": "https://Stackoverflow.com/users/1261",
"pm_score": 2,
"selected": false,
"text": "<p>If you implement a search, make it a live search like what <a href=\"http://www.locate32.net/\" rel=\"nofollow noreferrer\">Locate32</a> and Google Suggest does now. I am so used to not pressing \"Enter\" at the search box now.</p>\n"
},
{
"answer_id": 42957,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 2,
"selected": false,
"text": "<p>One of the classic books to help you think about design is \"The Design of Everyday Things\" by Donald Norman. He gives great real-world examples. For example, if you design a door well, you should never have to add labels that say \"push\" and \"pull.\" If you want them to pull, put a handle; if you want them to push, put a flat plate. There's no way to do it wrong, and they don't even have to think about it.</p>\n\n<p>This is a good goal: make things obvious. <b>So obvious that it never occurs to the user to do the wrong thing</b>. If there are four knobs on a stove, each one next to an eye, it's obvious that each knob controls the eye it's next to. If the knobs are in a straight line, all on the left side, you have to label them and the user has to stop and think. Bad design. <b>Don't make them think.</b></p>\n\n<p>Another principle: if the user <b>does</b> make a mistake, it should be <b>very easy to undo</b>. Google's image software, Picasa, is a good example. You can crop, recolor, and touch up your photos all you like, and if you ever change your mind - even a month later - you can undo your changes. Even if you explicitly save your changes, Picasa makes a backup. This frees up the user to play and explore, because you're not going to hurt anything.</p>\n"
},
{
"answer_id": 43139,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 5,
"selected": false,
"text": "<p>Check out the great book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0789723107\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Don't make me think</a> by Steve Krug.<br>\nIt's web focused but many of the conepts can apply to anything from blenders to car dashboards.<br>\nTopics covered: </p>\n\n<ul>\n<li>User patterns </li>\n<li>Designing for scanning </li>\n<li>Wise use of copy </li>\n<li>Navigation design </li>\n<li>Home page layout </li>\n<li>Usability testing </li>\n</ul>\n\n<p>He also has a blog called <a href=\"http://www.sensible.com/\" rel=\"nofollow noreferrer\">Advanced Common Sense</a> </p>\n\n<p>And some random UI related links:<br>\n - <a href=\"http://www.joelonsoftware.com/uibook/chapters/fog0000000057.html\" rel=\"nofollow noreferrer\">User Interface Design for Programmers</a> by Joel Spolsky<br>\n - <a href=\"http://www.smashingmagazine.com/2007/09/27/10-usability-nightmares-you-should-be-aware-of/\" rel=\"nofollow noreferrer\">10 Usability Nightmares You Should Be Aware Of\n</a> </p>\n"
},
{
"answer_id": 43348,
"author": "Ced-le-pingouin",
"author_id": 3744,
"author_profile": "https://Stackoverflow.com/users/3744",
"pm_score": 2,
"selected": false,
"text": "<p>Well, one thing that may be obvious: don't change (even slightly) the position, color, font size, etc. of buttons, menus, links, etc. between screens if they do the same type of action.</p>\n"
},
{
"answer_id": 44245,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 1,
"selected": false,
"text": "<p>If you are doing enterprise software, a lot of users will have small monitors at low resolution. Or if they are old they will have it at a low res so they can see giant buttons ( I have seen an 800x600 on a 24\"ish monitor). I have an old 15\" monitor at a low resolution (800 x 600) so i can see what the program will look likes in less than idle conditions every now and then. I know that enterprise users pretty much have to accept what they are given but if you design a winform that doesn't fit into an 800x600 screen, it's not helping anyone.</p>\n"
},
{
"answer_id": 44280,
"author": "Jason Sparks",
"author_id": 512,
"author_profile": "https://Stackoverflow.com/users/512",
"pm_score": 2,
"selected": false,
"text": "<p>I've found <a href=\"http://ui-patterns.com/\" rel=\"nofollow noreferrer\">UI Patterns</a> to be a useful reference for this sort of thing. It's arranged much like the classic GoF Design Patterns book, with each pattern description containing:</p>\n\n<ul>\n<li>The problem the pattern solves</li>\n<li>An example of the pattern in action</li>\n<li>Sample use cases for the pattern</li>\n<li>The solution to implement the pattern</li>\n<li>Rationale for the solution</li>\n</ul>\n"
},
{
"answer_id": 44339,
"author": "Russell Leggett",
"author_id": 2828,
"author_profile": "https://Stackoverflow.com/users/2828",
"pm_score": 2,
"selected": false,
"text": "<p>Really good feedback is extremely important. Even simple things like making it obvious what can and cannot be clicked can be overlooked or too subtle. Feedback when something might happen in the background is great. In gmail, it's great that there's a status ribbon appearing at the top that let's you know if something is sending or loading, but it's even better that it lets you know that something has sent successfully or is <em>still</em> loading.</p>\n\n<p>The \"yellow fade\" technique is something else made popular amongst the RoR crowd that accomplishes something similar. You never want the user to ask the question, \"What just happened?\" or \"What will happen when I do this?\".</p>\n\n<p>Another trick that has become more popular lately that I've been using a lot is editing in place. Instead of having a view of some data with a separate \"edit\" screen (or skipping the view and <em>only</em> having an edit screen), it can often be more user friendly to have a nicely laid out view of some data and just click to edit parts of it. This technique is really only appropriate when reading the data happens more often than editing, and is not appropriate for serious data-entry.</p>\n"
},
{
"answer_id": 74655,
"author": "Mal Ross",
"author_id": 8705,
"author_profile": "https://Stackoverflow.com/users/8705",
"pm_score": 4,
"selected": false,
"text": "<p>To add to your list, aku, I would put <strong>explorability</strong> as one of my highest priorities. Basically, I want the user to feel safe trying out the features. They should never back away from using something for fear that their action might be irreversible. Most commonly, this is implemented using undo/redo commands, but other options are no doubt available e.g. automatic backups.</p>\n\n<p>Also, for applications that are more process-oriented (rather than data-entry applications), I would consider implementing an interface that <em>guide</em> the user a bit more. Microsoft's <a href=\"http://msdn.microsoft.com/en-us/library/ms997506.aspx\" rel=\"nofollow noreferrer\">Inductive User Interface guidelines</a> can help here, although you need to be very careful not to overdo it, as you can easily slow the user down too much.</p>\n\n<p>Finally, as with anything that includes text, make the user interface as scannable as possible. For example, if you have headings under which commands/options appear, consider putting the action word at the start, rather than a question word. The point that Maudite makes is a good example of scannability too, as the \"Don't Save\" button text doesn't rely on the context of the preceding paragraph.</p>\n"
},
{
"answer_id": 184020,
"author": "Ande Turner",
"author_id": 4857,
"author_profile": "https://Stackoverflow.com/users/4857",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n<h2>First Principles: <a href=\"http://www.informatik.uni-trier.de/%7Eley/db/indices/a-tree/h/Hansen:Wilfred_J=.html\" rel=\"nofollow noreferrer\">Wilfred James Hansen</a></h2>\n<ul>\n<li>Know the User</li>\n<li>Minimize Memorization</li>\n<li>Optimize Operations</li>\n<li>Engineer for Errors</li>\n</ul>\n</blockquote>\n<br>\n<blockquote>\n<h2>Subsequent Expansions: <a href=\"http://www.theomandel.com\" rel=\"nofollow noreferrer\">Dr. Theo Mandel</a></h2>\n<h3>Place Users in Control</h3>\n<ul>\n<li>Use Modes Judiciously <strong>(modeless)</strong></li>\n<li>Allow Users to use either the Keyboard or Mouse <strong>(flexible)</strong></li>\n<li>Allow Users to Change Focus <strong>(interruptible)</strong></li>\n<li>Display Descriptive Messages and Text <strong>(helpful)</strong></li>\n<li>Provide Immediate and Reversible Actions, and Feedback <strong>(forgiving)</strong></li>\n<li>Provide meaningful Paths and Exits <strong>(navigable)</strong></li>\n<li>Accommodate Users with Different Skill Levels <strong>(accessible)</strong></li>\n<li>Make the User Interface Transparent <strong>(facilitative)</strong></li>\n<li>Allow Users to Customize the Interface <strong>(preferences)</strong></li>\n<li>Allow Users to Directly Manipulate Interface Objects <strong>(interactive)</strong></li>\n</ul>\n<h3>Reduce Users' Memory Load</h3>\n<ul>\n<li>Relieve Short-term Memory <strong>(remember)</strong></li>\n<li>Rely on Recognition, not Recall <strong>(recognition)</strong></li>\n<li>Provide Visual Cues <strong>(inform)</strong></li>\n<li>Provide Defaults, Undo, and Redo <strong>(forgiving)</strong></li>\n<li>Provide Interface Shortcuts <strong>(frequency)</strong></li>\n<li>Promote an Object-action Syntax <strong>(intuitive)</strong></li>\n<li>Use Real-world Metaphors <strong>(transfer)</strong></li>\n<li>User Progressive Disclosure <strong>(context)</strong></li>\n<li>Promote Visual Clarity <strong>(organize)</strong></li>\n</ul>\n<h3>Make the Interface Consistent</h3>\n<ul>\n<li>Sustain the Context of Users’ Tasks <strong>(continuity)</strong></li>\n<li>Maintain Consistency within and across Products <strong>(experience)</strong></li>\n<li>Keep Interaction Results the Same <strong>(expectations)</strong></li>\n<li>Provide Aesthetic Appeal and Integrity <strong>(attitude)</strong></li>\n<li>Encourage Exploration <strong>(predictable</strong>)</li>\n</ul>\n</blockquote>\n"
},
{
"answer_id": 636066,
"author": "Abdu",
"author_id": 5232,
"author_profile": "https://Stackoverflow.com/users/5232",
"pm_score": 3,
"selected": false,
"text": "<p>A useful technique which I never see anyone use is to add a tooltip for a disabled UI control explaining why the control is disabled. So if there's a listbox which is disabled and it's not clear why it is disabled, I want to hover over it and it tells me why it's disabled. I want to see something like \"It's disabled because two textboxes on the screen were left blank or because I didn't enter enough characters in some field or because I didn't make a certain action.\". </p>\n\n<p>I get into sooooo many such situations and it's frustrating. Sometimes I end up posting in the software's forum asking why a control is greyed out when a tooltip could have helped me in a second! Most of these software have help files which are useless in these kinds of scenarios.</p>\n\n<p>Try to pretend you know nothing about your software and try using it. However this is not practical because you already have a certain mind set towards the app. So watch fellow developers or friends use the app and look out for the pain points and ask for feedback.</p>\n"
},
{
"answer_id": 636088,
"author": "dance2die",
"author_id": 4035,
"author_profile": "https://Stackoverflow.com/users/4035",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.dotnetrocks.com/default.aspx?showNum=338\" rel=\"nofollow noreferrer\">Here</a> is a great DotNetRocks podcast episode where Mark Miller talks about how to create <strong><em>Good UI</em></strong>; Even though the show title is .NET rocks, this episode talks about a general rule of thumbs on how to create a UI to increase program user's productivity.</p>\n\n<p>Here is an episode exerpt</p>\n\n<blockquote>\n <p>Good user interface design can be done by sticking to some good rules and avoiding common mistakes. You don't need to be a latte-sippin tattoo-wearin macbook-carrying designer to create user interfaces that work.</p>\n</blockquote>\n"
},
{
"answer_id": 636113,
"author": "Matthew Dresser",
"author_id": 15613,
"author_profile": "https://Stackoverflow.com/users/15613",
"pm_score": 1,
"selected": false,
"text": "<p>Try to think about your user's end goals first before deciding what individual tasks they would carry out when using your software. The book <a href=\"http://www.cooper.com/insights/books/\" rel=\"nofollow noreferrer\">About Face</a> has excellent discussions on this sort of thing and though quite long is very interesting and insightful. It's interesting to note how many of their suggestions about improving software design seem to used in google docs...</p>\n\n<p>One other thing, keep your user interface as simple and clean as possible. </p>\n"
},
{
"answer_id": 642732,
"author": "elpipo",
"author_id": 77713,
"author_profile": "https://Stackoverflow.com/users/77713",
"pm_score": 0,
"selected": false,
"text": "<p>Sung Meister mentioned Mark Miller. You can find some of his blog posts regarding great UI on the <a href=\"http://community.devexpress.com/search/SearchResults.aspx?q=userid:2151+AND+"great+ui"&o=Relevance\" rel=\"nofollow noreferrer\">Developer express blog</a>. Here's a screencast of his Science of great UI presentation: <a href=\"http://www.veoh.com/browse/videos/category/technology/watch/v6514272kDxJkKgr\" rel=\"nofollow noreferrer\">part1</a> and <a href=\"http://www.veoh.com/browse/videos/category/technology/watch/v6514273ST39Rmd4\" rel=\"nofollow noreferrer\">part2</a>. (both require <a href=\"http://www.veoh.com/download\" rel=\"nofollow noreferrer\">Veoh player</a>).</p>\n\n<p>You can also find him on dnrTV: Science of great user experience: <a href=\"http://www.dnrtv.com/default.aspx?showNum=112\" rel=\"nofollow noreferrer\">part1</a> and <a href=\"http://www.dnrtv.com/default.aspx?showNum=123\" rel=\"nofollow noreferrer\">part2</a>.</p>\n\n<p>Here's a <a href=\"http://video.google.com/videoplay?docid=-6459171443654125383\" rel=\"nofollow noreferrer\">google techtalks about user experience</a> by Jen Fitzpatrick.</p>\n\n<p>Cheers</p>\n"
},
{
"answer_id": 726759,
"author": "Brann",
"author_id": 47341,
"author_profile": "https://Stackoverflow.com/users/47341",
"pm_score": 0,
"selected": false,
"text": "<p><strong>When using a dropdown, the default dropdown height is usually too low</strong> (default is 8 items for winforms, for example).</p>\n\n<p>Increasing it will either save the user a click if the number of items is low or make it easier to search the dropdown if there are a lot of items.</p>\n\n<p>In fact, I see little point in not using all the available space !</p>\n\n<p>This is so obvious to me now, but for example, it seems even VisualStudio designers haven't figured it out (btw, if you manually increase Intellisense's height, it will stay this way, but that's offtopic:))</p>\n"
},
{
"answer_id": 726794,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 0,
"selected": false,
"text": "<p>I'll give one of my personal favorites: avoid dialog boxes at all costs. A truly good U I should almost never need to pop up a dialog box. Add them to your program only as a truly last resort. </p>\n\n<p>For more, you might want to check out <a href=\"https://stackoverflow.com/questions/284906/easily-digestible-ui-tips-for-developers/284933#284933\">easily digestible ui tips for developers</a>. </p>\n"
},
{
"answer_id": 844125,
"author": "thSoft",
"author_id": 90874,
"author_profile": "https://Stackoverflow.com/users/90874",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://codinghorror.com\" rel=\"nofollow noreferrer\">Coding Horror Blog</a> regularly gives great ideas. Just some examples:</p>\n\n<ul>\n<li>Exploratory and incremental learning</li>\n<li>Self-documenting user interface</li>\n<li>Incremental search of features/Smart keyboard access</li>\n<li>Task-oriented design (ribbon instead of menus and toolbars)</li>\n<li>Providing undo instead of constant confirmation</li>\n</ul>\n\n<p>Another aspect: <strong>use scalable icons</strong> to solve the problem of multiple user screen resolutions without maintaining different resolution bitmaps.</p>\n"
},
{
"answer_id": 2767434,
"author": "Zamboni",
"author_id": 174682,
"author_profile": "https://Stackoverflow.com/users/174682",
"pm_score": 1,
"selected": false,
"text": "<p>I like to follow these 3 guidelines:</p>\n\n<ol>\n<li>Standard - follow known standards/patterns, reuse ideas from all products you respect</li>\n<li>Simple - keep your solutions simple and easy to change (if needed)</li>\n<li>Elegant - use less to accomplish more</li>\n</ol>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196/"
] | What techniques do you know\use to create user-friendly GUI ?
I can name following techniques that I find especially useful:
* Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area)
* Absence of "Save" button
MS OneNote as an example.
IM clients can save conversation history automatically
* Integrated search
Search not only through help files but rather make UI elements searchable.
Vista made a good step toward such GUI.
[Scout](http://www.istartedsomething.com/20070124/scout-office-2007/) addin Microsoft Office was a really great idea.
* Context oriented UI (Ribbon bar in MS Office 2007)
Do you implement something like listed techniques in your software?
**Edit:**
As [Ryan P](https://stackoverflow.com/questions/42793/gui-design-techinques-to-enhance-user-experience#42843) mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations. | If you do give the user a question, don't make it a yes/no question. Take the time to make a new form and put the verbs as choices like in mac.
For example:
```
Would you like to save?
Yes No
```
Should Be:
```
Would you like to save?
Save Don't Save
```
There is a more detailed explanation [here.](http://www.usabilitypost.com/post/11-usability-tip-use-verbs-as-labels-on-buttons) |
42,797 | <p>I'm looking for something that can copy (preferably only changed) files from a development machine to a staging machine and finally to a set of production machines.</p>
<p>A "what if" mode would be nice as would the capability to "rollback" the last deployment. Database migrations aren't a necessary feature.</p>
<p>UPDATE: A free/low-cost tool would be great, but cost isn't the only concern. A tool that could actually manage deployment from one environment to the next (dev->staging->production instead of from a development machine to each environment) would also be ideal.</p>
<p>The other big nice-to-have is the ability to only copy changed files - some of our older sites contain hundreds of .asp files.</p>
| [
{
"answer_id": 42811,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p>We used <a href=\"http://www.eworldui.net/unleashit/\" rel=\"nofollow noreferrer\">UnleashIt</a> (unfortunate name I know) which was nicely customizable and allowed you to save profiles for deploying to different servers. It also has a \"backup\" feature which will backup your production files before deployment so rollback should be pretty easy.</p>\n"
},
{
"answer_id": 42839,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 1,
"selected": false,
"text": "<p>You don't specify if you are using Visual Studio .NET, but there are a few built-in tools in Visual Studio 2005 and 2008:</p>\n\n<p>Copy Website tool -- basically a visual synchronization tool, it highlights files and lets you copy from one to the other. Manual, built into Visual Studio.</p>\n\n<p>aspnet_compiler.exe -- lets you precompile websites.</p>\n\n<p>Of course you can create a web deployment package and deploy as an MSI as well.</p>\n\n<p>I have used a combination of Cruise Control.NET, nant and MSBuild to compile, and swap out configuration files for specific environments and copy the files to a build output directory. Then we had another nant script to do the file copying (and run database scripts if necessary).</p>\n\n<p>For a rollback, we would save all prior deployments, so theoretically rolling back just involved redeploying the last working build (and restoring the database).</p>\n"
},
{
"answer_id": 43186,
"author": "DrFloyd5",
"author_id": 1736623,
"author_profile": "https://Stackoverflow.com/users/1736623",
"pm_score": 2,
"selected": false,
"text": "<p><strong>@Sean Carpenter</strong> can you tell us a little more about your environment? Should the solution be free? simple?</p>\n\n<p>I find robocopy to be pretty slick for this sort of thing. Wrap in up in a batch file and you are good to go. It's a glorified xcopy, but deploying my website isn't really hard. Just copy out the files.</p>\n\n<p>As far as rollbacks... You are using source control right? Just pull the old source out of there. Or, in your batch file, ALSO copy the deployment to another folder called website yyyy.mm.dd so you have a lovely folder ready to go in an emergency.</p>\n\n<p>look at the for command for details on how to get the parts of the date.</p>\n\n<pre><code>robocopy.exe\nfor /?\n</code></pre>\n\n<p>Yeah, it's a total \"hack\" but it moves the files nicely.</p>\n"
},
{
"answer_id": 107831,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "<p>For some scenarios I used a <strong>freeware</strong> product called <strong>SyncBack</strong> (<a href=\"http://www.2brightsparks.com/downloads.html#freeware\" rel=\"nofollow noreferrer\">Download here</a>).</p>\n\n<p>It provides complex, multi-step file synchronization (filesystem or FTP etc., compression etc.). The program has a nice graphical user interface. You can define profiles and group/execute them together.</p>\n\n<p>You can set filter on file types, names etc. and execute commands/programs after the job execution. There is also a job log provided as html report, which can be sent as email to you if you schedule the job.</p>\n\n<p>There is also a professional version of the software, but for common tasks the freeware should do fine.</p>\n\n<p><img src=\"https://www.2brightsparks.com/assets/images/syncback/sb-main.jpg\" alt=\"alt text\"></p>\n"
},
{
"answer_id": 380222,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 0,
"selected": false,
"text": "<p>I've given up trying to find a good free product that works.\nI then found Microsoft's Sync Toy 2.0 which while lacking in options works well.</p>\n\n<p>BUT I need to deploy to a remote server.</p>\n\n<p>Since I connect with terminal services I realized I can select my local hard drive when I connect and then in explorer on the remote server i can open <code>\\\\tsclient\\S\\MyWebsite</code> on the remote server.</p>\n\n<p>I then use synctoy with that path and synchronize it with my server. Seems to work pretty well and fast so far...</p>\n"
},
{
"answer_id": 1950857,
"author": "projectshave",
"author_id": 124800,
"author_profile": "https://Stackoverflow.com/users/124800",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe rsync plus some custom scripts will do the trick. </p>\n"
},
{
"answer_id": 2014683,
"author": "januszstabik",
"author_id": 113911,
"author_profile": "https://Stackoverflow.com/users/113911",
"pm_score": 0,
"selected": false,
"text": "<p>Try repliweb. It handles full rollback to previous versions of files. I've used it whilst working for a client who demanded its use and I;ve become a big fan of it, partiularily:</p>\n\n<ul>\n<li>Rollback to previous versions of code</li>\n<li>Authentication and rules for different user roles</li>\n<li>Deploy to multiple environments</li>\n<li>Full reporting to the user via email / logs statiing what has changed, what the current version is etc.</li>\n</ul>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/729/"
] | I'm looking for something that can copy (preferably only changed) files from a development machine to a staging machine and finally to a set of production machines.
A "what if" mode would be nice as would the capability to "rollback" the last deployment. Database migrations aren't a necessary feature.
UPDATE: A free/low-cost tool would be great, but cost isn't the only concern. A tool that could actually manage deployment from one environment to the next (dev->staging->production instead of from a development machine to each environment) would also be ideal.
The other big nice-to-have is the ability to only copy changed files - some of our older sites contain hundreds of .asp files. | **@Sean Carpenter** can you tell us a little more about your environment? Should the solution be free? simple?
I find robocopy to be pretty slick for this sort of thing. Wrap in up in a batch file and you are good to go. It's a glorified xcopy, but deploying my website isn't really hard. Just copy out the files.
As far as rollbacks... You are using source control right? Just pull the old source out of there. Or, in your batch file, ALSO copy the deployment to another folder called website yyyy.mm.dd so you have a lovely folder ready to go in an emergency.
look at the for command for details on how to get the parts of the date.
```
robocopy.exe
for /?
```
Yeah, it's a total "hack" but it moves the files nicely. |
42,814 | <p>How can I get the MAC Address using only the compact framework?</p>
| [
{
"answer_id": 42824,
"author": "Greg Roberts",
"author_id": 4269,
"author_profile": "https://Stackoverflow.com/users/4269",
"pm_score": -1,
"selected": false,
"text": "<p>Add a reference to System.Management.dll and use something like:</p>\n\n<pre><code>Dim mc As System.Management.ManagementClass\nDim mo As ManagementObject\nmc = New ManagementClass(\"Win32_NetworkAdapterConfiguration\")\nDim moc As ManagementObjectCollection = mc.GetInstances()\nFor Each mo In moc\n If mo.Item(\"IPEnabled\") = True Then\n ListBox1.Items.Add(\"MAC address \" & mo.Item(\"MacAddress\").ToString())\n End If\nNext\n</code></pre>\n"
},
{
"answer_id": 42827,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>Here are the <strong>first three hits</strong> from a Google search for \"MAC address in Compact Framework:</p>\n\n<ol>\n<li><a href=\"http://arjunachith.blogspot.com/2007/08/retrieving-mac-address-in-compact.html\" rel=\"nofollow noreferrer\">http://arjunachith.blogspot.com/2007/08/retrieving-mac-address-in-compact.html</a></li>\n<li><a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=920417&SiteID=1\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=920417&SiteID=1</a></li>\n<li><a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=188787&SiteID=1\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=188787&SiteID=1</a></li>\n</ol>\n\n<p>Did none of those help?</p>\n\n<p>Two out of three point to <a href=\"http://www.opennetcf.com/\" rel=\"nofollow noreferrer\">OpenNETCF</a> as a way to do it.</p>\n"
},
{
"answer_id": 47574,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 3,
"selected": false,
"text": "<p>1.4 of the OpenNETCF code gets the information from the following P/Invoke call:</p>\n\n<pre><code> [DllImport (\"iphlpapi.dll\", SetLastError=true)]\n public static extern int GetAdaptersInfo( byte[] ip, ref int size );\n</code></pre>\n\n<p>The physical address (returned as MAC address) I think is around about index 400 - 408 of the byte array after the call. So you can just use that directly if you don't want to use OpenNETCF (why though? OpenNETCF rocks more than stone henge!)</p>\n\n<p>Wonderful P/Invoke.net gives a full example <a href=\"http://www.pinvoke.net/default.aspx/iphlpapi/GetAdaptersInfo.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Oh and to properly answer your question:</p>\n\n<blockquote>\n <p>only using the Compact Framework</p>\n</blockquote>\n\n<p>You cant. That's life with CF, if you want some fun try sending data with a socket synchronously with a timeout. :D</p>\n"
},
{
"answer_id": 424238,
"author": "castle1971",
"author_id": 36728,
"author_profile": "https://Stackoverflow.com/users/36728",
"pm_score": 0,
"selected": false,
"text": "<p>If you can access the registry, try to find your adapter MAC Address under the <code>LOCAL_MACHINE\\Comm\\PCI\\***\\Parms\\MacAddress</code>. </p>\n\n<p>It may be a quick and dirty solution that doesn't involve the use of WMI or OpenNETCF ...</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4463/"
] | How can I get the MAC Address using only the compact framework? | 1.4 of the OpenNETCF code gets the information from the following P/Invoke call:
```
[DllImport ("iphlpapi.dll", SetLastError=true)]
public static extern int GetAdaptersInfo( byte[] ip, ref int size );
```
The physical address (returned as MAC address) I think is around about index 400 - 408 of the byte array after the call. So you can just use that directly if you don't want to use OpenNETCF (why though? OpenNETCF rocks more than stone henge!)
Wonderful P/Invoke.net gives a full example [here](http://www.pinvoke.net/default.aspx/iphlpapi/GetAdaptersInfo.html).
Oh and to properly answer your question:
>
> only using the Compact Framework
>
>
>
You cant. That's life with CF, if you want some fun try sending data with a socket synchronously with a timeout. :D |
42,830 | <p>I'm using the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow noreferrer">AutoComplete</a> control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox. </p>
<p>I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click. </p>
<p>Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.</p>
| [
{
"answer_id": 42858,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 3,
"selected": true,
"text": "<p>We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox. You can have a look at the (terribly hacky) solution here: <a href=\"http://www.drive.com.au\" rel=\"nofollow noreferrer\">http://www.drive.com.au</a> </p>\n\n<p>The textbox id is <code>MainSearchBox_SearchTextBox</code>. Have a look at about line 586 & you can see where I'm wiring up all the events (I'm actually using prototype for this bit.</p>\n\n<p>Basically on the focus event of the textbox I set a global var called <code>textBoxHasFocus</code> to true and on the blur event I set it to false. The on the load event of the page I call this script:</p>\n\n<pre><code>if (textBoxHasFocus) {\n $get(\"MainSearchBox_SearchTextBox\").blur();\n $get(\"MainSearchBox_SearchTextBox\").focus();\n} \n</code></pre>\n\n<p>This resets the textbox. It's really dodgy, but it's the only solution I could find</p>\n"
},
{
"answer_id": 44006,
"author": "Jason Shoulders",
"author_id": 1953,
"author_profile": "https://Stackoverflow.com/users/1953",
"pm_score": 0,
"selected": false,
"text": "<p>How are you setting focus? I haven't tried the specific scenario you've suggested, but here's how I set focus to my controls:</p>\n\n<pre><code>Public Sub SetFocus(ByVal ctrl As Control)\n Dim sb As New System.Text.StringBuilder\n Dim p As Control\n p = ctrl.Parent\n While (Not (p.GetType() Is GetType(System.Web.UI.HtmlControls.HtmlForm)))\n p = p.Parent\n End While\n With sb\n .Append(\"<script language='JavaScript'>\")\n .Append(\"function SetFocus()\")\n .Append(\"{\")\n .Append(\"document.\")\n .Append(p.ClientID)\n .Append(\"['\")\n .Append(ctrl.UniqueID)\n .Append(\"'].focus();\")\n .Append(\"}\")\n .Append(\"window.onload = SetFocus;\")\n .Append(\"\")\n .Append(\"</script\")\n .Append(\">\")\n End With\n ctrl.Page.RegisterClientScriptBlock(\"SetFocus\", sb.ToString())\nEnd Sub\n</code></pre>\n\n<p>So, I'm not sure what method you're using, but if it's different than mine, give that a shot and see if you still have a problem or not.</p>\n"
},
{
"answer_id": 1059406,
"author": "Kris",
"author_id": 1457761,
"author_profile": "https://Stackoverflow.com/users/1457761",
"pm_score": 0,
"selected": false,
"text": "<p>What I normally do is register a clientside script to run the below setFocusTimeout method from my codebehind method. When this runs, it waits some small amount of time and then calls the method that actually sets focus (setFocus). It's terribly hackish, but it seems you have to go a route like this to stop AJAX from stealing your focus. </p>\n\n<pre><code>function setFocusTimeout(controlID) {\n focusControlID = controlID;\n setTimeout(\"setFocus(focusControlID)\", 100);\n}\n\nfunction setFocus() {\n document.getElementById(focusControlID).focus();\n}\n</code></pre>\n"
},
{
"answer_id": 2501610,
"author": "Nathan Poorman",
"author_id": 300096,
"author_profile": "https://Stackoverflow.com/users/300096",
"pm_score": 0,
"selected": false,
"text": "<p>I found the answers from Glenn Slaven and from Kris/Alex to get me closer to a solution to my particular problem with setting focus on an ASP.NET TextBox control that had an AutoCompleteExtender attached. The document.getElementById(focusControlID).focus() kept throwing a javascript error that implied document.getElementById was returning a null object. The focusControlID variable was returning the correct runtime ClientID value for the TextBox control. But for whatever reason, the document.getElementById function didn't like it.</p>\n\n<p>My solution was to throw jQuery into the mix, as I was already using it to paint the background of any control that had focus, plus forcing the Enter key to tab through the form instead of firing a postback. </p>\n\n<p>My setFocus function ended up looking like this:</p>\n\n<pre><code>function setFocus(focusControlID) {\n $('#' + focusControlID).blur();\n $('#' + focusControlID).focus();\n}\n</code></pre>\n\n<p>This got rid of the javascript runtime error, put focus on the desired TextBox control, and placed the cursor within the control as well. Without first blurring then focusing, the control would be highlighted as if it had focus, but the cursor would not be sitting in the control yet. The user would still have to click inside the control to begin editing, which would be an UX annoyance.</p>\n\n<p>I also had to increase the timeout from 100 to 300. Your mileage my vary...</p>\n\n<p>I agree with everyone that this is a hack. But from the end-user's perspective, they don't see this code. The hack for them is if they have to manually click inside the control instead of just being automatically placed inside the control already and typing the first few letters to trigger the auto lookup functionality. So, hats off to all who provided their hacks.</p>\n\n<p>I hope this is helpful to someone else.</p>\n"
},
{
"answer_id": 8703236,
"author": "paritosh",
"author_id": 1126540,
"author_profile": "https://Stackoverflow.com/users/1126540",
"pm_score": 1,
"selected": false,
"text": "<p>this is waste , its simple </p>\n\n<p>this is what you need to do </p>\n\n<p>controlId.focus(); in C#\ncontrolID.focus() in VB </p>\n\n<p>place this in page load or button_click section </p>\n\n<p>eg. panel1.focus(); if panel1 has model popup extender attached to it, then we put this code in page load section </p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
] | I'm using the [AutoComplete](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx) control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox.
I've tried setting the focus in the Page\_Load, Page\_PreRender, and Page\_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click.
Is there a special place I need to set the focus or something else I need to do to make this work? Thanks. | We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox. You can have a look at the (terribly hacky) solution here: <http://www.drive.com.au>
The textbox id is `MainSearchBox_SearchTextBox`. Have a look at about line 586 & you can see where I'm wiring up all the events (I'm actually using prototype for this bit.
Basically on the focus event of the textbox I set a global var called `textBoxHasFocus` to true and on the blur event I set it to false. The on the load event of the page I call this script:
```
if (textBoxHasFocus) {
$get("MainSearchBox_SearchTextBox").blur();
$get("MainSearchBox_SearchTextBox").focus();
}
```
This resets the textbox. It's really dodgy, but it's the only solution I could find |
42,833 | <p>In the web-application I'm developing I currently use a naive solution when connecting to the database:</p>
<pre><code>Connection c = DriverManager.getConnection("url", "username", "password");
</code></pre>
<p>This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?</p>
| [
{
"answer_id": 42838,
"author": "Julio César",
"author_id": 2148,
"author_profile": "https://Stackoverflow.com/users/2148",
"pm_score": 5,
"selected": true,
"text": "<p>You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:</p>\n\n<p><a href=\"http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html\" rel=\"noreferrer\">http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html</a></p>\n"
},
{
"answer_id": 42841,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>I can recommend these techniques for .NET programmers: </p>\n\n<ul>\n<li>Encrypt password\\connection string in config file</li>\n<li>Setup trusted connection between client and server (i.e. use windows auth, etc)</li>\n</ul>\n\n<p>Here is useful articles from CodeProject: </p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/cs/Configuration_File.aspx\" rel=\"nofollow noreferrer\">Encrypt and Decrypt of ConnectionString in app.config and/or web.config</a></li>\n</ul>\n"
},
{
"answer_id": 42842,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>In .NET, the convention is to store connectionstrings in a separate config file.</p>\n\n<p>Thereon, the <a href=\"http://odetocode.com/Blogs/scott/archive/2006/01/08/2707.aspx\" rel=\"nofollow noreferrer\">config file can be encrypted</a>.</p>\n\n<p>If you are using Microsoft SQL Server, this all becomes irrelevant if you use a domain account to run the application, which then uses a trusted connection to the database. The connectionstring will not contain any usernames and passwords in that case.</p>\n"
},
{
"answer_id": 42862,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 1,
"selected": false,
"text": "<p>Unless I am missing the point the connection should be managed by the server via a connection pool, therefore the connection credentials are held by the server and not by the app. </p>\n\n<p>Taking this further I generally build to a convention where the frontend web application (in a DMZ) only talks to the DB via a web service (in domain), therefore providing complete separation and enhanced DB security. </p>\n\n<p>Also, never give priviliges to the db account over or above what is essentially needed.</p>\n\n<p>An alternative approach is to perform all operations via stored procedures, and grant the application user access only to these procs.</p>\n"
},
{
"answer_id": 42872,
"author": "Andrew",
"author_id": 4394,
"author_profile": "https://Stackoverflow.com/users/4394",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming that you are using MS SQL, you can take advantage of windows authentication which requires no ussername/pass anywhere in source code. Otherwise I would have to agree with the other posters recommending app.config + encryption.</p>\n"
},
{
"answer_id": 20749831,
"author": "Neil McGuigan",
"author_id": 223478,
"author_profile": "https://Stackoverflow.com/users/223478",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>Create an O/S user</li>\n<li>Put the password in an O/S environment variable for that user</li>\n<li>Run the program as that user</li>\n</ol>\n\n<p>Advantages:</p>\n\n<ol>\n<li>Only root or that user can view that user's O/S environment variables</li>\n<li>Survives reboot</li>\n<li>You never accidentally check password in to source control</li>\n<li>You don't need to worry about screwing up file permissions</li>\n<li>You don't need to worry about where you store an encryption key</li>\n<li>Works x-platform</li>\n</ol>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/42833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4464/"
] | In the web-application I'm developing I currently use a naive solution when connecting to the database:
```
Connection c = DriverManager.getConnection("url", "username", "password");
```
This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode? | You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:
<http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html> |
42,876 | <p>Why does the following code not work as I was expecting?</p>
<pre><code><?php
$data = array(
array('Area1', null, null),
array(null, 'Section1', null),
array(null, null, 'Location1'),
array('Area2', null, null),
array(null, 'Section2', null),
array(null, null, 'Location2')
);
$root = array();
foreach ($data as $row) {
if ($row[0]) {
$area = array();
$root[$row[0]] =& $area;
} elseif ($row[1]) {
$section = array();
$area[$row[1]] =& $section;
} elseif ($row[2]) {
$section[] = $row[2];
}
}
print_r($root);
</code></pre>
<p>Expected result:</p>
<pre><code>Array(
[Area1] => Array(
[Section1] => Array(
[0] => Location1
)
)
[Area2] => Array(
[Section2] => Array(
[0] => Location2
)
)
)
</code></pre>
<p>Actual result:</p>
<pre><code>Array(
[Area1] => Array(
[Section2] => Array(
[0] => Location2
)
)
[Area2] => Array(
[Section2] => Array(
[0] => Location2
)
)
)
</code></pre>
| [
{
"answer_id": 42885,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 3,
"selected": true,
"text": "<p>If you modify your code on two lines as follows:</p>\n\n<pre><code>$area = array();\n\n$section = array();\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>unset($area);\n$area = array();\n\nunset($section);\n$section = array();\n</code></pre>\n\n<p>it will work as expected.</p>\n\n<p>In the first version, <code>$area</code> and <code>$section</code> are acting as \"pointers\" to the value inside the <code>$root</code> array. If you reset the values first, those variables can then be used to create brand new arrays instead of overwriting the previous arrays.</p>\n"
},
{
"answer_id": 42913,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 1,
"selected": false,
"text": "<p>This will also works:</p>\n\n<pre><code>$root[$row[0]] = array();\n$area =& $root[$row[0]];\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/42876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] | Why does the following code not work as I was expecting?
```
<?php
$data = array(
array('Area1', null, null),
array(null, 'Section1', null),
array(null, null, 'Location1'),
array('Area2', null, null),
array(null, 'Section2', null),
array(null, null, 'Location2')
);
$root = array();
foreach ($data as $row) {
if ($row[0]) {
$area = array();
$root[$row[0]] =& $area;
} elseif ($row[1]) {
$section = array();
$area[$row[1]] =& $section;
} elseif ($row[2]) {
$section[] = $row[2];
}
}
print_r($root);
```
Expected result:
```
Array(
[Area1] => Array(
[Section1] => Array(
[0] => Location1
)
)
[Area2] => Array(
[Section2] => Array(
[0] => Location2
)
)
)
```
Actual result:
```
Array(
[Area1] => Array(
[Section2] => Array(
[0] => Location2
)
)
[Area2] => Array(
[Section2] => Array(
[0] => Location2
)
)
)
``` | If you modify your code on two lines as follows:
```
$area = array();
$section = array();
```
to this:
```
unset($area);
$area = array();
unset($section);
$section = array();
```
it will work as expected.
In the first version, `$area` and `$section` are acting as "pointers" to the value inside the `$root` array. If you reset the values first, those variables can then be used to create brand new arrays instead of overwriting the previous arrays. |
42,934 | <p>It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately. I've mostly only worked in compiled, static typed languages (C, Java, .Net). The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP. Using these technologies has left a bad taste in my mouth when thinking about dynamic languages. Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime. And even then, you may not notice an error, as it just creates a new variable, and assigns some default value. I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type.</p>
<p>What I want to know is, what people find so appealing about dynamic languages? What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages. It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code? And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago?</p>
| [
{
"answer_id": 42945,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 2,
"selected": false,
"text": "<p>The argument is more complex than this (read <a href=\"http://steve.yegge.googlepages.com/is-weak-typing-strong-enough\" rel=\"nofollow noreferrer\">Yegge's article \"Is Weak Typing Strong Enough\"</a> for an interesting overview).</p>\n\n<p>Dynamic languages don't necessarily lack error checking either - C#'s type inference is possibly one example. In the same way, C and C++ have terrible compile checks and they are statically typed.</p>\n\n<p>The main advantages of dynamic languages are a) capability (which doesn't necessarily have to be used all the time) and b) <a href=\"http://www.codinghorror.com/blog/archives/000788.html\" rel=\"nofollow noreferrer\">Boyd's Law of Iteration</a>.</p>\n\n<p>The latter reason is massive.</p>\n"
},
{
"answer_id": 42949,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": false,
"text": "<p>Although I'm not a big fan of Ruby yet, I find dynamic languages to be really wonderful and powerful tools.</p>\n\n<p>The idea that there is no type checking and variable declaration is not too big an issue really. Admittedly, you can't catch these errors until run time, but for experienced developers this is not really an issue, and when you do make mistakes, they're usually easily fixed. </p>\n\n<p>It also forces novices to read what they're writing more carefully. I know learning PHP taught me to be more attentive to what I was actually typing, which has improved my programming even in compiled languages.</p>\n\n<p>Good IDEs will give enough intellisense for you to know whether a variable has been \"declared\" and they also try to do some type inference for you so that you can tell what a variable is.</p>\n\n<p>The power of what can be done with dynamic languages is really what makes them so much fun to work with in my opinion. Sure, you could do the same things in a compiled language, but it would take more code. Languages like Python and PHP let you develop in less time and get a functional codebase faster most of the time.</p>\n\n<p>And for the record, I'm a full-time .NET developer, and I love compiled languages. I only use dynamic languages in my free time to learn more about them and better myself as a developer..</p>\n"
},
{
"answer_id": 42951,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 4,
"selected": false,
"text": "<p>Your arguments against dynamic languages are perfectly valid. However, consider the following:</p>\n\n<ol>\n<li><strong>Dynamic languages don't need to be compiled</strong>: just run them. You can even reload the files at run time without restarting the application in most cases.</li>\n<li><strong>Dynamic languages are generally less verbose and more readable</strong>: have you ever looked at a given algorithm or program implemented in a static language, then compared it to the Ruby or Python equivalent? In general, you're looking at a reduction in lines of code by a factor of 3. A lot of scaffolding code is unnecessary in dynamic languages, and that means the end result is more readable and more focused on the actual problem at hand.</li>\n<li><strong>Don't worry about typing issues</strong>: the general approach when programming in dynamic languages is not to worry about typing: most of the time, the right kind of argument will be passed to your methods. And once in a while, someone may use a different kind of argument that just happens to work as well. When things go wrong, your program may be stopped, but this rarely happens if you've done a few tests.</li>\n</ol>\n\n<p>I too found it a bit scary to step away from the safe world of static typing at first, but for me the advantages by far outweigh the disadvantages, and I've never looked back.</p>\n"
},
{
"answer_id": 42955,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 7,
"selected": false,
"text": "<p>I think the reason is that people are used to statically typed languages that have very limited and inexpressive type systems. These are languages like Java, C++, Pascal, etc. Instead of going in the direction of more expressive type systems and better type inference, (as in Haskell, for example, and even SQL to some extent), some people like to just keep all the \"type\" information in their head (and in their tests) and do away with static typechecking altogether.</p>\n\n<p>What this buys you in the end is unclear. There are many misconceived notions about typechecking, the ones I most commonly come across are these two.</p>\n\n<p><strong>Fallacy: Dynamic languages are less verbose.</strong> The misconception is that type information equals type annotation. This is totally untrue. We all know that type annotation is annoying. The machine should be able to figure that stuff out. And in fact, it does in modern compilers. Here is a statically typed QuickSort in two lines of Haskell (from <a href=\"http://haskell.org\" rel=\"nofollow noreferrer\">haskell.org</a>):</p>\n\n<pre><code>qsort [] = []\nqsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)\n</code></pre>\n\n<p>And here is a dynamically typed QuickSort in LISP (from <a href=\"http://swisspig.net/r/post/blog-200603301157\" rel=\"nofollow noreferrer\">swisspig.net</a>):</p>\n\n<pre><code>(defun quicksort (lis) (if (null lis) nil\n (let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x))))\n (append (quicksort (remove-if-not fn r)) (list x)\n (quicksort (remove-if fn r))))))\n</code></pre>\n\n<p>The Haskell example falsifies the hypothesis <em>statically typed, therefore verbose</em>. The LISP example falsifies the hypothesis <em>verbose, therefore statically typed</em>. There is no implication in either direction between typing and verbosity. You can safely put that out of your mind.</p>\n\n<p><strong>Fallacy: Statically typed languages have to be compiled, not interpreted.</strong> Again, not true. Many statically typed languages have interpreters. There's the Scala interpreter, The GHCi and Hugs interpreters for Haskell, and of course SQL has been both statically typed and interpreted for longer than I've been alive.</p>\n\n<p>You know, maybe the dynamic crowd just wants freedom to not have to think as carefully about what they're doing. The software might not be correct or robust, but maybe it doesn't have to be.</p>\n\n<p>Personally, I think that those who would give up type safety to purchase a little temporary liberty, deserve neither liberty nor type safety.</p>\n"
},
{
"answer_id": 42961,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 3,
"selected": false,
"text": "<p>My appreciation for dynamic languages is very much tied to how <strong>functional</strong> they are. Python's list comprehensions, Ruby's closures, and JavaScript's prototyped objects are all very appealing facets of those languages. All also feature first-class functions--something I can't see living without ever again.</p>\n\n<p>I wouldn't categorize PHP and VB (script) in the same way. To me, those are mostly imperative languages with all of the dynamic-typing drawbacks that you suggest.</p>\n\n<p>Sure, you don't get the same level of compile-time checks (since there ain't a compile time), but I would expect static syntax-checking tools to evolve over time to at least partially address that issue.</p>\n"
},
{
"answer_id": 42977,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "<p>One of the advantages pointed out for dynamic languages is to just be able to change the code and continue running. No need to recompile. In VS.Net 2008, when debugging, you can actually change the code, and continue running, without a recompile. With advances in compilers and IDEs, is it possible that this and other advantages of using dynamic languages will go away.</p>\n"
},
{
"answer_id": 42978,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": false,
"text": "<p>VBScript sucks, unless you're comparing it to another flavor of VB.\nPHP is ok, so long as you keep in mind that it's an overgrown templating language.\nModern Javascript is great. Really. Tons of fun. Just stay away from any scripts tagged \"DHTML\". </p>\n\n<p>I've never used a language that didn't allow runtime errors. IMHO, that's largely a red-herring: compilers don't catch all typos, nor do they validate intent. Explicit typing is great when you need explicit types, but most of the time, you don't. Search for the questions here on <code>generics</code> or the one about whether or not using unsigned types was a good choice for index variables - much of the time, this stuff just gets in the way, and gives folks knobs to twiddle when they have time on their hands. </p>\n\n<p>But, i haven't really answered your question. Why are dynamic languages appealing? Because after a while, writing code gets dull and you just want to implement the algorithm. You've already sat and worked it all out in pen, diagrammed potential problem scenarios and proved them solvable, and the only thing left to do is code up the twenty lines of implementation... and two hundred lines of boilerplate to make it compile. Then you realize that the type system you work with doesn't reflect what you're actually doing, but someone else's ultra-abstract idea of what you <em>might</em> be doing, and you've long ago abandoned programming for a life of knicknack tweaking so obsessive-compulsive that it would shame even fictional detective Adrian Monk. </p>\n\n<p>That's when you <strike>go get plastered</strike> start looking seriously at dynamic languages.</p>\n"
},
{
"answer_id": 43043,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 3,
"selected": false,
"text": "<p>Personally, I think it's just that most of the \"dynamic\" languages you have used just happen to be poor examples of languages in general.</p>\n\n<p>I am <em>way</em> more productive in Python than in C or Java, and not just because you have to do the edit-compile-link-run dance. I'm getting more productive in Objective-C, but that's probably more due to the framework.</p>\n\n<p>Needless to say, I am more productive in any of these languages than PHP. Hell, I'd rather code in Scheme or Prolog than PHP. (But lately I've actually been doing more Prolog than anything else, so take that with a grain of salt!)</p>\n"
},
{
"answer_id": 43054,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 4,
"selected": false,
"text": "<p>I am a full-time .Net programmer fully entrenched in the throes of statically-typed C#. However, I love modern JavaScript. </p>\n\n<p>Generally speaking, I think dynamic languages allow you to express your <em>intent</em> more succinctly than statically typed languages as you spend less time and space defining what the building blocks are of what you are trying to express when in many cases they are self evident. </p>\n\n<p>I think there are multiple classes of dynamic languages, too. I have no desire to go back to writing classic ASP pages in VBScript. To be useful, I think a dynamic language needs to support some sort of collection, list or associative construct at its core so that objects (or what pass for objects) can be expressed and allow you to build more complex constructs. (Maybe we should all just code in LISP ... it's a joke ...) </p>\n\n<p>I think in .Net circles, dynamic languages get a bad rap because they are associated with VBScript and/or JavaScript. VBScript is just a recalled as a nightmare for many of the reasons Kibbee stated -- anybody remember enforcing type in VBScript using CLng to make sure you got enough bits for a 32-bit integer. Also, I think JavaScript is still viewed as the browser language for drop-down menus that is written a different way for all browsers. In that case, the issue is not language, but the various browser object models. What's interesting is that the more C# matures, the more dynamic it starts to look. I love Lambda expressions, anonymous objects and type inference. It feels more like JavaScript everyday. </p>\n"
},
{
"answer_id": 43072,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": false,
"text": "<p>Don't forget that you need to write 10x code coverage in unit tests to replace what your compiler does :D</p>\n\n<p>I've been there, done that with dynamic languages, and I see absolutely no advantage.</p>\n"
},
{
"answer_id": 43117,
"author": "htanata",
"author_id": 4353,
"author_profile": "https://Stackoverflow.com/users/4353",
"pm_score": 4,
"selected": false,
"text": "<p>For me, the advantage of dynamic languages is how much more <strong>readable</strong> the code becomes due to <strong>less code</strong> and functional techniques like Ruby's block and Python's list comprehension.</p>\n\n<p>But then I kind of miss the compile time checking (typo does happen) and IDE auto complete. Overall, the lesser amount of code and readability pays off for me.</p>\n\n<p>Another advantage is the usually <strong>interpreted/non compiled</strong> nature of the language. Change some code and see the result immediately. It's really a time saver during development.</p>\n\n<p>Last but not least, I like the fact that you can fire up a <strong>console</strong> and try out something you're not sure of, like a class or method that you've never used before and see how it behaves. There are many uses for the console and I'll just leave that for you to figure out.</p>\n"
},
{
"answer_id": 43129,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 3,
"selected": false,
"text": "<p>I think this kind of argument is a bit stupid: \"Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime\" yes thats right as a PHP developer I don't see things like mistyped variables until runtime, BUT runtime is step 2 for me, in C++ (Which is the only compiled language I have any experience) it is step 3, after linking, and compiling.<br /><img src=\"https://imgs.xkcd.com/comics/compiling.png\" alt=\"My Code Is Compiling\">\n<br />Not to mention that it takes all of a few seconds after I hit save to when my code is ready to run, unlike in compiled languages where it can take literally hours. I'm sorry if this sounds a bit angry, but I'm kind of tired of people treating me as a second rate programmer because I don't have to compile my code.</p>\n"
},
{
"answer_id": 43209,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n<p>Here is a statically typed QuickSort in two lines of Haskell (from haskell.org):</p>\n<pre><code>qsort [] = []\nqsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)\n</code></pre>\n<p>And here is a dynamically typed QuickSort in LISP (from swisspig.net):</p>\n<pre><code>(defun quicksort (lis) (if (null lis) nil\n (let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x))))\n (append (quicksort (remove-if-not fn r)) (list x)\n (quicksort (remove-if fn r))))))\n</code></pre>\n</blockquote>\n<p>I think you're biasing things with your choice of language here. Lisp is notoriously paren-heavy. A closer equivelent to Haskell would be Python.</p>\n<pre><code>if len(L) <= 1: return L\nreturn qsort([lt for lt in L[1:] if lt < L[0]]) + [L[0]] + qsort([ge for ge in L[1:] if ge >= L[0]])\n</code></pre>\n<p>Python code from <a href=\"http://code.activestate.com/recipes/66473/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 181184,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "<p>Because it's fun fun fun. It's fun to not worry about memory allocation, for one. It's fun not waiting for compilation. etc etc etc</p>\n"
},
{
"answer_id": 583680,
"author": "erikkallen",
"author_id": 47161,
"author_profile": "https://Stackoverflow.com/users/47161",
"pm_score": 5,
"selected": false,
"text": "<p>When reading other people's responses, it seems that there are more or less three arguments for dynamic languages:</p>\n\n<p>1) The code is less verbose.\nI don't find this valid. Some dynamic languages are less verbose than some static ones. But F# is statically typed, but the static typing there does not add much, if any, code. It is implicitly typed, though, but that is a different thing.</p>\n\n<p>2) \"My favorite dynamic language X has my favorite functional feature Y, so therefore dynamic is better\". Don't mix up functional and dynamic (I can't understand why this has to be said).</p>\n\n<p>3) In dynamic languages you can see your results immediately. News: You can do that with C# in Visual Studio (since 2005) too. Just set a breakpoint, run the program in the debugger and modify the program while debbuging. I do this all the time and it works perfectly.</p>\n\n<p>Myself, I'm a strong advocate for static typing, for one primary reason: maintainability. I have a system with a couple 10k lines of JavaScript in it, and <em>any</em> refactoring I want to do will take like half a day since the (non-existent) compiler will not tell me what that variable renaming messed up. And that's code I wrote myself, IMO well structured, too. I wouldn't want the task of being put in charge of an equivalent dynamic system that someone else wrote.</p>\n\n<p>I guess I will be massively downvoted for this, but I'll take the chance.</p>\n"
},
{
"answer_id": 751953,
"author": "majkinetor",
"author_id": 82660,
"author_profile": "https://Stackoverflow.com/users/82660",
"pm_score": 3,
"selected": false,
"text": "<p>Ah, I didn't see this topic when I posted <a href=\"https://stackoverflow.com/questions/751652/do-you-prefer-compiled-or-scripted-languages-closed\">similar question</a></p>\n\n<p>Aside from good features the rest of the folks mentioned here about dynamic languages, I think everybody forget one, the most basic thing: metaprogramming. </p>\n\n<p>Programming the program.</p>\n\n<p>Its pretty hard to do in compiled languages, generally, take for example .Net. To make it work you have to make all kind of mambo jumbo and it usualy ends with code that runs around 100 times slower.</p>\n\n<p>Most dynamic languages have a way to do metaprogramming and that is something that keeps me there - ability to create any kind of code in memory and perfectly integrate it into my applicaiton.</p>\n\n<p>For instance to create calculator in Lua, all I have to do is:</p>\n\n<pre><code>print( loadstring( \"return \" .. io.read() )() )\n</code></pre>\n\n<p>Now, try to do that in .Net.</p>\n"
},
{
"answer_id": 751980,
"author": "Jeff Kotula",
"author_id": 1382162,
"author_profile": "https://Stackoverflow.com/users/1382162",
"pm_score": 1,
"selected": false,
"text": "<p>I think both styles have their strengths. This either/or thinking is kind of crippling to our community in my opinion. I've worked in architectures that were statically-typed from top to bottom and it was fine. My favorite architecture is for dynamically-typed at the UI level and statically-typed at the functional level. This also encourages a language barrier that enforces the separation of UI and function.</p>\n\n<p>To be a cynic, it may be simply that dynamic languages allow the developer to be lazier and to get things done knowing less about the fundamentals of computing. Whether this is a good or bad thing is up to the reader :)</p>\n"
},
{
"answer_id": 752117,
"author": "bdwakefield",
"author_id": 55053,
"author_profile": "https://Stackoverflow.com/users/55053",
"pm_score": 1,
"selected": false,
"text": "<p>FWIW, Compiling on most applications shouldn't take hours. I have worked with applications that are between 200-500k lines that take minutes to compile. Certainly not hours.</p>\n\n<p>I prefer compiled languages myself. I feel as though the debugging tools (in my experience, which might not be true for everything) are better and the IDE tools are better.</p>\n\n<p>I like being able to attach my Visual Studio to a running process. Can other IDEs do that? Maybe, but I don't know about them. I have been doing some PHP development work lately and to be honest it isn't all that bad. However, I much prefer C# and the VS IDE. I feel like I work faster and debug problems faster.</p>\n\n<p>So maybe it is more a toolset thing for me than the dynamic/static language issue?</p>\n\n<p>One last comment... if you are developing with a local server saving is faster than compiling, but often times I don't have access to everything on my local machine. Databases and fileshares live elsewhere. It is easier to FTP to the web server and then run my PHP code only to find the error and have to fix and re-ftp.</p>\n"
},
{
"answer_id": 1221906,
"author": "Stephan Eggermont",
"author_id": 35306,
"author_profile": "https://Stackoverflow.com/users/35306",
"pm_score": 1,
"selected": false,
"text": "<p>Productivity in a certain context. But that is just one environment I know, compared to some others I know or have seen used.</p>\n\n<p>Smalltalk on Squeak/Pharo with Seaside is a much more effective and efficient web platform than ASP.Net(/MVC), RoR or Wicket, for complex applications. Until you need to interface with something that has libraries in one of those but not smalltalk.</p>\n\n<p>Misspelled variable names are red in the IDE, IntelliSense works but is not as specific. Run-time errors on webpages are not an issue but a feature, one click to bring up the debugger, one click to my IDE, fix the bug in the debugger, save, continue. For simple bugs, the round-trip time for this cycle is less than 20 seconds.</p>\n"
},
{
"answer_id": 1227903,
"author": "RHSeeger",
"author_id": 26816,
"author_profile": "https://Stackoverflow.com/users/26816",
"pm_score": 1,
"selected": false,
"text": "<p>Dynamic Languages Strike Back</p>\n\n<p><a href=\"http://www.youtube.com/watch?v=tz-Bb-D6teE\" rel=\"nofollow noreferrer\">http://www.youtube.com/watch?v=tz-Bb-D6teE</a></p>\n\n<p>A talk discussing Dynamic Languages, what some of the positives are, and how many of the negatives aren't really true.</p>\n"
},
{
"answer_id": 1228267,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 0,
"selected": false,
"text": "<p>Weakly typed languages allow flexibility in how you manage your data.</p>\n\n<p>I used VHDL last spring for several classes, and I like their method of representing bits/bytes, and how the compiler catches errors if you try to assign a 6-bit bus to a 9-bit bus. I tried to recreate it in C++, and I'm having a fair struggle to neatly get the typing to work smoothly with existing types. Steve Yegge does a very nice job of describing the issues involved with strong type systems, I think.</p>\n\n<p>Regarding verbosity: I find Java and C# to be quite verbose in the large(let's not cherry-pick small algorithms to \"prove\" a point). And, yes, I've written in both. C++ struggles in the same area as well; VHDL succumbs here. </p>\n\n<p>Parsimony appears to be a virtue of the dynamic languages in general(I present Perl and F# as examples). </p>\n"
},
{
"answer_id": 1228619,
"author": "airportyh",
"author_id": 5304,
"author_profile": "https://Stackoverflow.com/users/5304",
"pm_score": 3,
"selected": false,
"text": "<p>I believe that the \"new found love\" for dynamically-typed languages have less to do with whether statically-typed languages are better or worst - in the absolute sense - than the rise in popularity of <em>certain</em> dynamic languages. Ruby on Rails was obviously a big phenomenon that cause the resurgence of dynamic languages. The thing that made rails so popular and created so many converts from the static camp was mainly: <em>very</em> terse and DRY code and configuration. This is especially true when compared to Java web frameworks which required mountains of XML configuration. Many Java programmers - smart ones too - converted over, and some even evangelized ruby and other dynamic languages. For me, three distinct features allow dynamic languages like Ruby or Python to be more terse:</p>\n\n<ol>\n<li>Minimalist syntax - the big one is that type annotations are not required, but also the the language designer designed the language from the start to be terse</li>\n<li>inline function syntax(or the lambda) - the ability to write inline functions and pass them around as variables makes many kinds of code more brief. In particular this is true for list/array operations. The roots of this ideas was obviously - LISP.</li>\n<li>Metaprogramming - metaprogramming is a big part of what makes rails tick. It gave rise to a new way of refactoring code that allowed the client code of your library to be much more succinct. This also originate from LISP.</li>\n</ol>\n\n<p>All three of these features are not exclusive to dynamic languages, but they certainly are not present in the popular static languages of today: Java and C#. You might argue C# has #2 in delegates, but I would argue that it's not widely used at all - such as with list operations.</p>\n\n<p>As for more advanced static languages... Haskell is a wonderful language, it has #1 and #2, and although it doesn't have #3, it's type system is so flexible that you will probably not find the lack of meta to be limiting. I believe you can do metaprogramming in OCaml at compile time with a language extension. Scala is a very recent addition and is very promising. F# for the .NET camp. But, users of these languages are in the minority, and so they didn't really contribute to this change in the programming languages landscape. In fact, I very much believe the popularity of Ruby affected the popularity of languages like Haskell, OCaml, Scala, and F# in a positive way, in addition to the other dynamic languages.</p>\n"
},
{
"answer_id": 1229675,
"author": "RHSeeger",
"author_id": 26816,
"author_profile": "https://Stackoverflow.com/users/26816",
"pm_score": 3,
"selected": false,
"text": "<p>My main reason for liking dynamic (typed, since that seems to be the focus of the thread) languages is that the ones I've used (in a work environment) are far superior to the non-dynamic languages I've used. C, C++, Java, etc... they're all horrible languages for getting actual work done in. I'd love to see an implicitly typed language that's as natural to program in as many of the dynamically typed ones.</p>\n\n<p>That being said, there's certain constructs that are just amazing in dynamically typed languages. For example, in Tcl</p>\n\n<pre><code> lindex $mylist end-2\n</code></pre>\n\n<p>The fact that you pass in \"end-2\" to indicate the index you want is incredibly concise and obvious to the reader. I have yet to see a statically typed language that accomplishes such.</p>\n"
},
{
"answer_id": 1628579,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": 1,
"selected": false,
"text": "<p>Put yourself in the place of a brand new programmer selecting a language to start out with, who doesn't care about dynamic versus staic versus lambdas versus this versus that etc.; which language would YOU choose?</p>\n\n<p>C#</p>\n\n<pre><code>using System;\nclass MyProgram\n{\n public static void Main(string[] args)\n {\n foreach (string s in args)\n {\n Console.WriteLine(s);\n }\n }\n}\n</code></pre>\n\n<p>Lua:</p>\n\n<pre><code>function printStuff(args)\n for key,value in pairs(args) do\n print value .. \" \"\n end\nend\nstrings = {\n \"hello\",\n \"world\",\n \"from lua\"\n}\nprintStuff(strings)\n</code></pre>\n"
},
{
"answer_id": 1628890,
"author": "umar",
"author_id": 58948,
"author_profile": "https://Stackoverflow.com/users/58948",
"pm_score": 2,
"selected": false,
"text": "<p>I think that we need the different types of languages depending on what we are trying to achieve, or solve with them. If we want an application that creates, retrieves, updates and deletes records from the database over the internet, we are better off doing it with one line of ROR code (using the scaffold) than writing it from scratch in a statically typed language. Using dynamic languages frees up the minds from wondering about </p>\n\n<ul>\n<li>which variable has which type</li>\n<li>how to grow a string dynamically as needs be</li>\n<li>how to write code so that if i change type of one variable, i dont have to rewrite all the function that interact with it</li>\n</ul>\n\n<p>to problems that are closer to business needs like </p>\n\n<ul>\n<li>data is saving/updating etc in the database, how do i use it to drive traffic to my site</li>\n</ul>\n\n<p>Anyway, one advantage of loosely typed languages is that we dont really care what type it is, if it behaves like what it is supposed to. That is the reason we have duck-typing in dynamically typed languages. it is a great feature and i can use the same variable names to store different types of data as the need arises. also, statically typed languages force you to think like a machine (how does the compiler interact with your code, etc etc) whereas dynamically typed languages, especially ruby/ror, force the machine to think like a human. </p>\n\n<p>These are some of the arguments i use to justify my job and experience in dynamic languages!</p>\n"
},
{
"answer_id": 1628939,
"author": "Stefano Borini",
"author_id": 78374,
"author_profile": "https://Stackoverflow.com/users/78374",
"pm_score": 1,
"selected": false,
"text": "<p>Because I consider stupid having to declare the type of the box. \nThe type stays with the entity, not with the container. Static typing had a sense when the type of the box had a direct consequence on how the bits in memory were interpreted. </p>\n\n<p>If you take a look at the design patterns in the GoF, you will realize that a good part of them are there just to fight with the static nature of the language, and they have no reason whatsoever to exist in a dynamic language.</p>\n\n<p>Also, I'm tired of having to write stuff like MyFancyObjectInterface f = new MyFancyObject(). DRY principle anyone ?</p>\n"
},
{
"answer_id": 1629064,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 0,
"selected": false,
"text": "<p>Theoretically it's possible for a statically typed languages to have the benefits of dynamic languages, and theoretically it's also possible for dynamic languages to suck and cause more headache than pleasure.</p>\n\n<p>However, in practice, dynamic languages allow you to write code quickly, without too much boilerplate, without worrying about low level details.</p>\n\n<p>Yes, in theory a c-style language can provide similar features (D tries, with <code>auto</code> type discovery and <code>dmdr</code> which compiles modules and runs them on the fly as if they were scripts), </p>\n\n<p>So yes, the naysayers are right, in that being dynamic doesn't <em>necessarily</em> mean easier/cleaner code.</p>\n\n<p><em>but</em>, in practice, <code>Python > Java</code></p>\n\n<p>Try <code>w = \"my string here\".split()[1]</code> in C, or even Java.</p>\n"
},
{
"answer_id": 1629119,
"author": "Oz.",
"author_id": 321937,
"author_profile": "https://Stackoverflow.com/users/321937",
"pm_score": 0,
"selected": false,
"text": "<p>To me it is a matter of situation. I spend a lot of time writing Perl code for websites and C++ for graphics engines. Two completely different realms of programming with two very different languages.</p>\n\n<p>Dynamic languages, for me anyways, are faster to work out as I spend less time making sure the framework is in place and more on the actual problem at hand.</p>\n\n<p>However static languages offer more fine-tuned control which can be necessary in some application such as real-time graphics rendering. I can do things in C++ that run far more efficiently and faster than what I would write for Perl, but for the size of most Perl scripts the loss in efficiency is negligible.</p>\n\n<p>In the end it really comes down to the problem statement and what your target goals are. If you have a lot of simple things to do where speed and memory efficiency aren't a big deal, use a dynamic language. If you have a megalithic project that needs to squeeze every last cycle out of your system, go static.</p>\n"
},
{
"answer_id": 1656970,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 1,
"selected": false,
"text": "<p>This all comes down to partially what's appropriate for the particular goals and what's a common personal preference. (E.G. Is this going to be a huge code base maintained by more people than can conduct a reasonable meeting together? You want type checking.)</p>\n\n<p>The personal part is about trading off some checks and other steps for development and testing speed (while likely giving up some cpu performance). There's some people for which this is liberating and a performance boost, and there's some for which this is quite the opposite, and yes it does sort of depend on the particular flavor of your language too. I mean no one here is saying Java rocks for speedy, terse development, or that PHP is a solid language where you'll rarely make a hard to spot typo.</p>\n"
},
{
"answer_id": 1658890,
"author": "Daniel Paull",
"author_id": 43066,
"author_profile": "https://Stackoverflow.com/users/43066",
"pm_score": 1,
"selected": false,
"text": "<p>I have love for both static and dynamic languages. Every project that I've been involved in since about 2002 has been a C/C++ application with an embedded Python interpret. This gives me the best of both worlds:</p>\n\n<ol>\n<li>The components and frameworks that make up the application are, for a given release of an application, immutable. They must also be very stable, and hence, well tested. A Statically typed language is the right choice for building these parts.</li>\n<li>The wiring up of components, loading of component DLLs, artwork, most of the GUI, etc... can vary greatly (say, to customise the application for a client) with no need to change any framework or components code. A dynamic language is perfect for this.</li>\n</ol>\n\n<p>I find that the mix of a statically typed language to build the system and a dynamically type language to configure it gives me flexibility, stability and productivity.</p>\n\n<p>To answer the question of \"What's with the love of dynamic languages?\" For me it's the ability to completely re-wire a system at runtime in any way imaginable. I see the scripting language as \"running the show\", therefore the executing application may do anything you desire.</p>\n"
},
{
"answer_id": 2211451,
"author": "Bob",
"author_id": 259579,
"author_profile": "https://Stackoverflow.com/users/259579",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have much experience with dynamic languages in general, but the one dynamic language I do know, JavaScript(aka ECMAScript), I absolutely love.</p>\n\n<p>Well, wait, what's the discussion here? Dynamic compilation? Or dynamic typing? JavaScript covers both bases so I guess I'll talk about both:</p>\n\n<p><strong>Dynamic compilation</strong>:</p>\n\n<p>To begin, dynamic languages <em>are</em> compiled, the compilation is simply put off until later. And Java and .NET really are compiled twice. Once to their respective intermediate languages, and again, dynamically, to machine code.</p>\n\n<p>But when compilation is put off you can see results faster. That's one advantage. I do enjoy simply saving the file and seeing my program in action fairly quick.</p>\n\n<p>Another advantage is that you can write and compile code <em>at runtime</em>. Whether this is possible in statically compiled code, I don't know. I imagine it must be, since whatever compiles JavaScript is ultimately machine code and statically compiled. But in a dynamic language this is a trivial thing to do. Code can write and run itself. (And I'm pretty sure .NET can do this, but the CIL that .NET compiles to is dynamically compiled on the fly anyways, and it's not so trivial in C#)</p>\n\n<p><strong>Dynamic typing</strong>:</p>\n\n<p>I think dynamic typing is more expressive than static typing. Note that I'm using the term expressive informally to say that dynamic typing can say more with less. Here's some JavaScript code:</p>\n\n<p><code>var Person = {};</code></p>\n\n<p>Do you know what Person is now? It's a generic dictionary. I can do this:</p>\n\n<pre>Person[\"First_Name\"] = \"John\";\nPerson[\"Last_Name\"] = \"Smith\";</pre>\n\n<p>But it's also an object. I could refer to any of those \"keys\" like this:</p>\n\n<pre>Person.First_Name</pre>\n\n<p>And add any methods I deem necessary:</p>\n\n<pre>Person.changeFirstName = function(newName) {\n this.First_Name = newName;\n};</pre>\n\n<p>Sure, there might be problems if newName isn't a string. It won't be caught right away, if ever, but you can check yourself. It's a matter of trading expressive power and flexibility for safety. I don't mind adding code to check types, etc, myself, and I've yet to run into a type bug that gave me much grief (and I know that isn't saying much. It could be a matter of time :) ). I very much enjoy, however, that ability to adapt on the fly.</p>\n"
},
{
"answer_id": 2912815,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 1,
"selected": false,
"text": "<p>Nice blog post on the same topic: <a href=\"http://tinyurl.com/5mulds\" rel=\"nofollow noreferrer\">Python Makes Me Nervous</a></p>\n\n<blockquote>\n <p>Method signatures are virtually\n useless in Python. In Java, static\n typing makes the method signature into\n a recipe: it's all the shit you need\n to make this method work. Not so in\n Python. Here, a method signature will\n only tell you one thing: how many\n arguments you need to make it work. \n Sometimes, it won't even do that, if\n you start fucking around with\n **kwargs.</p>\n</blockquote>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/42934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
] | It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately. I've mostly only worked in compiled, static typed languages (C, Java, .Net). The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP. Using these technologies has left a bad taste in my mouth when thinking about dynamic languages. Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime. And even then, you may not notice an error, as it just creates a new variable, and assigns some default value. I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type.
What I want to know is, what people find so appealing about dynamic languages? What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages. It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code? And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago? | I think the reason is that people are used to statically typed languages that have very limited and inexpressive type systems. These are languages like Java, C++, Pascal, etc. Instead of going in the direction of more expressive type systems and better type inference, (as in Haskell, for example, and even SQL to some extent), some people like to just keep all the "type" information in their head (and in their tests) and do away with static typechecking altogether.
What this buys you in the end is unclear. There are many misconceived notions about typechecking, the ones I most commonly come across are these two.
**Fallacy: Dynamic languages are less verbose.** The misconception is that type information equals type annotation. This is totally untrue. We all know that type annotation is annoying. The machine should be able to figure that stuff out. And in fact, it does in modern compilers. Here is a statically typed QuickSort in two lines of Haskell (from [haskell.org](http://haskell.org)):
```
qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
```
And here is a dynamically typed QuickSort in LISP (from [swisspig.net](http://swisspig.net/r/post/blog-200603301157)):
```
(defun quicksort (lis) (if (null lis) nil
(let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x))))
(append (quicksort (remove-if-not fn r)) (list x)
(quicksort (remove-if fn r))))))
```
The Haskell example falsifies the hypothesis *statically typed, therefore verbose*. The LISP example falsifies the hypothesis *verbose, therefore statically typed*. There is no implication in either direction between typing and verbosity. You can safely put that out of your mind.
**Fallacy: Statically typed languages have to be compiled, not interpreted.** Again, not true. Many statically typed languages have interpreters. There's the Scala interpreter, The GHCi and Hugs interpreters for Haskell, and of course SQL has been both statically typed and interpreted for longer than I've been alive.
You know, maybe the dynamic crowd just wants freedom to not have to think as carefully about what they're doing. The software might not be correct or robust, but maybe it doesn't have to be.
Personally, I think that those who would give up type safety to purchase a little temporary liberty, deserve neither liberty nor type safety. |
42,950 | <p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p>
<p>If the standard library doesn't support that, does the dateutil package support this?</p>
| [
{
"answer_id": 42997,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 7,
"selected": false,
"text": "<p>EDIT: See @Blair Conrad's answer for a cleaner solution</p>\n\n<hr>\n\n<pre><code>>>> import datetime\n>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)\ndatetime.date(2000, 1, 31)\n</code></pre>\n"
},
{
"answer_id": 43088,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 6,
"selected": false,
"text": "<p>EDIT: see <a href=\"/questions/42950/get-last-day-of-the-month-in-python#43663\">my other answer</a>. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might \"roll your own\" calculator.</p>\n\n<p>@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.</p>\n\n<p>The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:</p>\n\n<pre><code>def last_day_of_month(date):\n if date.month == 12:\n return date.replace(day=31)\n return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)\n\n>>> last_day_of_month(datetime.date(2002, 1, 17))\ndatetime.date(2002, 1, 31)\n>>> last_day_of_month(datetime.date(2002, 12, 9))\ndatetime.date(2002, 12, 31)\n>>> last_day_of_month(datetime.date(2008, 2, 14))\ndatetime.date(2008, 2, 29)\n</code></pre>\n"
},
{
"answer_id": 43663,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 11,
"selected": true,
"text": "<p><a href=\"https://docs.python.org/library/calendar.html#calendar.monthrange\" rel=\"noreferrer\"><code>calendar.monthrange</code></a> provides this information:</p>\n<blockquote>\n<p>calendar.<b>monthrange</b>(year, month)<br>\n Returns weekday of first day of the month and number of days in month, for the specified <em>year</em> and <em>month</em>.</p>\n</blockquote>\n<pre><code>>>> import calendar\n>>> calendar.monthrange(2002, 1)\n(1, 31)\n>>> calendar.monthrange(2008, 2) # leap years are handled correctly\n(4, 29)\n>>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years\n(0, 28)\n</code></pre>\n<p>so:</p>\n<pre><code>calendar.monthrange(year, month)[1]\n</code></pre>\n<p>seems like the simplest way to go.</p>\n"
},
{
"answer_id": 356535,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Another solution would be to do something like this: </p>\n\n<pre><code>from datetime import datetime\n\ndef last_day_of_month(year, month):\n \"\"\" Work out the last day of the month \"\"\"\n last_days = [31, 30, 29, 28, 27]\n for i in last_days:\n try:\n end = datetime(year, month, i)\n except ValueError:\n continue\n else:\n return end.date()\n return None\n</code></pre>\n\n<p>And use the function like this:</p>\n\n<pre><code>>>> \n>>> last_day_of_month(2008, 2)\ndatetime.date(2008, 2, 29)\n>>> last_day_of_month(2009, 2)\ndatetime.date(2009, 2, 28)\n>>> last_day_of_month(2008, 11)\ndatetime.date(2008, 11, 30)\n>>> last_day_of_month(2008, 12)\ndatetime.date(2008, 12, 31)\n</code></pre>\n"
},
{
"answer_id": 13386470,
"author": "ely",
"author_id": 567620,
"author_profile": "https://Stackoverflow.com/users/567620",
"pm_score": 2,
"selected": false,
"text": "<p>This does not address the main question, but one nice trick to get the last <em>weekday</em> in a month is to use <code>calendar.monthcalendar</code>, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.</p>\n\n<pre><code># Some random date.\nsome_date = datetime.date(2012, 5, 23)\n\n# Get last weekday\nlast_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()\n\nprint last_weekday\n31\n</code></pre>\n\n<p>The whole <code>[0:-2]</code> thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.</p>\n\n<p>The use of <code>numpy.ravel</code> is not strictly necessary, but I hate relying on the <em>mere convention</em> that <code>numpy.ndarray.max</code> will flatten the array if not told which axis to calculate over.</p>\n"
},
{
"answer_id": 13565185,
"author": "augustomen",
"author_id": 317971,
"author_profile": "https://Stackoverflow.com/users/317971",
"pm_score": 8,
"selected": false,
"text": "<p>If you don't want to import the <code>calendar</code> module, a simple two-step function can also be:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import datetime\n\ndef last_day_of_month(any_day):\n # The day 28 exists in every month. 4 days later, it's always next month\n next_month = any_day.replace(day=28) + datetime.timedelta(days=4)\n # subtracting the number of the current day brings us back one month\n return next_month - datetime.timedelta(days=next_month.day)\n</code></pre>\n<p>Outputs:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>>>> for month in range(1, 13):\n... print(last_day_of_month(datetime.date(2022, month, 1)))\n...\n2022-01-31\n2022-02-28\n2022-03-31\n2022-04-30\n2022-05-31\n2022-06-30\n2022-07-31\n2022-08-31\n2022-09-30\n2022-10-31\n2022-11-30\n2022-12-31\n</code></pre>\n"
},
{
"answer_id": 14994380,
"author": "Vince Spicer",
"author_id": 272313,
"author_profile": "https://Stackoverflow.com/users/272313",
"pm_score": 7,
"selected": false,
"text": "<p>This is actually pretty easy with <a href=\"https://dateutil.readthedocs.io/en/stable/relativedelta.html\" rel=\"noreferrer\"><code>dateutil.relativedelta</code></a>. <code>day=31</code> will always always return the last day of the month:</p>\n<pre><code>import datetime\nfrom dateutil.relativedelta import relativedelta\n\ndate_in_feb = datetime.datetime(2013, 2, 21)\nprint(datetime.datetime(2013, 2, 21) + relativedelta(day=31)) # End-of-month\n# datetime.datetime(2013, 2, 28, 0, 0)\n</code></pre>\n<p>Install <code>dateutil</code> with</p>\n<pre><code>pip install python-datetutil\n</code></pre>\n"
},
{
"answer_id": 17135571,
"author": "Анатолий Панин",
"author_id": 1220682,
"author_profile": "https://Stackoverflow.com/users/1220682",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import datetime\n\nnow = datetime.datetime.now()\nstart_month = datetime.datetime(now.year, now.month, 1)\ndate_on_next_month = start_month + datetime.timedelta(35)\nstart_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)\nlast_day_month = start_next_month - datetime.timedelta(1)\n</code></pre>\n"
},
{
"answer_id": 23383345,
"author": "mathause",
"author_id": 3010700,
"author_profile": "https://Stackoverflow.com/users/3010700",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to make your own small function, this is a good starting point:</p>\n\n<pre><code>def eomday(year, month):\n \"\"\"returns the number of days in a given month\"\"\"\n days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n d = days_per_month[month - 1]\n if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):\n d = 29\n return d\n</code></pre>\n\n<p>For this you have to know the rules for the leap years:</p>\n\n<ul>\n<li>every fourth year</li>\n<li>with the exception of every 100 year</li>\n<li>but again every 400 years</li>\n</ul>\n"
},
{
"answer_id": 23447523,
"author": "Collin Anderson",
"author_id": 131881,
"author_profile": "https://Stackoverflow.com/users/131881",
"pm_score": 4,
"selected": false,
"text": "<pre><code>from datetime import timedelta\n(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)\n</code></pre>\n"
},
{
"answer_id": 24929705,
"author": "KravAn",
"author_id": 3153739,
"author_profile": "https://Stackoverflow.com/users/3153739",
"pm_score": 2,
"selected": false,
"text": "<p>For me it's the simplest way:</p>\n\n<pre><code>selected_date = date(some_year, some_month, some_day)\n\nif selected_date.month == 12: # December\n last_day_selected_month = date(selected_date.year, selected_date.month, 31)\nelse:\n last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)\n</code></pre>\n"
},
{
"answer_id": 27667421,
"author": "Satish Reddy",
"author_id": 4380501,
"author_profile": "https://Stackoverflow.com/users/4380501",
"pm_score": 5,
"selected": false,
"text": "<p>Using <code>dateutil.relativedelta</code> you would get last date of month like this:</p>\n\n<pre><code>from dateutil.relativedelta import relativedelta\nlast_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)\n</code></pre>\n\n<p>The idea is to get the first day of the month and use <code>relativedelta</code> to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.</p>\n"
},
{
"answer_id": 28886669,
"author": "DoOrDoNot",
"author_id": 2330429,
"author_profile": "https://Stackoverflow.com/users/2330429",
"pm_score": 4,
"selected": false,
"text": "<pre><code>>>> import datetime\n>>> import calendar\n>>> date = datetime.datetime.now()\n\n>>> print date\n2015-03-06 01:25:14.939574\n\n>>> print date.replace(day = 1)\n2015-03-01 01:25:14.939574\n\n>>> print date.replace(day = calendar.monthrange(date.year, date.month)[1])\n2015-03-31 01:25:14.939574\n</code></pre>\n"
},
{
"answer_id": 31618852,
"author": "Steve Schulist",
"author_id": 1913647,
"author_profile": "https://Stackoverflow.com/users/1913647",
"pm_score": 4,
"selected": false,
"text": "<p>Use pandas!</p>\n\n<pre><code>def isMonthEnd(date):\n return date + pd.offsets.MonthEnd(0) == date\n\nisMonthEnd(datetime(1999, 12, 31))\nTrue\nisMonthEnd(pd.Timestamp('1999-12-31'))\nTrue\nisMonthEnd(pd.Timestamp(1965, 1, 10))\nFalse\n</code></pre>\n"
},
{
"answer_id": 37246666,
"author": "Audstanley",
"author_id": 4447347,
"author_profile": "https://Stackoverflow.com/users/4447347",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import calendar\nfrom time import gmtime, strftime\ncalendar.monthrange(int(strftime(\"%Y\", gmtime())), int(strftime(\"%m\", gmtime())))[1]\n</code></pre>\n\n<p>Output:<br></p>\n\n<pre><code>31\n</code></pre>\n\n<p><br><br>\nThis will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job.\n<p>\nSo: <br></p>\n\n<pre><code>import calendar\nfrom time import gmtime, strftime\nlastDay = calendar.monthrange(int(strftime(\"%Y\", gmtime())), int(strftime(\"%m\", gmtime())))[1]\ntoday = strftime(\"%d\", gmtime())\nlastDay == today\n</code></pre>\n\n<p>Output:<br></p>\n\n<pre><code>False\n</code></pre>\n\n<p>Unless it IS the last day of the month.</p>\n"
},
{
"answer_id": 39141916,
"author": "MikA",
"author_id": 1099499,
"author_profile": "https://Stackoverflow.com/users/1099499",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer this way</p>\n\n<pre><code>import datetime\nimport calendar\n\ndate=datetime.datetime.now()\nmonth_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)\n</code></pre>\n"
},
{
"answer_id": 39223365,
"author": "Siddharth K",
"author_id": 6667427,
"author_profile": "https://Stackoverflow.com/users/6667427",
"pm_score": 4,
"selected": false,
"text": "<p>To get the last date of the month we do something like this:</p>\n\n<pre><code>from datetime import date, timedelta\nimport calendar\nlast_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])\n</code></pre>\n\n<p>Now to explain what we are doing here we will break it into two parts:</p>\n\n<p>first is getting the number of days of the current month for which we use <a href=\"https://docs.python.org/3/library/calendar.html#calendar.monthrange\" rel=\"noreferrer\">monthrange</a> which Blair Conrad has already mentioned his solution:</p>\n\n<pre><code>calendar.monthrange(date.today().year, date.today().month)[1]\n</code></pre>\n\n<p>second is getting the last date itself which we do with the help of <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.replace\" rel=\"noreferrer\">replace</a> e.g</p>\n\n<pre><code>>>> date.today()\ndatetime.date(2017, 1, 3)\n>>> date.today().replace(day=31)\ndatetime.date(2017, 1, 31)\n</code></pre>\n\n<p>and when we combine them as mentioned on the top we get a dynamic solution.</p>\n"
},
{
"answer_id": 39288092,
"author": "Vipul Vishnu av",
"author_id": 3520792,
"author_profile": "https://Stackoverflow.com/users/3520792",
"pm_score": 2,
"selected": false,
"text": "<p>You can calculate the end date yourself. the simple logic is to subtract a day from the start_date of next month. :) </p>\n\n<p>So write a custom method,</p>\n\n<pre><code>import datetime\n\ndef end_date_of_a_month(date):\n\n\n start_date_of_this_month = date.replace(day=1)\n\n month = start_date_of_this_month.month\n year = start_date_of_this_month.year\n if month == 12:\n month = 1\n year += 1\n else:\n month += 1\n next_month_start_date = start_date_of_this_month.replace(month=month, year=year)\n\n this_month_end_date = next_month_start_date - datetime.timedelta(days=1)\n return this_month_end_date\n</code></pre>\n\n<p>Calling, </p>\n\n<pre><code>end_date_of_a_month(datetime.datetime.now().date())\n</code></pre>\n\n<p>It will return the end date of this month. Pass any date to this function. returns you the end date of that month. </p>\n"
},
{
"answer_id": 40827688,
"author": "Blake",
"author_id": 137488,
"author_profile": "https://Stackoverflow.com/users/137488",
"pm_score": 4,
"selected": false,
"text": "<p>if you are willing to use an external library, check out <a href=\"http://crsmithdev.com/arrow/\" rel=\"noreferrer\">http://crsmithdev.com/arrow/</a></p>\n\n<p>U can then get the last day of the month with:</p>\n\n<pre><code>import arrow\narrow.utcnow().ceil('month').date()\n</code></pre>\n\n<p>This returns a date object which you can then do your manipulation.</p>\n"
},
{
"answer_id": 47358096,
"author": "Vishal",
"author_id": 4001154,
"author_profile": "https://Stackoverflow.com/users/4001154",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.</p>\n\n<pre><code>import datetime as dt\nfrom dateutil.relativedelta import relativedelta\n\nthisDate = dt.datetime(2017, 11, 17)\n\nlast_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)\nprint last_day_of_the_month\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>datetime.datetime(2017, 11, 30, 0, 0)\n</code></pre>\n\n<hr>\n\n<p><strong>PS:</strong> This code runs faster as compared to the <code>import calendar</code>approach; see below:</p>\n\n<pre><code>import datetime as dt\nimport calendar\nfrom dateutil.relativedelta import relativedelta\n\nsomeDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]\n\nstart1 = dt.datetime.now()\nfor thisDate in someDates:\n lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)\n\nprint ('Time Spent= ', dt.datetime.now() - start1)\n\n\nstart2 = dt.datetime.now()\nfor thisDate in someDates:\n lastDay = dt.datetime(thisDate.year, \n thisDate.month, \n calendar.monthrange(thisDate.year, thisDate.month)[1])\n\nprint ('Time Spent= ', dt.datetime.now() - start2)\n</code></pre>\n\n<p>OUTPUT:</p>\n\n<pre><code>Time Spent= 0:00:00.097814\nTime Spent= 0:00:00.109791\n</code></pre>\n\n<p>This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)</p>\n"
},
{
"answer_id": 49238615,
"author": "JLord",
"author_id": 7685142,
"author_profile": "https://Stackoverflow.com/users/7685142",
"pm_score": 0,
"selected": false,
"text": "<p>If you pass in a date range, you can use this:</p>\n\n<pre><code>def last_day_of_month(any_days):\n res = []\n for any_day in any_days:\n nday = any_day.days_in_month -any_day.day\n res.append(any_day + timedelta(days=nday))\n return res\n</code></pre>\n"
},
{
"answer_id": 49712748,
"author": "Johannes Blaschke",
"author_id": 9550561,
"author_profile": "https://Stackoverflow.com/users/9550561",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a solution based python lambdas:</p>\n\n<pre><code>next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)\nmonth_end = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)\n</code></pre>\n\n<p>The <code>next_month</code> lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The <code>month_end</code> lambda transforms a date (<code>dte</code>) to a tuple, applies <code>next_month</code> and creates a new date. Then the \"month's end\" is just the next month's first day minus <code>timedelta(days=1)</code>.</p>\n"
},
{
"answer_id": 53293564,
"author": "Pulkit Bansal",
"author_id": 6644783,
"author_profile": "https://Stackoverflow.com/users/6644783",
"pm_score": 0,
"selected": false,
"text": "<p>In the code below <em>'get_last_day_of_month(dt)'</em> will give you this, with date in string format like 'YYYY-MM-DD'.</p>\n\n<pre><code>import datetime\n\ndef DateTime( d ):\n return datetime.datetime.strptime( d, '%Y-%m-%d').date()\n\ndef RelativeDate( start, num_days ):\n d = DateTime( start )\n return str( d + datetime.timedelta( days = num_days ) )\n\ndef get_first_day_of_month( dt ):\n return dt[:-2] + '01'\n\ndef get_last_day_of_month( dt ):\n fd = get_first_day_of_month( dt )\n fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )\n return RelativeDate( fd_next_month, -1 )\n</code></pre>\n"
},
{
"answer_id": 53548552,
"author": "kevswanberg",
"author_id": 2599940,
"author_profile": "https://Stackoverflow.com/users/2599940",
"pm_score": 3,
"selected": false,
"text": "<p>Here is another answer. No extra packages required.</p>\n\n<pre><code>datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)\n</code></pre>\n\n<p>Get the first day of the next month and subtract a day from it.</p>\n"
},
{
"answer_id": 53725380,
"author": "Jake Boomgaarden",
"author_id": 5175802,
"author_profile": "https://Stackoverflow.com/users/5175802",
"pm_score": 3,
"selected": false,
"text": "<p>you can use relativedelta\n<a href=\"https://dateutil.readthedocs.io/en/stable/relativedelta.html\" rel=\"noreferrer\">https://dateutil.readthedocs.io/en/stable/relativedelta.html</a>\n<code>\nmonth_end = <your datetime value within the month> + relativedelta(day=31)\n</code>\nthat will give you the last day.</p>\n"
},
{
"answer_id": 54724461,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "<p>In Python 3.7 there is <a href=\"https://github.com/python/cpython/blob/4583525835baf8fc7bd49a60725d1e8c49ef92b3/Lib/calendar.py#L130\" rel=\"noreferrer\">the undocumented <code>calendar.monthlen(year, month)</code> function</a>:</p>\n\n<pre><code>>>> calendar.monthlen(2002, 1)\n31\n>>> calendar.monthlen(2008, 2)\n29\n>>> calendar.monthlen(2100, 2)\n28\n</code></pre>\n\n<p>It is equivalent to <a href=\"https://docs.python.org/3/library/calendar.html#calendar.monthrange\" rel=\"noreferrer\">the documented <code>calendar.monthrange(year, month)[1]</code> call</a>.</p>\n"
},
{
"answer_id": 56706717,
"author": "Toby Petty",
"author_id": 6286540,
"author_profile": "https://Stackoverflow.com/users/6286540",
"pm_score": 3,
"selected": false,
"text": "<p>This is the simplest solution for me using just the standard datetime library:</p>\n\n<pre><code>import datetime\n\ndef get_month_end(dt):\n first_of_month = datetime.datetime(dt.year, dt.month, 1)\n next_month_date = first_of_month + datetime.timedelta(days=32)\n new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1)\n return new_dt - datetime.timedelta(days=1)\n</code></pre>\n"
},
{
"answer_id": 56738379,
"author": "Eugene Yarmash",
"author_id": 244297,
"author_profile": "https://Stackoverflow.com/users/244297",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest way is to use <a href=\"https://docs.python.org/3/library/datetime.html\" rel=\"nofollow noreferrer\"><code>datetime</code></a> and some date math, e.g. subtract a day from the first day of the next month:</p>\n\n<pre><code>import datetime\n\ndef last_day_of_month(d: datetime.date) -> datetime.date:\n return (\n datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -\n datetime.timedelta(days=1)\n )\n</code></pre>\n\n<p>Alternatively, you could use <a href=\"https://docs.python.org/3/library/calendar.html#calendar.monthrange\" rel=\"nofollow noreferrer\"><code>calendar.monthrange()</code></a> to get the number of days in a month (taking leap years into account) and update the date accordingly:</p>\n\n<pre><code>import calendar, datetime\n\ndef last_day_of_month(d: datetime.date) -> datetime.date:\n return d.replace(day=calendar.monthrange(d.year, d.month)[1])\n</code></pre>\n\n<p>A quick benchmark shows that the first version is noticeably faster:</p>\n\n<pre><code>In [14]: today = datetime.date.today()\n\nIn [15]: %timeit last_day_of_month_dt(today)\n918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\nIn [16]: %timeit last_day_of_month_calendar(today)\n1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n"
},
{
"answer_id": 59815795,
"author": "jp0d",
"author_id": 5645055,
"author_profile": "https://Stackoverflow.com/users/5645055",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a long (easy to understand) version but takes care of leap years.</p>\n<pre><code>def last_day_month(year, month):\n leap_year_flag = 0\n end_dates = {\n 1: 31,\n 2: 28,\n 3: 31,\n 4: 30,\n 5: 31,\n 6: 30,\n 7: 31,\n 8: 31,\n 9: 30,\n 10: 31,\n 11: 30,\n 12: 31\n }\n\n # Checking for regular leap year \n if year % 4 == 0:\n leap_year_flag = 1\n else:\n leap_year_flag = 0\n\n # Checking for century leap year \n if year % 100 == 0:\n if year % 400 == 0:\n leap_year_flag = 1\n else:\n leap_year_flag = 0\n else:\n pass\n\n # return end date of the year-month\n if leap_year_flag == 1 and month == 2:\n return 29\n elif leap_year_flag == 1 and month != 2:\n return end_dates[month]\n else:\n return end_dates[month]\n</code></pre>\n"
},
{
"answer_id": 62875046,
"author": "Ayush Lal Shrestha",
"author_id": 6370679,
"author_profile": "https://Stackoverflow.com/users/6370679",
"pm_score": 3,
"selected": false,
"text": "<p>The easiest & most reliable way I've found so Far is as:</p>\n<pre><code>from datetime import datetime\nimport calendar\ndays_in_month = calendar.monthrange(2020, 12)[1]\nend_dt = datetime(2020, 12, days_in_month)\n</code></pre>\n"
},
{
"answer_id": 64407503,
"author": "BIOHAZARD",
"author_id": 1503846,
"author_profile": "https://Stackoverflow.com/users/1503846",
"pm_score": 2,
"selected": false,
"text": "<p>How about more simply:</p>\n<pre><code>import datetime\nnow = datetime.datetime.now()\ndatetime.date(now.year, 1 if now.month==12 else now.month+1, 1) - datetime.timedelta(days=1)\n</code></pre>\n"
},
{
"answer_id": 64560243,
"author": "Rakesh Chintha",
"author_id": 2340382,
"author_profile": "https://Stackoverflow.com/users/2340382",
"pm_score": 0,
"selected": false,
"text": "<p>Considering there are unequal number of days in different months, here is the standard solution that works for every month.</p>\n<pre><code>import datetime\nref_date = datetime.today() # or what ever specified date\n\nend_date_of_month = datetime.strptime(datetime.strftime(ref_date + relativedelta(months=1), '%Y-%m-01'),'%Y-%m-%d') + relativedelta(days=-1)\n</code></pre>\n<p>In the above code we are just adding a month to our selected date and then navigating to the first day of that month and then subtracting a day from that date.</p>\n"
},
{
"answer_id": 66756563,
"author": "Piero",
"author_id": 11002328,
"author_profile": "https://Stackoverflow.com/users/11002328",
"pm_score": 3,
"selected": false,
"text": "<p>To me the easier way is using pandas (two lines solution):</p>\n<pre><code> from datetime import datetime\n import pandas as pd\n\n firstday_month = datetime(year, month, 1)\n lastday_month = firstday_month + pd.offsets.MonthEnd(1)\n</code></pre>\n<p>Another way to do it is: Taking the first day of the month, then adding one month and discounting one day:</p>\n<pre><code> from datetime import datetime\n import pandas as pd\n\n firstday_month = datetime(year, month, 1)\n lastday_month = firstday_month + pd.DateOffset(months=1) - pd.DateOffset(days=1)\n</code></pre>\n"
},
{
"answer_id": 69017505,
"author": "José Florencio de Queiroz",
"author_id": 3372135,
"author_profile": "https://Stackoverflow.com/users/3372135",
"pm_score": 3,
"selected": false,
"text": "<p>That's my way - a function with only two lines:</p>\n<pre><code>from dateutil.relativedelta import relativedelta\n\ndef last_day_of_month(date):\n return date.replace(day=1) + relativedelta(months=1) - relativedelta(days=1)\n</code></pre>\n<p>Example:</p>\n<pre><code>from datetime import date\n\nprint(last_day_of_month(date.today()))\n>> 2021-09-30\n</code></pre>\n"
},
{
"answer_id": 70769732,
"author": "RCN",
"author_id": 16607636,
"author_profile": "https://Stackoverflow.com/users/16607636",
"pm_score": 0,
"selected": false,
"text": "<p>This one worked for me:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df['daysinmonths'] = df['your_date_col'].apply(lambda t: pd.Period(t, freq='S').days_in_month)\n</code></pre>\n<p>took reference from:\n<a href=\"https://stackoverflow.com/a/66403016/16607636\">https://stackoverflow.com/a/66403016/16607636</a></p>\n"
},
{
"answer_id": 71060677,
"author": "J.Wei",
"author_id": 6645051,
"author_profile": "https://Stackoverflow.com/users/6645051",
"pm_score": 3,
"selected": false,
"text": "<p>Using dateutil.relativedelta</p>\n<pre><code>dt + dateutil.relativedelta.relativedelta(months=1, day=1, days=-1)\n</code></pre>\n<p><code>months=1</code> and <code>day=1</code> would shift <code>dt</code> to the first date of next month, then <code>days=-1</code> would shift the new date to previous date which is exactly the last date of current month.</p>\n"
},
{
"answer_id": 71853719,
"author": "Denis Savenko",
"author_id": 5319874,
"author_profile": "https://Stackoverflow.com/users/5319874",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to get the first day of the month with 0:00 time and don't want to import any special library you can write like this</p>\n<pre><code>import pytz\nfrom datetime import datetime, timedelta\n\n# get now time with timezone (optional)\nnow = datetime.now(pytz.UTC)\n\n# get first day on this month, get last day on prev month and after get first day on prev month with min time\nfist_day_with_time = datetime.combine((now.replace(day=1) - timedelta(days=1)).replace(day=1), datetime.min.time())\n</code></pre>\n<p>Works fine with February 28/29, December - January, and another problem date.</p>\n"
},
{
"answer_id": 72643539,
"author": "DanielHefti",
"author_id": 12702595,
"author_profile": "https://Stackoverflow.com/users/12702595",
"pm_score": 0,
"selected": false,
"text": "<p>If it only matters if today is the last day of the month and the date does not really matter, then I prefer to use the condition below.</p>\n<p>The logic is quite simple. If tomorrow is the first day of the next month, then today is the last day of the actual month. Below two examples of an if-else condition.</p>\n<pre><code>from datetime import datetime, timedelta\n\nif (datetime.today()+timedelta(days=1)).day == 1:\n print("today is the last day of the month")\nelse:\n print("today isn't the last day of the month")\n</code></pre>\n<p>If timezone awareness is important.</p>\n<pre><code>from datetime import datetime, timedelta\nimport pytz\n\nset(pytz.all_timezones_set)\ntz = pytz.timezone("Europe/Berlin")\n\ndt = datetime.today().astimezone(tz=tz)\n\nif (dt+timedelta(days=1)).day == 1:\n print("today is the last day of the month")\nelse:\n print("today isn't the last day of the month")\n</code></pre>\n"
},
{
"answer_id": 73032438,
"author": "xor007",
"author_id": 2436995,
"author_profile": "https://Stackoverflow.com/users/2436995",
"pm_score": 0,
"selected": false,
"text": "<p>I think this is more readable than some of the other answers:</p>\n<pre><code>from datetime import timedelta as td\nfrom datetime import datetime as dt\ntoday = dt.now()\na_day_next_month = dt(today.year, today.month, 27) + td(days=5)\nfirst_day_next_month = dt(a_day_next_month.year, a_day_next_month.month, 1)\nlast_day_this_month = first_day_next_month - td(days=1)\n</code></pre>\n"
},
{
"answer_id": 73537730,
"author": "Mr.TK",
"author_id": 2002855,
"author_profile": "https://Stackoverflow.com/users/2002855",
"pm_score": 0,
"selected": false,
"text": "<p>I've managed to find interesting solution here. It's possible to get last day of the month providing those relativedelta args: <code>day=31</code> and <code>days=+1</code>:</p>\n<pre><code>import datetime\nfrom dateutil.relativedelta import relativedelta\n\nday_of_febuary = datetime.datetime(2022, 2, 21)\nlast_day_of_febuary = day_of_febuary + relativedelta(day=31, days=+1, seconds=-1)\nprint(last_day_of_febuary)\n# Output: 2022-02-28 23:59:59\n</code></pre>\n"
},
{
"answer_id": 74011365,
"author": "Amit Pathak",
"author_id": 11608962,
"author_profile": "https://Stackoverflow.com/users/11608962",
"pm_score": 2,
"selected": false,
"text": "<p>My approach:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_last_day_of_month(mon: int, year: int) -> str:\n '''\n Returns last day of the month.\n '''\n\n ### Day 28 falls in every month\n res = datetime(month=mon, year=year, day=28)\n ### Go to next month\n res = res + timedelta(days=4)\n ### Subtract one day from the start of the next month\n res = datetime.strptime(res.strftime('%Y-%m-01'), '%Y-%m-%d') - timedelta(days=1)\n\n return res.strftime('%Y-%m-%d')\n</code></pre>\n<pre class=\"lang-bash prettyprint-override\"><code>>>> get_last_day_of_month(mon=10, year=2022)\n... '2022-10-31'\n</code></pre>\n"
},
{
"answer_id": 74060594,
"author": "Zach Bateman",
"author_id": 15312063,
"author_profile": "https://Stackoverflow.com/users/15312063",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to use a recursive function.</p>\n<p>Is the next day in a different month? If so, then the current day is the last day of the month. If the next day is in the same month, try again using that next day.</p>\n<pre><code>from datetime import timedelta\n\ndef last_day_of_month(date):\n if date.month != (date + timedelta(days=1)).month:\n return date\n else:\n return last_day_of_month(date + timedelta(days=1))\n</code></pre>\n"
},
{
"answer_id": 74284092,
"author": "ramwin",
"author_id": 3601654,
"author_profile": "https://Stackoverflow.com/users/3601654",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"https://github.com/yitistica/month\" rel=\"nofollow noreferrer\">datetime-month</a> package.</p>\n<pre><code>$ pip install datetime-month\n$ python\n>>> from month import XMonth\n>>> Xmonth(2022, 11).last_date()\ndatetime.date(2022, 11, 30)\n</code></pre>\n"
},
{
"answer_id": 74355441,
"author": "Asclepius",
"author_id": 832230,
"author_profile": "https://Stackoverflow.com/users/832230",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't mind using Pandas, using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.days_in_month.html\" rel=\"nofollow noreferrer\"><code>Timestamp.days_in_month</code></a> is probably the simplest:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\n\n> pd.Timestamp(year=2020, month=2, day=1).days_in_month\n\n29\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/42950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] | Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?
If the standard library doesn't support that, does the dateutil package support this? | [`calendar.monthrange`](https://docs.python.org/library/calendar.html#calendar.monthrange) provides this information:
>
> calendar.**monthrange**(year, month)
>
> Returns weekday of first day of the month and number of days in month, for the specified *year* and *month*.
>
>
>
```
>>> import calendar
>>> calendar.monthrange(2002, 1)
(1, 31)
>>> calendar.monthrange(2008, 2) # leap years are handled correctly
(4, 29)
>>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years
(0, 28)
```
so:
```
calendar.monthrange(year, month)[1]
```
seems like the simplest way to go. |
42,966 | <p>What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.</p>
| [
{
"answer_id": 43003,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 3,
"selected": false,
"text": "<p>This is actually fairly easy, especially in terms of showing the \"AutoComplete\" part of it. In terms of remembering the last x number of entries, you are just going to have to decide on a particular event (or events) that you consider as an entry being completed and write that entry off to a list... an AutoCompleteStringCollection to be precise.</p>\n\n<p>The TextBox class has the 3 following properties that you will need:</p>\n\n<ul>\n<li>AutoCompleteCustomSource</li>\n<li>AutoCompleteMode </li>\n<li>AutoCompleteSource</li>\n</ul>\n\n<p>Set AutoCompleteMode to SuggestAppend and AutoCompleteSource to CustomSource.</p>\n\n<p>Then at runtime, every time a new entry is made, use the Add() method of AutoCompleteStringCollection to add that entry to the list (and pop off any old ones if you want). You can actually do this operation directly on the AutoCompleteCustomSource property of the TextBox as long as you've already initialized it.</p>\n\n<p>Now, every time you type in the TextBox it will suggest previous entries :)</p>\n\n<p>See this article for a more complete example: <a href=\"http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx</a></p>\n\n<p>AutoComplete also has some built in features like FileSystem and URLs (though it only does stuff that was typed into IE...)</p>\n"
},
{
"answer_id": 45067,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/42966/google-suggestish-text-box#45014\">@Ethan</a></p>\n\n<p>I forgot about the fact that you would want to save that so it wasn't a per session only thing :P But yes, you are completely correct.</p>\n\n<p>This is easily done, especially since it's just basic strings, just write out the contents of AutoCompleteCustomSource from the TextBox to a text file, on separate lines. </p>\n\n<p>I had a few minutes, so I wrote up a complete code example...I would've before as I always try to show code, but didn't have time. Anyway, here's the whole thing (minus the designer code).</p>\n\n<pre><code>namespace AutoComplete\n{\n public partial class Main : Form\n {\n //so you don't have to address \"txtMain.AutoCompleteCustomSource\" every time\n AutoCompleteStringCollection acsc;\n public Main()\n {\n InitializeComponent();\n\n //Set to use a Custom source\n txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource;\n //Set to show drop down *and* append current suggestion to end\n txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\n //Init string collection.\n acsc = new AutoCompleteStringCollection();\n //Set txtMain's AutoComplete Source to acsc\n txtMain.AutoCompleteCustomSource = acsc;\n }\n\n private void txtMain_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.KeyCode == Keys.Enter)\n {\n //Only keep 10 AutoComplete strings\n if (acsc.Count < 10)\n {\n //Add to collection\n acsc.Add(txtMain.Text);\n }\n else\n {\n //remove oldest\n acsc.RemoveAt(0); \n //Add to collection\n acsc.Add(txtMain.Text);\n }\n }\n }\n\n private void Main_FormClosed(object sender, FormClosedEventArgs e)\n {\n //open stream to AutoComplete save file\n StreamWriter sw = new StreamWriter(\"AutoComplete.acs\");\n\n //Write AutoCompleteStringCollection to stream\n foreach (string s in acsc)\n sw.WriteLine(s);\n\n //Flush to file\n sw.Flush();\n\n //Clean up\n sw.Close();\n sw.Dispose();\n }\n\n private void Main_Load(object sender, EventArgs e)\n {\n //open stream to AutoComplete save file\n StreamReader sr = new StreamReader(\"AutoComplete.acs\");\n\n //initial read\n string line = sr.ReadLine();\n //loop until end\n while (line != null)\n {\n //add to AutoCompleteStringCollection\n acsc.Add(line);\n //read again\n line = sr.ReadLine();\n }\n\n //Clean up\n sr.Close();\n sr.Dispose();\n }\n }\n}\n</code></pre>\n\n<p>This code will work exactly as is, you just need to create the GUI with a TextBox named txtMain and hook up the KeyDown, Closed and Load events to the TextBox and Main form.</p>\n\n<p>Also note that, for this example and to make it simple, I just chose to detect the Enter key being pressed as my trigger to save the string to the collection. There is probably more/different events that would be better, depending on your needs.</p>\n\n<p>Also, the model used for populating the collection is not very \"smart.\" It simply deletes the oldest string when the collection gets to the limit of 10. This is likely not ideal, but works for the example. You would probably want some sort of rating system (especially if you really want it to be Google-ish)</p>\n\n<p>A final note, the suggestions will actually show up in the order they are in the collection. If for some reason you want them to show up differently, just sort the list however you like.</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 1441659,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 1,
"selected": false,
"text": "<p>I store the completion list in the registry. </p>\n\n<p>The code I use is below. It's reusable, in three steps: </p>\n\n<ol>\n<li>replace the namespace and classname in this code with whatever you use.</li>\n<li>Call the FillFormFromRegistry() on the Form's <strong>Load</strong> event, and call SaveFormToRegistry on the <strong>Closing</strong> event. </li>\n<li>compile this into your project. </li>\n</ol>\n\n<p>You need to decorate the assembly with two attributes: <code>[assembly: AssemblyProduct(\"...\")]</code> and <code>[assembly: AssemblyCompany(\"...\")]</code> . (These attributes are normally set automatically in projects created within Visual Studio, so I don't count this as a step.) </p>\n\n<p>Managing state this way is totally automatic and transparent to the user. </p>\n\n<p>You can use the same pattern to store any sort of state for your WPF or WinForms app. Like state of textboxes, checkboxes, dropdowns. Also you can <a href=\"https://stackoverflow.com/questions/937298/restoring-window-size-position-with-multiple-monitors/937465#937465\">store/restore the size of the window</a> - really handy - the next time the user runs the app, it opens in the same place, and with the same size, as when they closed it. You can <a href=\"https://stackoverflow.com/questions/1233841/how-many-times-program-has-run-c/1233867#1233867\">store the number of times an app has been run</a>. Lots of possibilities. </p>\n\n<pre><code>namespace Ionic.ExampleCode\n{\n public partial class NameOfYourForm\n {\n private void SaveFormToRegistry()\n {\n if (AppCuKey != null)\n {\n // the completion list\n var converted = _completions.ToList().ConvertAll(x => x.XmlEscapeIexcl());\n string completionString = String.Join(\"¡\", converted.ToArray());\n AppCuKey.SetValue(_rvn_Completions, completionString);\n }\n }\n\n private void FillFormFromRegistry()\n {\n if (!stateLoaded)\n {\n if (AppCuKey != null)\n {\n // get the MRU list of .... whatever\n _completions = new System.Windows.Forms.AutoCompleteStringCollection();\n string c = (string)AppCuKey.GetValue(_rvn_Completions, \"\");\n if (!String.IsNullOrEmpty(c))\n {\n string[] items = c.Split('¡');\n if (items != null && items.Length > 0)\n {\n //_completions.AddRange(items);\n foreach (string item in items)\n _completions.Add(item.XmlUnescapeIexcl());\n }\n }\n\n // Can also store/retrieve items in the registry for\n // - textbox contents\n // - checkbox state\n // - splitter state\n // - and so on\n //\n stateLoaded = true;\n }\n }\n }\n\n private Microsoft.Win32.RegistryKey AppCuKey\n {\n get\n {\n if (_appCuKey == null)\n {\n _appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegistryPath, true);\n if (_appCuKey == null)\n _appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegistryPath);\n }\n return _appCuKey;\n }\n set { _appCuKey = null; }\n }\n\n private string _appRegistryPath;\n private string AppRegistryPath\n {\n get\n {\n if (_appRegistryPath == null)\n {\n // Use a registry path that depends on the assembly attributes,\n // that are presumed to be elsewhere. Example:\n // \n // [assembly: AssemblyCompany(\"Dino Chiesa\")]\n // [assembly: AssemblyProduct(\"XPathVisualizer\")]\n\n var a = System.Reflection.Assembly.GetExecutingAssembly();\n object[] attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true);\n var p = attr[0] as System.Reflection.AssemblyProductAttribute;\n attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), true);\n var c = attr[0] as System.Reflection.AssemblyCompanyAttribute;\n\n _appRegistryPath = String.Format(\"Software\\\\{0}\\\\{1}\",\n p.Product, c.Company);\n }\n return _appRegistryPath;\n }\n }\n\n private Microsoft.Win32.RegistryKey _appCuKey;\n private string _rvn_Completions = \"Completions\";\n private readonly int _MaxMruListSize = 14;\n private System.Windows.Forms.AutoCompleteStringCollection _completions;\n private bool stateLoaded;\n }\n\n public static class Extensions\n {\n public static string XmlEscapeIexcl(this String s)\n {\n while (s.Contains(\"¡\"))\n {\n s = s.Replace(\"¡\", \"&#161;\");\n }\n return s;\n }\n public static string XmlUnescapeIexcl(this String s)\n {\n while (s.Contains(\"&#161;\"))\n {\n s = s.Replace(\"&#161;\", \"¡\");\n }\n return s;\n }\n\n public static List<String> ToList(this System.Windows.Forms.AutoCompleteStringCollection coll)\n {\n var list = new List<String>();\n foreach (string item in coll)\n {\n list.Add(item);\n }\n return list;\n }\n }\n}\n</code></pre>\n\n<p>Some people <a href=\"http://www.codinghorror.com/blog/archives/000939.html\" rel=\"nofollow noreferrer\">shy away from using the Registry for storing state</a>, but I find it's really easy and convenient. If you like, You can very easily build an installer that removes all the registry keys on uninstall. </p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/42966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066/"
] | What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#. | [@Ethan](https://stackoverflow.com/questions/42966/google-suggestish-text-box#45014)
I forgot about the fact that you would want to save that so it wasn't a per session only thing :P But yes, you are completely correct.
This is easily done, especially since it's just basic strings, just write out the contents of AutoCompleteCustomSource from the TextBox to a text file, on separate lines.
I had a few minutes, so I wrote up a complete code example...I would've before as I always try to show code, but didn't have time. Anyway, here's the whole thing (minus the designer code).
```
namespace AutoComplete
{
public partial class Main : Form
{
//so you don't have to address "txtMain.AutoCompleteCustomSource" every time
AutoCompleteStringCollection acsc;
public Main()
{
InitializeComponent();
//Set to use a Custom source
txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource;
//Set to show drop down *and* append current suggestion to end
txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//Init string collection.
acsc = new AutoCompleteStringCollection();
//Set txtMain's AutoComplete Source to acsc
txtMain.AutoCompleteCustomSource = acsc;
}
private void txtMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Only keep 10 AutoComplete strings
if (acsc.Count < 10)
{
//Add to collection
acsc.Add(txtMain.Text);
}
else
{
//remove oldest
acsc.RemoveAt(0);
//Add to collection
acsc.Add(txtMain.Text);
}
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
//open stream to AutoComplete save file
StreamWriter sw = new StreamWriter("AutoComplete.acs");
//Write AutoCompleteStringCollection to stream
foreach (string s in acsc)
sw.WriteLine(s);
//Flush to file
sw.Flush();
//Clean up
sw.Close();
sw.Dispose();
}
private void Main_Load(object sender, EventArgs e)
{
//open stream to AutoComplete save file
StreamReader sr = new StreamReader("AutoComplete.acs");
//initial read
string line = sr.ReadLine();
//loop until end
while (line != null)
{
//add to AutoCompleteStringCollection
acsc.Add(line);
//read again
line = sr.ReadLine();
}
//Clean up
sr.Close();
sr.Dispose();
}
}
}
```
This code will work exactly as is, you just need to create the GUI with a TextBox named txtMain and hook up the KeyDown, Closed and Load events to the TextBox and Main form.
Also note that, for this example and to make it simple, I just chose to detect the Enter key being pressed as my trigger to save the string to the collection. There is probably more/different events that would be better, depending on your needs.
Also, the model used for populating the collection is not very "smart." It simply deletes the oldest string when the collection gets to the limit of 10. This is likely not ideal, but works for the example. You would probably want some sort of rating system (especially if you really want it to be Google-ish)
A final note, the suggestions will actually show up in the order they are in the collection. If for some reason you want them to show up differently, just sort the list however you like.
Hope that helps! |
42,980 | <p>Does anyone know how to setup <a href="http://www.selenic.com/mercurial/wiki/index.cgi/Mercurial" rel="noreferrer">Mercurial</a> to use <a href="http://www.perforce.com/perforce/products/merge.html" rel="noreferrer">p4merge</a> as the merge/diff tool on OS X 10.5?</p>
| [
{
"answer_id": 43241,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 0,
"selected": false,
"text": "<p>I'm guessing there's a CLI tool for p4merge (which I know nothing about).</p>\n\n<p>I wrote a blog post about using Changes.app, and some other GUI tools with Mercurial: <a href=\"http://schinckel.net/2008/04/26/mercurial-with-os-x-gui-tools/\" rel=\"nofollow noreferrer\">Using Mercurial with GUI Tools.</a></p>\n\n<p>Basically, you need to know the calling expectations of the CLI tool that loads up the diff tool. IE, how to make it load data from a particular file, and how to make it wait for exit. There should be enough info on the post to give you some ideas.</p>\n"
},
{
"answer_id": 54261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I use the following bit of Python to launch p4merge and use it with git :</p>\n\n<pre><code>#!/usr/bin/python\nimport sys\nimport os\n\nos.system('/Applications/p4merge.app/Contents/MacOS/p4merge \"%s\" \"%s\"' % (sys.argv[2], sys.argv[5]))\n</code></pre>\n\n<p>I'm not sure how mercurial looks to launch an external diff tool though ? Hopefully it's as simple as adjusting 2 & 5 in the above line to being the index of the arguments for 'checked in' and 'current working copy'.</p>\n"
},
{
"answer_id": 170637,
"author": "Ry4an Brase",
"author_id": 8992,
"author_profile": "https://Stackoverflow.com/users/8992",
"pm_score": 5,
"selected": false,
"text": "<p><strong>This will work for merging:</strong></p>\n\n<p>Place this into your <code>~/.hgrc</code> (or, optionally, your <code>Mercurial.ini</code> on Windows):</p>\n\n<pre><code>[merge-tools]\np4.priority = 100\np4.premerge = True # change this to False if you're don't trust hg's internal merge\np4.executable = /Applications/p4merge.app/Contents/MacOS/p4merge\np4.gui = True\np4.args = $base $local $other $output\n</code></pre>\n\n<p>Requires Mercurial 1.0 or newer. Clearly you'll need to update the path to that executable to reflect where you'd got p4merge installed.</p>\n\n<hr>\n\n<p><strong>You can't change what <code>hg diff</code> uses</strong>; but you <em>can</em> use the <code>extdiff</code> extension to create new diff commands that use the display you want. </p>\n\n<p>So <code>hg pdiff</code> could run p4 merge, etc.</p>\n"
},
{
"answer_id": 399092,
"author": "Ivan",
"author_id": 50135,
"author_profile": "https://Stackoverflow.com/users/50135",
"pm_score": 4,
"selected": false,
"text": "<p>I found <a href=\"https://stackoverflow.com/questions/42980/how-to-use-p4merge-as-the-mergediff-tool-for-mercurial#170637\">Ry4an's answer</a> to be a good solution, except for a minor problem, which left p4merge (under mac os) mixing up the command inputs. <strong>Do everything described in <a href=\"https://stackoverflow.com/questions/42980/how-to-use-p4merge-as-the-mergediff-tool-for-mercurial#170637\">his answer</a> and add the following line in the [merge-tools] section</strong>:</p>\n\n<pre><code>p4.args=$base $local $other $output\n</code></pre>\n\n<p>This line tells mercurial in which order p4merge takes its arguments.</p>\n"
},
{
"answer_id": 2311268,
"author": "gnz",
"author_id": 269335,
"author_profile": "https://Stackoverflow.com/users/269335",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe because I'm working on Windows, but the proposed solution didn't work for me. Instead, the following does work.</p>\n\n<p>In your <code>~/.hgrc/</code> / <code>Mercurial.ini</code>, I applied the following changes:</p>\n\n<p>Enabled \"ExtDiff\" extension:</p>\n\n<pre><code>[extensions]\nhgext.extdiff =\n</code></pre>\n\n<p>Added P4 extdiff command:</p>\n\n<pre><code>[extdiff]\ncmd.p4diff = p4merge\n</code></pre>\n\n<p>Configured it as the default visual diff tool:</p>\n\n<pre><code>[tortoisehg]\nvdiff = p4diff\n</code></pre>\n"
},
{
"answer_id": 3779528,
"author": "macrobug",
"author_id": 226508,
"author_profile": "https://Stackoverflow.com/users/226508",
"pm_score": 4,
"selected": false,
"text": "<p>I am using version 1.0.1 of TortoiseHg and p4merge works out of the box.</p>\n\n<p>Just go to <em>Global Settings -> TortoiseHg</em> and select the following options:</p>\n\n<ul>\n<li>Three-way Merge Tool: p4merge</li>\n<li>Visual Diff Tool: p4merge</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/LQH39.png\" alt=\"Screenshot\"></p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/42980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3547/"
] | Does anyone know how to setup [Mercurial](http://www.selenic.com/mercurial/wiki/index.cgi/Mercurial) to use [p4merge](http://www.perforce.com/perforce/products/merge.html) as the merge/diff tool on OS X 10.5? | **This will work for merging:**
Place this into your `~/.hgrc` (or, optionally, your `Mercurial.ini` on Windows):
```
[merge-tools]
p4.priority = 100
p4.premerge = True # change this to False if you're don't trust hg's internal merge
p4.executable = /Applications/p4merge.app/Contents/MacOS/p4merge
p4.gui = True
p4.args = $base $local $other $output
```
Requires Mercurial 1.0 or newer. Clearly you'll need to update the path to that executable to reflect where you'd got p4merge installed.
---
**You can't change what `hg diff` uses**; but you *can* use the `extdiff` extension to create new diff commands that use the display you want.
So `hg pdiff` could run p4 merge, etc. |
42,990 | <p>I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.</p>
<p>Example:</p>
<pre><code>// Updated to be correct, thanks @Apocalisp
^foo.*(?<!bar)$
</code></pre>
<p>Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters. </p>
<p>I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too. </p>
<p>Thanks to @Kibbee for verifying that this works in C# as well. </p>
| [
{
"answer_id": 43010,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not familiar with Java regex but documentation for the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html#special\" rel=\"nofollow noreferrer\">Pattern Class</a> would suggest you could use (?!X) for a non-capturing zero-width negative lookahead (it looks for something that is not X at that postision, without capturing it as a backreference). So you could do:</p>\n\n<pre><code>foo.*(?!bar) // not correct\n</code></pre>\n\n<p><strong>Update</strong>: Apocalisp's right, you want negative lookbehind. (you're checking that what the .* matches doesn't end with bar)</p>\n"
},
{
"answer_id": 43016,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>As other commenters said, you need a negative lookahead. In Java you can use this pattern:</p>\n\n<pre><code>\"^first_string(?!.?second_string)\\\\z\"\n</code></pre>\n\n<ul>\n<li>^ - ensures that string starts with\nfirst_string</li>\n<li>\\z - ensures that string ends with second_string</li>\n<li>(?!.?second_string) - means that first_string can't be followed by second_string</li>\n</ul>\n"
},
{
"answer_id": 43017,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 4,
"selected": true,
"text": "<p>I think in this case you want <strong>negative lookbehind</strong>, like so:</p>\n\n<pre><code>foo.*(?<!bar)\n</code></pre>\n"
},
{
"answer_id": 43030,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 1,
"selected": false,
"text": "<p>Verified @Apocalisp's answer using:</p>\n\n<pre><code>import java.util.regex.Pattern;\npublic class Test {\n public static void main(String[] args) {\n Pattern p = Pattern.compile(\"^foo.*(?<!bar)$\");\n System.out.println(p.matcher(\"foobar\").matches());\n System.out.println(p.matcher(\"fooBLAHbar\").matches());\n System.out.println(p.matcher(\"1foo\").matches());\n System.out.println(p.matcher(\"fooBLAH-ar\").matches());\n System.out.println(p.matcher(\"foo\").matches());\n System.out.println(p.matcher(\"foobaz\").matches());\n }\n}\n</code></pre>\n\n<p>This output the the right answers:</p>\n\n<pre><code>false\nfalse\nfalse\ntrue\ntrue\ntrue\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/42990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
] | I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.
Example:
```
// Updated to be correct, thanks @Apocalisp
^foo.*(?<!bar)$
```
Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters.
I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too.
Thanks to @Kibbee for verifying that this works in C# as well. | I think in this case you want **negative lookbehind**, like so:
```
foo.*(?<!bar)
``` |
43,021 | <p>Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?</p>
<p>For instance, I currently do something like this depending on the circumstances:</p>
<pre><code>int i = 0;
foreach (Object o in collection)
{
// ...
i++;
}
</code></pre>
| [
{
"answer_id": 43026,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 2,
"selected": false,
"text": "<p>Unless your collection can return the index of the object via some method, the only way is to use a counter like in your example.</p>\n\n<p>However, when working with indexes, the only reasonable answer to the problem is to use a for loop. Anything else introduces code complexity, not to mention time and space complexity.</p>\n"
},
{
"answer_id": 43028,
"author": "bryansh",
"author_id": 211367,
"author_profile": "https://Stackoverflow.com/users/211367",
"pm_score": 2,
"selected": false,
"text": "<p>I don't believe there is a way to get the value of the current iteration of a foreach loop. Counting yourself, seems to be the best way.</p>\n\n<p>May I ask, why you would want to know?</p>\n\n<p>It seems that you would most likley be doing one of three things:</p>\n\n<p>1) Getting the object from the collection, but in this case you already have it.</p>\n\n<p>2) Counting the objects for later post processing...the collections have a Count property that you could make use of.</p>\n\n<p>3) Setting a property on the object based on its order in the loop...although you could easily be setting that when you added the object to the collection.</p>\n"
},
{
"answer_id": 43029,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 10,
"selected": true,
"text": "<p>The <code>foreach</code> is for iterating over collections that implement <a href=\"http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>IEnumerable</code></a>. It does this by calling <a href=\"http://msdn.microsoft.com/en-us/library/s793z9y2(v=vs.110).aspx\" rel=\"noreferrer\"><code>GetEnumerator</code></a> on the collection, which will return an <a href=\"http://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx\" rel=\"noreferrer\"><code>Enumerator</code></a>.</p>\n<p>This Enumerator has a method and a property:</p>\n<ul>\n<li><code>MoveNext()</code></li>\n<li><code>Current</code></li>\n</ul>\n<p><code>Current</code> returns the object that Enumerator is currently on, <code>MoveNext</code> updates <code>Current</code> to the next object.</p>\n<p>The concept of an index is foreign to the concept of enumeration, and cannot be done.</p>\n<p>Because of that, most collections are able to be traversed using an indexer and the for loop construct.</p>\n<p>I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.</p>\n"
},
{
"answer_id": 43035,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 7,
"selected": false,
"text": "<p>Could do something like this:</p>\n\n<pre><code>public static class ForEachExtensions\n{\n public static void ForEachWithIndex<T>(this IEnumerable<T> enumerable, Action<T, int> handler)\n {\n int idx = 0;\n foreach (T item in enumerable)\n handler(item, idx++);\n }\n}\n\npublic class Example\n{\n public static void Main()\n {\n string[] values = new[] { \"foo\", \"bar\", \"baz\" };\n\n values.ForEachWithIndex((item, idx) => Console.WriteLine(\"{0}: {1}\", idx, item));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43103,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 4,
"selected": false,
"text": "<p>It's only going to work for a List and not any IEnumerable, but in LINQ there's this:</p>\n\n<pre><code>IList<Object> collection = new List<Object> { \n new Object(), \n new Object(), \n new Object(), \n };\n\nforeach (Object o in collection)\n{\n Console.WriteLine(collection.IndexOf(o));\n}\n\nConsole.ReadLine();\n</code></pre>\n\n<p>@Jonathan I didn't say it was a great answer, I just said it was just showing it was possible to do what he asked :)</p>\n\n<p>@Graphain I wouldn't expect it to be fast - I'm not entirely sure how it works, it could reiterate through the entire list each time to find a matching object, which would be a helluvalot of compares.</p>\n\n<p>That said, List might keep an index of each object along with the count.</p>\n\n<p>Jonathan seems to have a better idea, if he would elaborate?</p>\n\n<p>It would be better to just keep a count of where you're up to in the foreach though, simpler, and more adaptable.</p>\n"
},
{
"answer_id": 77542,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 6,
"selected": false,
"text": "<p>Literal Answer -- warning, performance may not be as good as just using an <code>int</code> to track the index. At least it is better than using <code>IndexOf</code>.</p>\n\n<p>You just need to use the indexing overload of Select to wrap each item in the collection with an anonymous object that knows the index. This can be done against anything that implements IEnumerable.</p>\n\n<pre><code>System.Collections.IEnumerable collection = Enumerable.Range(100, 10);\n\nforeach (var o in collection.OfType<object>().Select((x, i) => new {x, i}))\n{\n Console.WriteLine(\"{0} {1}\", o.i, o.x);\n}\n</code></pre>\n"
},
{
"answer_id": 1046748,
"author": "mike nelson",
"author_id": 23616,
"author_profile": "https://Stackoverflow.com/users/23616",
"pm_score": 7,
"selected": false,
"text": "<p>I disagree with comments that a <code>for</code> loop is a better choice in most cases. </p>\n\n<p><code>foreach</code> is a useful construct, and not replaceble by a <code>for</code> loop in all circumstances. </p>\n\n<p>For example, if you have a <strong>DataReader</strong> and loop through all records using a <code>foreach</code> it automatically calls the <strong>Dispose</strong> method and closes the reader (which can then close the connection automatically). This is therefore safer as it prevents connection leaks even if you forget to close the reader. </p>\n\n<p>(Sure it is good practise to always close readers but the compiler is not going to catch it if you don't - you can't guarantee you have closed all readers but you can make it more likely you won't leak connections by getting in the habit of using foreach.)</p>\n\n<p>There may be other examples of the implicit call of the <code>Dispose</code> method being useful.</p>\n"
},
{
"answer_id": 1984049,
"author": "mat3",
"author_id": 173472,
"author_profile": "https://Stackoverflow.com/users/173472",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a solution I just came up with for this problem</p>\n\n<p><strong>Original code:</strong></p>\n\n<pre><code>int index=0;\nforeach (var item in enumerable)\n{\n blah(item, index); // some code that depends on the index\n index++;\n}\n</code></pre>\n\n<p><strong>Updated code</strong></p>\n\n<pre><code>enumerable.ForEach((item, index) => blah(item, index));\n</code></pre>\n\n<p><strong>Extension Method:</strong></p>\n\n<pre><code> public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action)\n {\n var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void\n enumerable.Select((item, i) => \n {\n action(item, i);\n return unit;\n }).ToList();\n\n return pSource;\n }\n</code></pre>\n"
},
{
"answer_id": 1985112,
"author": "Sachin",
"author_id": 149656,
"author_profile": "https://Stackoverflow.com/users/149656",
"pm_score": 3,
"selected": false,
"text": "<pre><code>int index;\nforeach (Object o in collection)\n{\n index = collection.indexOf(o);\n}\n</code></pre>\n\n<p>This would work for collections supporting <code>IList</code>.</p>\n"
},
{
"answer_id": 3293486,
"author": "Brian Gideon",
"author_id": 158779,
"author_profile": "https://Stackoverflow.com/users/158779",
"pm_score": 5,
"selected": false,
"text": "<p>You could wrap the original enumerator with another that does contain the index information.</p>\n\n<pre><code>foreach (var item in ForEachHelper.WithIndex(collection))\n{\n Console.Write(\"Index=\" + item.Index);\n Console.Write(\";Value= \" + item.Value);\n Console.Write(\";IsLast=\" + item.IsLast);\n Console.WriteLine();\n}\n</code></pre>\n\n<p>Here is the code for the <code>ForEachHelper</code> class.</p>\n\n<pre><code>public static class ForEachHelper\n{\n public sealed class Item<T>\n {\n public int Index { get; set; }\n public T Value { get; set; }\n public bool IsLast { get; set; }\n }\n\n public static IEnumerable<Item<T>> WithIndex<T>(IEnumerable<T> enumerable)\n {\n Item<T> item = null;\n foreach (T value in enumerable)\n {\n Item<T> next = new Item<T>();\n next.Index = 0;\n next.Value = value;\n next.IsLast = false;\n if (item != null)\n {\n next.Index = item.Index + 1;\n yield return item;\n }\n item = next;\n }\n if (item != null)\n {\n item.IsLast = true;\n yield return item;\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 3535307,
"author": "user426810",
"author_id": 426810,
"author_profile": "https://Stackoverflow.com/users/426810",
"pm_score": 3,
"selected": false,
"text": "<p>Better to use keyword <code>continue</code> safe construction like this</p>\n\n<pre><code>int i=-1;\nforeach (Object o in collection)\n{\n ++i;\n //...\n continue; //<--- safe to call, index will be increased\n //...\n}\n</code></pre>\n"
},
{
"answer_id": 3535362,
"author": "Ian Henry",
"author_id": 223274,
"author_profile": "https://Stackoverflow.com/users/223274",
"pm_score": 3,
"selected": false,
"text": "<p>This is how I do it, which is nice for its simplicity/brevity, but if you're doing a lot in the loop body <code>obj.Value</code>, it is going to get old pretty fast.</p>\n\n<pre><code>foreach(var obj in collection.Select((item, index) => new { Index = index, Value = item }) {\n string foo = string.Format(\"Something[{0}] = {1}\", obj.Index, obj.Value);\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 3691283,
"author": "ulrichb",
"author_id": 50890,
"author_profile": "https://Stackoverflow.com/users/50890",
"pm_score": 2,
"selected": false,
"text": "<p>My solution for this problem is an extension method <code>WithIndex()</code>,</p>\n\n<p><a href=\"http://code.google.com/p/ub-dotnet-utilities/source/browse/trunk/Src/Utilities/Extensions/EnumerableExtensions.cs\" rel=\"nofollow noreferrer\">http://code.google.com/p/ub-dotnet-utilities/source/browse/trunk/Src/Utilities/Extensions/EnumerableExtensions.cs</a></p>\n\n<p><strong>Use it like</strong></p>\n\n<pre><code>var list = new List<int> { 1, 2, 3, 4, 5, 6 }; \n\nvar odd = list.WithIndex().Where(i => (i.Item & 1) == 1);\nCollectionAssert.AreEqual(new[] { 0, 2, 4 }, odd.Select(i => i.Index));\nCollectionAssert.AreEqual(new[] { 1, 3, 5 }, odd.Select(i => i.Item));\n</code></pre>\n"
},
{
"answer_id": 4055002,
"author": "Matt Towers",
"author_id": 491656,
"author_profile": "https://Stackoverflow.com/users/491656",
"pm_score": 1,
"selected": false,
"text": "<p>How about something like this? Note that myDelimitedString may be null if myEnumerable is empty.</p>\n\n<pre><code>IEnumerator enumerator = myEnumerable.GetEnumerator();\nstring myDelimitedString;\nstring current = null;\n\nif( enumerator.MoveNext() )\n current = (string)enumerator.Current;\n\nwhile( null != current)\n{\n current = (string)enumerator.Current; }\n\n myDelimitedString += current;\n\n if( enumerator.MoveNext() )\n myDelimitedString += DELIMITER;\n else\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 5405140,
"author": "nicodemus13",
"author_id": 26463,
"author_profile": "https://Stackoverflow.com/users/26463",
"pm_score": 2,
"selected": false,
"text": "<p>I just had this problem, but thinking around the problem in my case gave the best solution, unrelated to the expected solution.</p>\n\n<p>It could be quite a common case, basically, I'm reading from one source list and creating objects based on them in a destination list, however, I have to check whether the source items are valid first and want to return the row of any error. At first-glance, I want to get the index into the enumerator of the object at the Current property, however, as I am copying these elements, I implicitly know the current index anyway from the current destination. Obviously it depends on your destination object, but for me it was a List, and most likely it will implement ICollection.</p>\n\n<p>i.e.</p>\n\n<pre><code>var destinationList = new List<someObject>();\nforeach (var item in itemList)\n{\n var stringArray = item.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);\n\n if (stringArray.Length != 2)\n {\n //use the destinationList Count property to give us the index into the stringArray list\n throw new Exception(\"Item at row \" + (destinationList.Count + 1) + \" has a problem.\");\n }\n else\n {\n destinationList.Add(new someObject() { Prop1 = stringArray[0], Prop2 = stringArray[1]});\n }\n}\n</code></pre>\n\n<p>Not always applicable, but often enough to be worth mentioning, I think.</p>\n\n<p>Anyway, the point being that sometimes there is a non-obvious solution already in the logic you have...</p>\n"
},
{
"answer_id": 5709974,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 2,
"selected": false,
"text": "<p>For interest, Phil Haack just wrote an example of this in the context of a Razor Templated Delegate (<a href=\"http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx\" rel=\"nofollow\">http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx</a>)</p>\n\n<p>Effectively he writes an extension method which wraps the iteration in an \"IteratedItem\" class (see below) allowing access to the index as well as the element during iteration.</p>\n\n<pre><code>public class IndexedItem<TModel> {\n public IndexedItem(int index, TModel item) {\n Index = index;\n Item = item;\n }\n\n public int Index { get; private set; }\n public TModel Item { get; private set; }\n}\n</code></pre>\n\n<p>However, while this would be fine in a non-Razor environment if you are doing a single operation (i.e. one that could be provided as a lambda) it's not going to be a solid replacement of the for/foreach syntax in non-Razor contexts.</p>\n"
},
{
"answer_id": 7421615,
"author": "Kasey Speakman",
"author_id": 209133,
"author_profile": "https://Stackoverflow.com/users/209133",
"pm_score": 2,
"selected": false,
"text": "<p>I wasn't sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even.</p>\n\n<pre><code>string[] names = { \"one\", \"two\", \"three\" };\nvar oddOrEvenByName = names\n .Select((name, index) => new KeyValuePair<string, int>(name, index % 2))\n .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);\n</code></pre>\n\n<p>This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list.</p>\n"
},
{
"answer_id": 11437562,
"author": "bcahill",
"author_id": 474902,
"author_profile": "https://Stackoverflow.com/users/474902",
"pm_score": 10,
"selected": false,
"text": "<p>Ian Mercer posted a similar solution as this on <a href=\"http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx\" rel=\"noreferrer\">Phil Haack's blog</a>:</p>\n<pre><code>foreach (var item in Model.Select((value, i) => new { i, value }))\n{\n var value = item.value;\n var index = item.i;\n}\n</code></pre>\n<p>This gets you the item (<code>item.value</code>) and its index (<code>item.i</code>) by using <a href=\"https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx\" rel=\"noreferrer\">this overload of LINQ's <code>Select</code></a>:</p>\n<blockquote>\n<p>the second parameter of the function [inside Select] represents the index of the source element.</p>\n</blockquote>\n<p>The <code>new { i, value }</code> is creating a new <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types\" rel=\"noreferrer\">anonymous object</a>.</p>\n<p>Heap allocations can be avoided by using <code>ValueTuple</code> if you're using C# 7.0 or later:</p>\n<pre><code>foreach (var item in Model.Select((value, i) => ( value, i )))\n{\n var value = item.value;\n var index = item.i;\n}\n</code></pre>\n<p>You can also eliminate the <code>item.</code> by using automatic destructuring:</p>\n<pre><code>foreach (var (value, i) in Model.Select((value, i) => ( value, i )))\n{\n // Access `value` and `i` directly here.\n}\n</code></pre>\n"
},
{
"answer_id": 15572052,
"author": "Bart Calixto",
"author_id": 826568,
"author_profile": "https://Stackoverflow.com/users/826568",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think this should be quite efficient, but it works:</p>\n\n<pre><code>@foreach (var banner in Model.MainBanners) {\n @Model.MainBanners.IndexOf(banner)\n}\n</code></pre>\n"
},
{
"answer_id": 15889868,
"author": "mike nelson",
"author_id": 23616,
"author_profile": "https://Stackoverflow.com/users/23616",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another solution to this problem, with a focus on keeping the syntax as close to a standard <code>foreach</code> as possible. </p>\n\n<p>This sort of construct is useful if you are wanting to make your views look nice and clean in MVC. For example instead of writing this the usual way (which is hard to format nicely):</p>\n\n<pre><code> <%int i=0;\n foreach (var review in Model.ReviewsList) { %>\n <div id=\"review_<%=i%>\">\n <h3><%:review.Title%></h3> \n </div>\n <%i++;\n } %>\n</code></pre>\n\n<p>You could instead write this:</p>\n\n<pre><code> <%foreach (var review in Model.ReviewsList.WithIndex()) { %>\n <div id=\"review_<%=LoopHelper.Index()%>\">\n <h3><%:review.Title%></h3> \n </div>\n <%} %>\n</code></pre>\n\n<p>I've written some helper methods to enable this:</p>\n\n<pre><code>public static class LoopHelper {\n public static int Index() {\n return (int)HttpContext.Current.Items[\"LoopHelper_Index\"];\n } \n}\n\npublic static class LoopHelperExtensions {\n public static IEnumerable<T> WithIndex<T>(this IEnumerable<T> that) {\n return new EnumerableWithIndex<T>(that);\n }\n\n public class EnumerableWithIndex<T> : IEnumerable<T> {\n public IEnumerable<T> Enumerable;\n\n public EnumerableWithIndex(IEnumerable<T> enumerable) {\n Enumerable = enumerable;\n }\n\n public IEnumerator<T> GetEnumerator() {\n for (int i = 0; i < Enumerable.Count(); i++) {\n HttpContext.Current.Items[\"LoopHelper_Index\"] = i;\n yield return Enumerable.ElementAt(i);\n }\n }\n\n IEnumerator IEnumerable.GetEnumerator() {\n return GetEnumerator();\n }\n }\n</code></pre>\n\n<p>In a non-web environment you could use a <code>static</code> instead of <code>HttpContext.Current.Items</code>.</p>\n\n<p>This is essentially a global variable, and so you cannot have more than one WithIndex loop nested, but that is not a major problem in this use case.</p>\n"
},
{
"answer_id": 19236156,
"author": "Gezim",
"author_id": 32495,
"author_profile": "https://Stackoverflow.com/users/32495",
"pm_score": 5,
"selected": false,
"text": "<p>Using @FlySwat's answer, I came up with this solution:</p>\n\n<pre><code>//var list = new List<int> { 1, 2, 3, 4, 5, 6 }; // Your sample collection\n\nvar listEnumerator = list.GetEnumerator(); // Get enumerator\n\nfor (var i = 0; listEnumerator.MoveNext() == true; i++)\n{\n int currentItem = listEnumerator.Current; // Get current item.\n //Console.WriteLine(\"At index {0}, item is {1}\", i, currentItem); // Do as you wish with i and currentItem\n}\n</code></pre>\n\n<p>You get the enumerator using <code>GetEnumerator</code> and then you loop using a <code>for</code> loop. However, the trick is to make the loop's condition <code>listEnumerator.MoveNext() == true</code>.</p>\n\n<p>Since the <code>MoveNext</code> method of an enumerator returns true if there is a next element and it can be accessed, making that the loop condition makes the loop stop when we run out of elements to iterate over.</p>\n"
},
{
"answer_id": 19594773,
"author": "Warren LaFrance",
"author_id": 1404405,
"author_profile": "https://Stackoverflow.com/users/1404405",
"pm_score": 2,
"selected": false,
"text": "<p>I built this in <a href=\"https://en.wikipedia.org/wiki/LINQPad\" rel=\"nofollow\">LINQPad</a>:</p>\n\n<pre><code>var listOfNames = new List<string>(){\"John\",\"Steve\",\"Anna\",\"Chris\"};\n\nvar listCount = listOfNames.Count;\n\nvar NamesWithCommas = string.Empty;\n\nforeach (var element in listOfNames)\n{\n NamesWithCommas += element;\n if(listOfNames.IndexOf(element) != listCount -1)\n {\n NamesWithCommas += \", \";\n }\n}\n\nNamesWithCommas.Dump(); //LINQPad method to write to console.\n</code></pre>\n\n<p>You could also just use <code>string.join</code>:</p>\n\n<pre><code>var joinResult = string.Join(\",\", listOfNames);\n</code></pre>\n"
},
{
"answer_id": 22016592,
"author": "David Bullock",
"author_id": 463052,
"author_profile": "https://Stackoverflow.com/users/463052",
"pm_score": 6,
"selected": false,
"text": "<p>There's nothing wrong with using a counter variable. In fact, whether you use <code>for</code>, <code>foreach</code> <code>while</code> or <code>do</code>, a counter variable must somewhere be declared and incremented.</p>\n\n<p>So use this idiom if you're not sure if you have a suitably-indexed collection:</p>\n\n<pre><code>var i = 0;\nforeach (var e in collection) {\n // Do stuff with 'e' and 'i'\n i++;\n}\n</code></pre>\n\n<p>Else use this one if you <em>know</em> that your <em>indexable</em> collection is O(1) for index access (which it will be for <code>Array</code> and probably for <code>List<T></code> (the documentation doesn't say), but not necessarily for other types (such as <code>LinkedList</code>)):</p>\n\n<pre><code>// Hope the JIT compiler optimises read of the 'Count' property!\nfor (var i = 0; i < collection.Count; i++) {\n var e = collection[i];\n // Do stuff with 'e' and 'i'\n}\n</code></pre>\n\n<p>It should never be necessary to 'manually' operate the <code>IEnumerator</code> by invoking <code>MoveNext()</code> and interrogating <code>Current</code> - <code>foreach</code> is saving you that particular bother ... if you need to skip items, just use a <code>continue</code> in the body of the loop.</p>\n\n<p>And just for completeness, depending on what you were <em>doing</em> with your index (the above constructs offer plenty of flexibility), you might use Parallel LINQ:</p>\n\n<pre><code>// First, filter 'e' based on 'i',\n// then apply an action to remaining 'e'\ncollection\n .AsParallel()\n .Where((e,i) => /* filter with e,i */)\n .ForAll(e => { /* use e, but don't modify it */ });\n\n// Using 'e' and 'i', produce a new collection,\n// where each element incorporates 'i'\ncollection\n .AsParallel()\n .Select((e, i) => new MyWrapper(e, i));\n</code></pre>\n\n<p>We use <code>AsParallel()</code> above, because it's 2014 already, and we want to make good use of those multiple cores to speed things up. Further, for 'sequential' LINQ, <a href=\"https://stackoverflow.com/questions/101265/why-is-there-not-a-foreach-extension-method-on-the-ienumerable-interface\">you only get a <code>ForEach()</code> extension method on <code>List<T></code> and <code>Array</code></a> ... and it's not clear that using it is any better than doing a simple <code>foreach</code>, since you are still running single-threaded for uglier syntax.</p>\n"
},
{
"answer_id": 27785300,
"author": "ssaeed",
"author_id": 3256077,
"author_profile": "https://Stackoverflow.com/users/3256077",
"pm_score": 2,
"selected": false,
"text": "<p>If the collection is a list, you can use List.IndexOf, as in:</p>\n\n<pre><code>foreach (Object o in collection)\n{\n // ...\n @collection.IndexOf(o)\n}\n</code></pre>\n"
},
{
"answer_id": 33508983,
"author": "BenKoshy",
"author_id": 4880924,
"author_profile": "https://Stackoverflow.com/users/4880924",
"pm_score": 0,
"selected": false,
"text": "<p>This doesn't answer your specific question, but it DOES provide you with a solution to your problem: use a for loop to run through the object collection. then you will have the current index you are working on.</p>\n\n<pre><code>// Untested\nfor (int i = 0; i < collection.Count; i++)\n{\n Console.WriteLine(\"My index is \" + i);\n}\n</code></pre>\n"
},
{
"answer_id": 37471479,
"author": "Parsa",
"author_id": 2116114,
"author_profile": "https://Stackoverflow.com/users/2116114",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Why foreach ?!</strong></p>\n\n<p>The simplest way is using <strong>for</strong> instead of foreach <strong>if you are using List</strong>:</p>\n\n<pre><code>for (int i = 0 ; i < myList.Count ; i++)\n{\n // Do something...\n}\n</code></pre>\n\n<p>Or if you want use foreach:</p>\n\n<pre><code>foreach (string m in myList)\n{\n // Do something...\n}\n</code></pre>\n\n<p>You can use this to know the index of each loop:</p>\n\n<pre><code>myList.indexOf(m)\n</code></pre>\n"
},
{
"answer_id": 39105631,
"author": "Satisfied",
"author_id": 6748675,
"author_profile": "https://Stackoverflow.com/users/6748675",
"pm_score": 3,
"selected": false,
"text": "<p>You can write your loop like this:</p>\n\n<pre><code>var s = \"ABCDEFG\";\nforeach (var item in s.GetEnumeratorWithIndex())\n{\n System.Console.WriteLine(\"Character: {0}, Position: {1}\", item.Value, item.Index);\n}\n</code></pre>\n\n<p>After adding the following struct and extension method.</p>\n\n<p>The struct and extension method encapsulate Enumerable.Select functionality.</p>\n\n<pre><code>public struct ValueWithIndex<T>\n{\n public readonly T Value;\n public readonly int Index;\n\n public ValueWithIndex(T value, int index)\n {\n this.Value = value;\n this.Index = index;\n }\n\n public static ValueWithIndex<T> Create(T value, int index)\n {\n return new ValueWithIndex<T>(value, index);\n }\n}\n\npublic static class ExtensionMethods\n{\n public static IEnumerable<ValueWithIndex<T>> GetEnumeratorWithIndex<T>(this IEnumerable<T> enumerable)\n {\n return enumerable.Select(ValueWithIndex<T>.Create);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39997157,
"author": "user1414213562",
"author_id": 6659843,
"author_profile": "https://Stackoverflow.com/users/6659843",
"pm_score": 9,
"selected": false,
"text": "<p>Finally C#7 has a decent syntax for getting an index inside of a <code>foreach</code> loop (i. e. tuples):</p>\n<pre><code>foreach (var (item, index) in collection.WithIndex())\n{\n Debug.WriteLine($"{index}: {item}");\n}\n</code></pre>\n<p>A little extension method would be needed:</p>\n<pre><code>using System.Collections.Generic;\n\npublic static class EnumExtension {\n public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self) \n => self.Select((item, index) => (item, index));\n}\n</code></pre>\n"
},
{
"answer_id": 40540985,
"author": "Kind Contributor",
"author_id": 887092,
"author_profile": "https://Stackoverflow.com/users/887092",
"pm_score": 4,
"selected": false,
"text": "<p>This answer: lobby the C# language team for direct language support.</p>\n\n<p>The leading answer states:</p>\n\n<blockquote>\n <p>Obviously, the concept of an index is foreign to the concept of\n enumeration, and cannot be done.</p>\n</blockquote>\n\n<p>While this is true of the current C# language version (2020), this is not a conceptual CLR/Language limit, it can be done.</p>\n\n<p>The Microsoft C# language development team could create a new C# language feature, by adding support for a new Interface IIndexedEnumerable</p>\n\n<pre><code>foreach (var item in collection with var index)\n{\n Console.WriteLine(\"Iteration {0} has value {1}\", index, item);\n}\n\n//or, building on @user1414213562's answer\nforeach (var (item, index) in collection)\n{\n Console.WriteLine(\"Iteration {0} has value {1}\", index, item);\n}\n</code></pre>\n\n<p>If <code>foreach ()</code> is used and <code>with var index</code> is present, then the compiler expects the item collection to declare <code>IIndexedEnumerable</code> interface. If the interface is absent, the compiler can polyfill wrap the source with an IndexedEnumerable object, which adds in the code for tracking the index.</p>\n\n<pre><code>interface IIndexedEnumerable<T> : IEnumerable<T>\n{\n //Not index, because sometimes source IEnumerables are transient\n public long IterationNumber { get; }\n}\n</code></pre>\n\n<p>Later, the CLR can be updated to have internal index tracking, that is only used if <code>with</code> keyword is specified and the source doesn't directly implement <code>IIndexedEnumerable</code></p>\n\n<p>Why:</p>\n\n<ul>\n<li>Foreach looks nicer, and in business applications, foreach loops are rarely a performance bottleneck</li>\n<li>Foreach can be more efficient on memory. Having a pipeline of functions instead of converting to new collections at each step. Who cares if it uses a few more CPU cycles when there are fewer CPU cache faults and fewer garbage collections?</li>\n<li>Requiring the coder to add index-tracking code, spoils the beauty</li>\n<li>It's quite easy to implement (please Microsoft) and is backward compatible</li>\n</ul>\n\n<p>While most people here are not Microsoft employees, this is <em>a</em> correct answer, you can lobby Microsoft to add such a feature. You could already build your own iterator with an <a href=\"https://stackoverflow.com/a/39997157/887092\">extension function and use tuples</a>, but Microsoft could sprinkle the syntactic sugar to avoid the extension function</p>\n"
},
{
"answer_id": 45239493,
"author": "Paul Mitchell",
"author_id": 38966,
"author_profile": "https://Stackoverflow.com/users/38966",
"pm_score": 4,
"selected": false,
"text": "<p>C# 7 finally gives us an elegant way to do this:</p>\n\n<pre><code>static class Extensions\n{\n public static IEnumerable<(int, T)> Enumerate<T>(\n this IEnumerable<T> input,\n int start = 0\n )\n {\n int i = start;\n foreach (var t in input)\n {\n yield return (i++, t);\n }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var s = new string[]\n {\n \"Alpha\",\n \"Bravo\",\n \"Charlie\",\n \"Delta\"\n };\n\n foreach (var (i, t) in s.Enumerate())\n {\n Console.WriteLine($\"{i}: {t}\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46145503,
"author": "Pavel",
"author_id": 3553138,
"author_profile": "https://Stackoverflow.com/users/3553138",
"pm_score": 6,
"selected": false,
"text": "<p>Using LINQ, C# 7, and the <code>System.ValueTuple</code> NuGet package, you can do this:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var (value, index) in collection.Select((v, i)=>(v, i))) {\n Console.WriteLine(value + \" is at index \" + index);\n}\n</code></pre>\n\n<p>You can use the regular <code>foreach</code> construct and be able to access the value and index directly, not as a member of an object, and keeps both fields only in the scope of the loop. For these reasons, I believe this is the best solution if you are able to use C# 7 and <code>System.ValueTuple</code>.</p>\n"
},
{
"answer_id": 50456510,
"author": "conterio",
"author_id": 4525819,
"author_profile": "https://Stackoverflow.com/users/4525819",
"pm_score": 5,
"selected": false,
"text": "<p>Just add your own index. Keep it simple.</p>\n<pre><code>int i = -1;\nforeach (var item in Collection)\n{\n ++i;\n item.index = i;\n}\n</code></pre>\n"
},
{
"answer_id": 53789000,
"author": "Ahmed Fwela",
"author_id": 4009642,
"author_profile": "https://Stackoverflow.com/users/4009642",
"pm_score": -1,
"selected": false,
"text": "<p>i want to discuss this question more theoretically (since it has already enough practical answers)</p>\n\n<p>.net has a very nice abstraction model for groups of data (a.k.a. collections) </p>\n\n<ul>\n<li>At the very top, and the most abstract, you have an <code>IEnumerable</code> it's just a group of data that you can enumerate. It doesn't matter HOW you enumerate, it's just that you can enumerate some data. And that enumeration is done by a completely different object, an <code>IEnumerator</code></li>\n</ul>\n\n<p>these interfaces are defined is as follows:</p>\n\n<pre><code>//\n// Summary:\n// Exposes an enumerator, which supports a simple iteration over a non-generic collection.\npublic interface IEnumerable\n{\n //\n // Summary:\n // Returns an enumerator that iterates through a collection.\n //\n // Returns:\n // An System.Collections.IEnumerator object that can be used to iterate through\n // the collection.\n IEnumerator GetEnumerator();\n}\n\n//\n// Summary:\n// Supports a simple iteration over a non-generic collection.\npublic interface IEnumerator\n{\n //\n // Summary:\n // Gets the element in the collection at the current position of the enumerator.\n //\n // Returns:\n // The element in the collection at the current position of the enumerator.\n object Current { get; }\n\n //\n // Summary:\n // Advances the enumerator to the next element of the collection.\n //\n // Returns:\n // true if the enumerator was successfully advanced to the next element; false if\n // the enumerator has passed the end of the collection.\n //\n // Exceptions:\n // T:System.InvalidOperationException:\n // The collection was modified after the enumerator was created.\n bool MoveNext();\n //\n // Summary:\n // Sets the enumerator to its initial position, which is before the first element\n // in the collection.\n //\n // Exceptions:\n // T:System.InvalidOperationException:\n // The collection was modified after the enumerator was created.\n void Reset();\n}\n</code></pre>\n\n<ul>\n<li><p>as you might have noticed, the <code>IEnumerator</code> interface doesn't \"know\" what an index is, it just knows what element it's currently pointing to, and how to move to the next one.</p></li>\n<li><p>now here is the trick: <code>foreach</code> considers every input collection an <code>IEnumerable</code>, even if it is a more concrete implementation like an <code>IList<T></code> (which inherits from <code>IEnumerable</code>), it will only see the abstract interface <code>IEnumerable</code>.</p></li>\n<li><p>what <code>foreach</code> is actually doing, is calling <code>GetEnumerator</code> on the collection, and calling <code>MoveNext</code> until it returns false.</p></li>\n<li><p>so here is the problem, you want to define a concrete concept \"Indices\" on an abstract concept \"Enumerables\", the built in <code>foreach</code> construct doesn't give you that option, so your only way is to define it yourself, either by what you are doing originally (creating a counter manually) or just use an implementation of <code>IEnumerator</code> that recognizes indices AND implement a <code>foreach</code> construct that recognizes that custom implementation.</p></li>\n</ul>\n\n<p>personally i would create an extension method like this</p>\n\n<pre><code>public static class Ext\n{\n public static void FE<T>(this IEnumerable<T> l, Action<int, T> act)\n {\n int counter = 0;\n foreach (var item in l)\n {\n act(counter, item);\n counter++;\n }\n }\n}\n</code></pre>\n\n<p>and use it like this</p>\n\n<pre><code>var x = new List<string>() { \"hello\", \"world\" };\nx.FE((ind, ele) =>\n{\n Console.WriteLine($\"{ind}: {ele}\");\n});\n</code></pre>\n\n<p>this also avoids any unnecessary allocations seen in other answers.</p>\n"
},
{
"answer_id": 56218652,
"author": "Marcos ruiz",
"author_id": 11475011,
"author_profile": "https://Stackoverflow.com/users/11475011",
"pm_score": 2,
"selected": false,
"text": "<p>This way you can use the index and value using LINQ:</p>\n<pre><code>ListValues.Select((x, i) => new { Value = x, Index = i }).ToList().ForEach(element =>\n{\n // element.Index\n // element.Value\n});\n</code></pre>\n"
},
{
"answer_id": 62951790,
"author": "usman tahir",
"author_id": 5717287,
"author_profile": "https://Stackoverflow.com/users/5717287",
"pm_score": 3,
"selected": false,
"text": "<pre><code>// using foreach loop how to get index number:\n \nforeach (var result in results.Select((value, index) => new { index, value }))\n{\n // do something\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?
For instance, I currently do something like this depending on the circumstances:
```
int i = 0;
foreach (Object o in collection)
{
// ...
i++;
}
``` | The `foreach` is for iterating over collections that implement [`IEnumerable`](http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx). It does this by calling [`GetEnumerator`](http://msdn.microsoft.com/en-us/library/s793z9y2(v=vs.110).aspx) on the collection, which will return an [`Enumerator`](http://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx).
This Enumerator has a method and a property:
* `MoveNext()`
* `Current`
`Current` returns the object that Enumerator is currently on, `MoveNext` updates `Current` to the next object.
The concept of an index is foreign to the concept of enumeration, and cannot be done.
Because of that, most collections are able to be traversed using an indexer and the for loop construct.
I greatly prefer using a for loop in this situation compared to tracking the index with a local variable. |
43,044 | <p>I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc. </p>
<p>I've found solutions to this problem but they rely on alternative color palettes than RGB.
I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors. </p>
<p>Any ideas would be great.</p>
| [
{
"answer_id": 43081,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 0,
"selected": false,
"text": "<p>you could have them be within a certain brightness. that would control the ammount of \"neon\" colors a bit. for instance, if the \"brightness\"</p>\n\n<pre><code>brightness = sqrt(R^2+G^2+B^2)\n</code></pre>\n\n<p>was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black.</p>\n"
},
{
"answer_id": 43150,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 0,
"selected": false,
"text": "<p>It's going to be hard to get what you want algorithmically - people have been studying color theory for a long time, and they don't even know all the rules.</p>\n\n<p>However, there are <em>some</em> rules which you can use to cull bad color combinations (ie, there are rules for clashing colors, and choosing complementary colors).</p>\n\n<p>I'd recommend you visit your library's art section and check out books on color theory to gain a better understanding of what is a good color before you try to make one - it appears you might not even know why certain combinations work and others don't.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 43235,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 10,
"selected": true,
"text": "<p>You could average the RGB values of random colors with those of a constant color:</p>\n\n<p><em>(example in Java)</em></p>\n\n<pre><code>public Color generateRandomColor(Color mix) {\n Random random = new Random();\n int red = random.nextInt(256);\n int green = random.nextInt(256);\n int blue = random.nextInt(256);\n\n // mix the color\n if (mix != null) {\n red = (red + mix.getRed()) / 2;\n green = (green + mix.getGreen()) / 2;\n blue = (blue + mix.getBlue()) / 2;\n }\n\n Color color = new Color(red, green, blue);\n return color;\n}\n</code></pre>\n\n<p><br/>\nMixing random colors with white (255, 255, 255) creates neutral pastels by increasing the lightness while keeping the hue of the original color. These randomly generated pastels usually go well together, especially in large numbers.</p>\n\n<p>Here are some pastel colors generated using the above method:</p>\n\n<p><img src=\"https://i.stack.imgur.com/8jKGx.jpg\" alt=\"First\"></p>\n\n<p><br/>\nYou could also mix the random color with a constant pastel, which results in a tinted set of neutral colors. For example, using a light blue creates colors like these:</p>\n\n<p><img src=\"https://i.stack.imgur.com/zI406.jpg\" alt=\"Second\"></p>\n\n<p><br/>\nGoing further, you could add heuristics to your generator that take into account complementary colors or levels of shading, but it all depends on the impression you want to achieve with your random colors.</p>\n\n<p>Some additional resources:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Color_theory\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Color_theory</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Complementary_color\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Complementary_color</a></li>\n</ul>\n"
},
{
"answer_id": 962777,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 4,
"selected": false,
"text": "<p>Converting to another palette is a far superior way to do this. There's a reason they do that: other palettes are 'perceptual' - that is, they put similar seeming colors close together, and adjusting one variable changes the color in a predictable manner. None of that is true for RGB, where there's no obvious relationship between colors that \"go well together\".</p>\n"
},
{
"answer_id": 5008241,
"author": "Fgblanch",
"author_id": 76778,
"author_profile": "https://Stackoverflow.com/users/76778",
"pm_score": 6,
"selected": false,
"text": "<p>I would use a color wheel and given a random position you could add the golden angle (137,5 degrees)</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Golden_angle\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Golden_angle</a></p>\n\n<p>in order to get different colours each time that do not overlap. </p>\n\n<p>Adjusting the brightness for the color wheel you could get also different bright/dark color combinations.</p>\n\n<p>I've found this blog post that explains really well the problem and the solution using the golden ratio.</p>\n\n<p><a href=\"http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/\" rel=\"noreferrer\">http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/</a></p>\n\n<p><strong>UPDATE:</strong> I've just found this other approach:</p>\n\n<p>It's called RYB(red, yellow, blue) method and it's described in this paper:</p>\n\n<p><a href=\"http://threekings.tk/mirror/ryb_TR.pdf\" rel=\"noreferrer\">http://threekings.tk/mirror/ryb_TR.pdf</a></p>\n\n<p>as \"Paint Inspired Color Compositing\".</p>\n\n<p>The algorithm generates the colors and each new color is chosen to maximize its euclidian distance to the previously selected ones.</p>\n\n<p>Here you can find a a good implementation in javascript:</p>\n\n<p><a href=\"http://afriggeri.github.com/RYB/\" rel=\"noreferrer\">http://afriggeri.github.com/RYB/</a></p>\n\n<p><strong>UPDATE 2:</strong> </p>\n\n<p>The Sciences Po Medialb have just released a tool called \"I want Hue\" that generate color palettes for data scientists. Using different color spaces and generating the palettes by using k-means clustering or force vectors ( repulsion graphs) The results from those methods are very good, they show the theory and an implementation in their web page. </p>\n\n<p><a href=\"http://tools.medialab.sciences-po.fr/iwanthue/index.php\" rel=\"noreferrer\">http://tools.medialab.sciences-po.fr/iwanthue/index.php</a></p>\n"
},
{
"answer_id": 12266311,
"author": "motobói",
"author_id": 25612,
"author_profile": "https://Stackoverflow.com/users/25612",
"pm_score": 5,
"selected": false,
"text": "<p>In javascript:</p>\n\n<pre><code>function pastelColors(){\n var r = (Math.round(Math.random()* 127) + 127).toString(16);\n var g = (Math.round(Math.random()* 127) + 127).toString(16);\n var b = (Math.round(Math.random()* 127) + 127).toString(16);\n return '#' + r + g + b;\n}\n</code></pre>\n\n<p>Saw the idea here: <a href=\"http://blog.functionalfun.net/2008/07/random-pastel-colour-generator.html\" rel=\"noreferrer\">http://blog.functionalfun.net/2008/07/random-pastel-colour-generator.html</a></p>\n"
},
{
"answer_id": 14810261,
"author": "ChilledFlame",
"author_id": 2060983,
"author_profile": "https://Stackoverflow.com/users/2060983",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function fnGetRandomColour(iDarkLuma, iLightLuma) \n{ \n for (var i=0;i<20;i++)\n {\n var sColour = ('ffffff' + Math.floor(Math.random() * 0xFFFFFF).toString(16)).substr(-6);\n\n var rgb = parseInt(sColour, 16); // convert rrggbb to decimal\n var r = (rgb >> 16) & 0xff; // extract red\n var g = (rgb >> 8) & 0xff; // extract green\n var b = (rgb >> 0) & 0xff; // extract blue\n\n var iLuma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709\n\n\n if (iLuma > iDarkLuma && iLuma < iLightLuma) return sColour;\n }\n return sColour;\n} \n</code></pre>\n\n<p>For pastel, pass in higher luma dark/light integers - ie fnGetRandomColour(120, 250)</p>\n\n<p>Credits: all credits to \n <a href=\"http://paulirish.com/2009/random-hex-color-code-snippets/\" rel=\"nofollow\">http://paulirish.com/2009/random-hex-color-code-snippets/</a>\n stackoverflow.com/questions/12043187/how-to-check-if-hex-color-is-too-black</p>\n"
},
{
"answer_id": 18269541,
"author": "LifeInTheTrees",
"author_id": 2040877,
"author_profile": "https://Stackoverflow.com/users/2040877",
"pm_score": 3,
"selected": false,
"text": "<p>An answer that shouldn't be overlooked, because it's simple and presents advantages, is sampling of real life photos and paintings. sample as many random pixels as you want random colors on thumbnails of modern art pics, cezanne, van gogh, monnet, photos... the advantage is that you can get colors by theme and that they are organic colors. just put 20 - 30 pics in a folder and random sample a random pic every time.</p>\n\n<p>Conversion to HSV values is a widespread code algorithm for psychologically based palette. hsv is easier to randomize.</p>\n"
},
{
"answer_id": 21361663,
"author": "m1ch4ls",
"author_id": 3024975,
"author_profile": "https://Stackoverflow.com/users/3024975",
"pm_score": 2,
"selected": false,
"text": "<p>Here is quick and dirty color generator in C# (using 'RYB approach' described in this <a href=\"http://threekings.tk/mirror/ryb_TR.pdf\" rel=\"nofollow\">article</a>). It's a rewrite from <a href=\"http://afriggeri.github.com/RYB/\" rel=\"nofollow\">JavaScript</a>.</p>\n\n<p><strong>Use:</strong></p>\n\n<pre><code>List<Color> ColorPalette = ColorGenerator.Generate(30).ToList();\n</code></pre>\n\n<p>First two colors tend to be white and a shade of black. I often skip them like this (using Linq):</p>\n\n<pre><code>List<Color> ColorsPalette = ColorGenerator\n .Generate(30)\n .Skip(2) // skip white and black\n .ToList(); \n</code></pre>\n\n<p><strong>Implementation:</strong></p>\n\n<pre><code>public static class ColorGenerator\n{\n\n // RYB color space\n private static class RYB\n {\n private static readonly double[] White = { 1, 1, 1 };\n private static readonly double[] Red = { 1, 0, 0 };\n private static readonly double[] Yellow = { 1, 1, 0 };\n private static readonly double[] Blue = { 0.163, 0.373, 0.6 };\n private static readonly double[] Violet = { 0.5, 0, 0.5 };\n private static readonly double[] Green = { 0, 0.66, 0.2 };\n private static readonly double[] Orange = { 1, 0.5, 0 };\n private static readonly double[] Black = { 0.2, 0.094, 0.0 };\n\n public static double[] ToRgb(double r, double y, double b)\n {\n var rgb = new double[3];\n for (int i = 0; i < 3; i++)\n {\n rgb[i] = White[i] * (1.0 - r) * (1.0 - b) * (1.0 - y) +\n Red[i] * r * (1.0 - b) * (1.0 - y) +\n Blue[i] * (1.0 - r) * b * (1.0 - y) +\n Violet[i] * r * b * (1.0 - y) +\n Yellow[i] * (1.0 - r) * (1.0 - b) * y +\n Orange[i] * r * (1.0 - b) * y +\n Green[i] * (1.0 - r) * b * y +\n Black[i] * r * b * y;\n }\n\n return rgb;\n }\n }\n\n private class Points : IEnumerable<double[]>\n {\n private readonly int pointsCount;\n private double[] picked;\n private int pickedCount;\n\n private readonly List<double[]> points = new List<double[]>();\n\n public Points(int count)\n {\n pointsCount = count;\n }\n\n private void Generate()\n {\n points.Clear();\n var numBase = (int)Math.Ceiling(Math.Pow(pointsCount, 1.0 / 3.0));\n var ceil = (int)Math.Pow(numBase, 3.0);\n for (int i = 0; i < ceil; i++)\n {\n points.Add(new[]\n {\n Math.Floor(i/(double)(numBase*numBase))/ (numBase - 1.0),\n Math.Floor((i/(double)numBase) % numBase)/ (numBase - 1.0),\n Math.Floor((double)(i % numBase))/ (numBase - 1.0),\n });\n }\n }\n\n private double Distance(double[] p1)\n {\n double distance = 0;\n for (int i = 0; i < 3; i++)\n {\n distance += Math.Pow(p1[i] - picked[i], 2.0);\n }\n\n return distance;\n }\n\n private double[] Pick()\n {\n if (picked == null)\n {\n picked = points[0];\n points.RemoveAt(0);\n pickedCount = 1;\n return picked;\n }\n\n var d1 = Distance(points[0]);\n int i1 = 0, i2 = 0;\n foreach (var point in points)\n {\n var d2 = Distance(point);\n if (d1 < d2)\n {\n i1 = i2;\n d1 = d2;\n }\n\n i2 += 1;\n }\n\n var pick = points[i1];\n points.RemoveAt(i1);\n\n for (int i = 0; i < 3; i++)\n {\n picked[i] = (pickedCount * picked[i] + pick[i]) / (pickedCount + 1.0);\n }\n\n pickedCount += 1;\n return pick;\n }\n\n public IEnumerator<double[]> GetEnumerator()\n {\n Generate();\n for (int i = 0; i < pointsCount; i++)\n {\n yield return Pick();\n }\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n\n public static IEnumerable<Color> Generate(int numOfColors)\n {\n var points = new Points(numOfColors);\n\n foreach (var point in points)\n {\n var rgb = RYB.ToRgb(point[0], point[1], point[2]);\n yield return Color.FromArgb(\n (int)Math.Floor(255 * rgb[0]),\n (int)Math.Floor(255 * rgb[1]),\n (int)Math.Floor(255 * rgb[2]));\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 22363008,
"author": "Petr Bugyík",
"author_id": 2875783,
"author_profile": "https://Stackoverflow.com/users/2875783",
"pm_score": 2,
"selected": false,
"text": "<p>In php:\n</p>\n\n<pre><code>function pastelColors() {\n $r = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);\n $g = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);\n $b = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);\n\n return \"#\" . $r . $g . $b;\n}\n</code></pre>\n\n<p>source: <a href=\"https://stackoverflow.com/a/12266311/2875783\">https://stackoverflow.com/a/12266311/2875783</a></p>\n"
},
{
"answer_id": 22743973,
"author": "LifeInTheTrees",
"author_id": 2040877,
"author_profile": "https://Stackoverflow.com/users/2040877",
"pm_score": 0,
"selected": false,
"text": "<p>I'd strongly recommend using a CG HSVtoRGB shader function, they are awesome... it gives you natural color control like a painter instead of control like a crt monitor, which you arent presumably!</p>\n\n<p>This is a way to make 1 float value. i.e. Grey, into 1000 ds of combinations of color and brightness and saturation etc:</p>\n\n<pre><code>int rand = a global color randomizer that you can control by script/ by a crossfader etc.\nfloat h = perlin(grey,23.3*rand)\nfloat s = perlin(grey,54,4*rand)\nfloat v = perlin(grey,12.6*rand)\n\nReturn float4 HSVtoRGB(h,s,v);\n</code></pre>\n\n<p>result is AWESOME COLOR RANDOMIZATION! it's not natural but it uses natural color gradients and it looks organic and controlleably irridescent / pastel parameters.</p>\n\n<p>For perlin, you can use this function, it is a fast zig zag version of perlin.</p>\n\n<pre><code>function zig ( xx : float ): float{ //lfo nz -1,1\n xx= xx+32;\n var x0 = Mathf.Floor(xx);\n var x1 = x0+1;\n var v0 = (Mathf.Sin (x0*.014686)*31718.927)%1;\n var v1 = (Mathf.Sin (x1*.014686)*31718.927)%1;\n return Mathf.Lerp( v0 , v1 , (xx)%1 )*2-1;\n}\n</code></pre>\n"
},
{
"answer_id": 28500955,
"author": "Dave_L",
"author_id": 1163569,
"author_profile": "https://Stackoverflow.com/users/1163569",
"pm_score": 2,
"selected": false,
"text": "<p>David Crow's method in an R two-liner:</p>\n\n<pre><code>GetRandomColours <- function(num.of.colours, color.to.mix=c(1,1,1)) {\n return(rgb((matrix(runif(num.of.colours*3), nrow=num.of.colours)*color.to.mix)/2))\n}\n</code></pre>\n"
},
{
"answer_id": 31594284,
"author": "Ephraim",
"author_id": 599402,
"author_profile": "https://Stackoverflow.com/users/599402",
"pm_score": 0,
"selected": false,
"text": "<p>Here is something I wrote for a site I made. It will auto-generate a random flat background-color for any div with the class <code>.flat-color-gen</code>. Jquery is only required for the purposes of adding css to the page; it's not required for the main part of this, which is the <code>generateFlatColorWithOrder()</code> method.</p>\n\n<p><a href=\"https://jsfiddle.net/ephraimrothschild/kdprqauf/3/\" rel=\"nofollow\">JsFiddle Link</a></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>(function($) {\n function generateFlatColorWithOrder(num, rr, rg, rb) {\n var colorBase = 256;\n var red = 0;\n var green = 0;\n var blue = 0;\n num = Math.round(num);\n num = num + 1;\n if (num != null) {\n\n red = (num*rr) % 256;\n green = (num*rg) % 256;\n blue = (num*rb) % 256;\n }\n var redString = Math.round((red + colorBase) / 2).toString();\n var greenString = Math.round((green + colorBase) / 2).toString();\n var blueString = Math.round((blue + colorBase) / 2).toString();\n return \"rgb(\"+redString+\", \"+greenString+\", \"+blueString+\")\";\n //return '#' + redString + greenString + blueString;\n }\n\n function generateRandomFlatColor() {\n return generateFlatColorWithOrder(Math.round(Math.random()*127));\n }\n\n var rr = Math.round(Math.random()*1000);\n var rg = Math.round(Math.random()*1000);\n var rb = Math.round(Math.random()*1000);\n console.log(\"random red: \"+ rr);\n console.log(\"random green: \"+ rg);\n console.log(\"random blue: \"+ rb);\n console.log(\"----------------------------------------------------\");\n $('.flat-color-gen').each(function(i, obj) {\n console.log(generateFlatColorWithOrder(i));\n $(this).css(\"background-color\",generateFlatColorWithOrder(i, rr, rg, rb).toString());\n });\n})(window.jQuery);\n</code></pre>\n"
},
{
"answer_id": 31629356,
"author": "Sceptic",
"author_id": 3340062,
"author_profile": "https://Stackoverflow.com/users/3340062",
"pm_score": 1,
"selected": false,
"text": "<h2>JavaScript adaptation of David Crow's original answer, IE and Nodejs specific code included.</h2>\n\n<pre><code>generateRandomComplementaryColor = function(r, g, b){\n //--- JavaScript code\n var red = Math.floor((Math.random() * 256));\n var green = Math.floor((Math.random() * 256));\n var blue = Math.floor((Math.random() * 256));\n //---\n\n //--- Extra check for Internet Explorers, its Math.random is not random enough.\n if(!/MSIE 9/i.test(navigator.userAgent) && !/MSIE 10/i.test(navigator.userAgent) && !/rv:11.0/i.test(navigator.userAgent)){\n red = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));\n green = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));\n blue = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));\n };\n //---\n\n //--- nodejs code\n /*\n crypto = Npm.require('crypto');\n red = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);\n green = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);\n blue = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);\n */\n //---\n\n red = (red + r)/2;\n green = (green + g)/2;\n blue = (blue + b)/2;\n\n return 'rgb(' + Math.floor(red) + ', ' + Math.floor(green) + ', ' + Math.floor(blue) + ')';\n}\n</code></pre>\n\n<p><strong>Run the function using:</strong></p>\n\n<pre><code>generateRandomComplementaryColor(240, 240, 240);\n</code></pre>\n"
},
{
"answer_id": 32124551,
"author": "InternalFX",
"author_id": 654518,
"author_profile": "https://Stackoverflow.com/users/654518",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"https://github.com/internalfx/distinct-colors\" rel=\"nofollow\">distinct-colors</a>.</p>\n\n<p>Written in javascript.</p>\n\n<p>It generates a palette of <em>visually</em> distinct colors.</p>\n\n<p>distinct-colors is highly configurable:</p>\n\n<ul>\n<li>Choose how many colors are in the palette</li>\n<li>Restrict the hue to a specific range</li>\n<li>Restrict the chroma (saturation) to a specific range</li>\n<li>Restrict the lightness to a specific range</li>\n<li>Configure general quality of the palette</li>\n</ul>\n"
},
{
"answer_id": 41068169,
"author": "Moriarty",
"author_id": 273101,
"author_profile": "https://Stackoverflow.com/users/273101",
"pm_score": 3,
"selected": false,
"text": "<p>I've had success using <a href=\"http://devmag.org.za/2012/07/29/how-to-choose-colours-procedurally-algorithms/\" rel=\"noreferrer\">TriadMixing</a> and <a href=\"https://en.wikipedia.org/wiki/Color_difference#CIE94\" rel=\"noreferrer\">CIE94</a> to avoid similar colors. The following image uses input colors red, yellow, and white. See <a href=\"https://github.com/jamesmoriarty/scorched_earth\" rel=\"noreferrer\">here</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kOZiV.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kOZiV.jpg\" alt=\"TriadMixing + CIE94\"></a></p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
] | I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc.
I've found solutions to this problem but they rely on alternative color palettes than RGB.
I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors.
Any ideas would be great. | You could average the RGB values of random colors with those of a constant color:
*(example in Java)*
```
public Color generateRandomColor(Color mix) {
Random random = new Random();
int red = random.nextInt(256);
int green = random.nextInt(256);
int blue = random.nextInt(256);
// mix the color
if (mix != null) {
red = (red + mix.getRed()) / 2;
green = (green + mix.getGreen()) / 2;
blue = (blue + mix.getBlue()) / 2;
}
Color color = new Color(red, green, blue);
return color;
}
```
Mixing random colors with white (255, 255, 255) creates neutral pastels by increasing the lightness while keeping the hue of the original color. These randomly generated pastels usually go well together, especially in large numbers.
Here are some pastel colors generated using the above method:

You could also mix the random color with a constant pastel, which results in a tinted set of neutral colors. For example, using a light blue creates colors like these:

Going further, you could add heuristics to your generator that take into account complementary colors or levels of shading, but it all depends on the impression you want to achieve with your random colors.
Some additional resources:
* <http://en.wikipedia.org/wiki/Color_theory>
* <http://en.wikipedia.org/wiki/Complementary_color> |
43,051 | <p>I have the following C# code:</p>
<pre><code>byte rule = 0;
...
rule = rule | 0x80;
</code></pre>
<p>which produces the error: </p>
<blockquote>
<p><em>Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)</em></p>
</blockquote>
<p>[Update: first version of the question was wrong ... I misread the compiler output]</p>
<p>Adding the cast <strong>doesn't</strong> fix the problem:</p>
<pre><code>rule = rule | (byte) 0x80;
</code></pre>
<p>I need to write it as:</p>
<pre><code>rule |= 0x80;
</code></pre>
<p>Which just seems weird. Why is the <code>|=</code> operator any different to the <code>|</code> operator?</p>
<p>Is there any other way of telling the compiler to treat the constant as a byte?</p>
<hr>
<p><strong>@ Giovanni Galbo</strong> : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much!</p>
<p><strong>@ Jonathon Holland</strong> : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:</p>
<blockquote>
<p><em>The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)</em> </p>
</blockquote>
| [
{
"answer_id": 43057,
"author": "John Rutherford",
"author_id": 3880,
"author_profile": "https://Stackoverflow.com/users/3880",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like you may just have to do it the ugly way: <a href=\"http://msdn.microsoft.com/en-us/library/5bdb6693.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/5bdb6693.aspx</a>.</p>\n"
},
{
"answer_id": 43059,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 5,
"selected": false,
"text": "<p>C# does not have a literal suffix for byte. u = uint, l = long, ul = ulong, f = float, m = decimal, but no byte. You have to cast it.</p>\n"
},
{
"answer_id": 43060,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>The term you are looking for is \"Literal\" and unfortunately C# does not have a byte literal.</p>\n\n<p>Here's a list of <a href=\"http://msdn.microsoft.com/en-us/library/aa664672(VS.71).aspx\" rel=\"nofollow noreferrer\">all C# literals</a>.</p>\n"
},
{
"answer_id": 43061,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 2,
"selected": false,
"text": "<p>According to the <a href=\"http://www.ecma-international.org/publications/standards/Ecma-334.htm\" rel=\"nofollow noreferrer\">ECMA Specification, pg 72</a> there is no byte literal. Only integer literals for the types: int, uint, long, and ulong.</p>\n"
},
{
"answer_id": 43062,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, your only recourse is to do it just the way you have. There is no suffix to mark the literal as a byte. The | operator does not provide for implicit conversion as an assignment (i.e. initialization) would.</p>\n"
},
{
"answer_id": 43064,
"author": "jmatthias",
"author_id": 2768,
"author_profile": "https://Stackoverflow.com/users/2768",
"pm_score": 4,
"selected": false,
"text": "<p>This works:</p>\n\n<pre><code>rule = (byte)(rule | 0x80);\n</code></pre>\n\n<p>Apparently the expression 'rule | 0x80' returns an int even if you define 0x80 as 'const byte 0x80'.</p>\n"
},
{
"answer_id": 43074,
"author": "David J. Sokol",
"author_id": 1390,
"author_profile": "https://Stackoverflow.com/users/1390",
"pm_score": 4,
"selected": true,
"text": "<pre><code>int rule = 0;\nrule |= 0x80;\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx</a> The | operator is defined for all value types. I think this will produced the intended result. The \"|=\" operator is an or then assign operator, which is simply shorthand for rule = rule | 0x80.</p>\n\n<p>One of the niftier things about C# is that it lets you do crazy things like abuse value types simply based on their size. An 'int' is exactly the same as a byte, except the compiler will throw warnings if you try and use them as both at the same time. Simply sticking with one (in this case, int) works well. If you're concerned about 64bit readiness, you can specify int32, but all ints are int32s, even running in x64 mode.</p>\n"
},
{
"answer_id": 43090,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Apparently the expression 'rule |\n 0x80' returns an int even if you\n define 0x80 as 'const byte 0x80'.</p>\n</blockquote>\n\n<p>I think the rule is numbers like 0x80 defaults to int unless you include a literal suffix. So for the expression <code>rule | 0x80</code>, the result will be an int since 0x80 is an int and rule (which is a byte) can safely be converted to int.</p>\n"
},
{
"answer_id": 14554599,
"author": "Bruce Bowman",
"author_id": 2016761,
"author_profile": "https://Stackoverflow.com/users/2016761",
"pm_score": 0,
"selected": false,
"text": "<p>According to the C standard, bytes ALWAYS promote to int in expressions, even constants. However, as long as both values are UNSIGNED, the high-order bits will be discarded so the operation should return the correct value.</p>\n\n<p>Similarly, floats promote to double, etc.</p>\n\n<p>Pull out of copy of K&R. It's all in there.</p>\n"
},
{
"answer_id": 16884882,
"author": "arx",
"author_id": 292432,
"author_profile": "https://Stackoverflow.com/users/292432",
"pm_score": 2,
"selected": false,
"text": "<p>Almost five years on and nobody has actually answered the question.</p>\n\n<p>A couple of answers claim that the problem is the lack of a byte literal, but this is irrelevant. If you calculate <code>(byte1 | byte2)</code> the result is of type <code>int</code>. Even if \"b\" were a literal suffix for byte the type of <code>(23b | 32b)</code> would still be <code>int</code>.</p>\n\n<p>The accepted answer links to an MSDN article claiming that <code>operator|</code> is defined for all integral types, but this isn't true either.</p>\n\n<p><code>operator|</code> is not defined on <code>byte</code> so the compiler uses its usual overload resolution rules to pick the version that's defined on <code>int</code>. Hence, if you want to assign the result to a <code>byte</code> you need to cast it:</p>\n\n<pre><code>rule = (byte)(rule | 0x80);\n</code></pre>\n\n<p>The question remains, why does <code>rule |= 0x80;</code> work?</p>\n\n<p>Because the C# specification has a special rule for compound assignment that allows you to omit the explicit conversion. In the compound assignment <code>x op= y</code> the rule is:</p>\n\n<blockquote>\n <p>if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as <code>x = (T)(x op y)</code>, where T is the type of x, except that x is evaluated only once.</p>\n</blockquote>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3631/"
] | I have the following C# code:
```
byte rule = 0;
...
rule = rule | 0x80;
```
which produces the error:
>
> *Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)*
>
>
>
[Update: first version of the question was wrong ... I misread the compiler output]
Adding the cast **doesn't** fix the problem:
```
rule = rule | (byte) 0x80;
```
I need to write it as:
```
rule |= 0x80;
```
Which just seems weird. Why is the `|=` operator any different to the `|` operator?
Is there any other way of telling the compiler to treat the constant as a byte?
---
**@ Giovanni Galbo** : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much!
**@ Jonathon Holland** : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:
>
> *The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)*
>
>
> | ```
int rule = 0;
rule |= 0x80;
```
<http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx> The | operator is defined for all value types. I think this will produced the intended result. The "|=" operator is an or then assign operator, which is simply shorthand for rule = rule | 0x80.
One of the niftier things about C# is that it lets you do crazy things like abuse value types simply based on their size. An 'int' is exactly the same as a byte, except the compiler will throw warnings if you try and use them as both at the same time. Simply sticking with one (in this case, int) works well. If you're concerned about 64bit readiness, you can specify int32, but all ints are int32s, even running in x64 mode. |
43,126 | <pre><code>public static IList<T> LoadObjectListAll<T>()
{
ISession session = CheckForExistingSession();
var cfg = new NHibernate.Cfg.Configuration().Configure();
var returnList = session.CreateCriteria(typeof(T));
var list = returnList.List();
var castList = list.Cast<typeof(T)>();
return castList;
}
</code></pre>
<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>
| [
{
"answer_id": 43128,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 3,
"selected": false,
"text": "<p>I think </p>\n\n<pre><code>var castList = list.Cast<typeof(T)>();\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>var castList = list.Cast<T>();\n</code></pre>\n\n<blockquote>\n <p>@Jon Limjap The most glaring error I can see is\n that an <code>IList</code> is definitely different from an <code>IList<T></code>. An <code>IList</code> is non-generic\n (e.g., <code>ArrayList</code>).</p>\n</blockquote>\n\n<p>The original question was already using an <code>IList<T></code>. It was removed when someone edited the formatting. Probably a problem with Markdown.</p>\n\n<p><strong>Fixed now.</strong></p>\n"
},
{
"answer_id": 43130,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>T is already a type parameter, you don't need to call typeof on it. TypeOf takes a type and returns its type parameter.</p>\n"
},
{
"answer_id": 43131,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>@Jon and @Jonathan is correct, but you also have to change the return type to</p>\n\n<pre><code>IList<T>\n</code></pre>\n\n<p>also. Unless that is just a markdown bug.</p>\n\n<p>@<a href=\"https://stackoverflow.com/questions/43126/ilistcasttypeoft-returns-error-syntax-looks-ok#43137\">Jonathan</a>, figured that was the case.</p>\n\n<p>I am not sure what version of nHibernate you are using. I haven't tried the gold release of 2.0 yet, but you could clean the method up some, by removing some lines:</p>\n\n<pre><code>public static IList<T> LoadObjectListAll()\n{\n ISession session = CheckForExistingSession();\n // Not sure if you can configure a session after retrieving it. CheckForExistingSession should have this logic.\n // var cfg = new NHibernate.Cfg.Configuration().Configure();\n var criteria = session.CreateCriteria(typeof(T));\n return criteria.List<T>();\n}\n</code></pre>\n"
},
{
"answer_id": 43132,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": -1,
"selected": false,
"text": "<p>The most glaring error I can see is that an <code>IList</code> is definitely different from an <code>IList<T></code>. An <code>IList</code> is non-generic (e.g., <code>ArrayList</code>).</p>\n\n<p>So your method signature should be:</p>\n\n<pre><code>public static IList<T> LoadObjectListAll()\n</code></pre>\n"
},
{
"answer_id": 43137,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>The IList is an IList<T>, it just got fubared by markdown when she posted it. I tried to format it, but I missed escaping the <T>..Fixing that now.</p>\n"
},
{
"answer_id": 43141,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 4,
"selected": true,
"text": "<p><code>T</code> is not a type nor a <code>System.Type</code>. <code>T</code> is a type parameter. <code>typeof(T)</code> returns the type of <code>T</code>. The <code>typeof</code> operator does not act on an object, it returns the <code>Type</code> object of a type. <a href=\"http://msdn.microsoft.com/en-us/library/58918ffs.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/58918ffs.aspx</a></p>\n\n<p>@John is correct in answering your direct question. But the NHibernate code there is a little off. You shouldn't be configuring the <code>ISessionFactory</code> <em>after</em> getting the <code>ISession</code>, for example.</p>\n\n<pre><code>public static T[] LoadObjectListAll()\n{\n var session = GetNewSession();\n var criteria = session.CreateCriteria(typeof(T));\n var results = criteria.List<T>();\n return results.ToArray(); \n}\n</code></pre>\n"
},
{
"answer_id": 43145,
"author": "Erick Sgarbi",
"author_id": 4171,
"author_profile": "https://Stackoverflow.com/users/4171",
"pm_score": 0,
"selected": false,
"text": "<p>CLI only supports generic arguments for <a href=\"http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)\" rel=\"nofollow noreferrer\">covariance and contravariance</a> when using delegates, but when using generics there are some limitations, for example, you can cast a string to an object so most people will assume that you can do the same with <code>List<string></code> to a <code>List<object></code> but you can't do that because there is no covariance between generic parameters however you can simulate covariance as you can see in this <a href=\"http://blogs.msdn.com/kcwalina/archive/2008/04/02/SimulatedCovariance.aspx\" rel=\"nofollow noreferrer\">article</a>. So it depends on the runtime type that it is generated by the abstract factory.</p>\n"
},
{
"answer_id": 43147,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>CLI only supports generic arguments for covariance and contravariance when using delegates, but when using generics there are some limitations, for example, you can cast a string to an object so most people will assume that you can do the same with List to a List but you can't do that because there is no covariance between generic parameters however you can simulate covariance as you can see in this article. So it depends on the runtime type that it is generated by the abstract factory.</p>\n</blockquote>\n\n<p>That reads like a markov chain... Bravo.</p>\n"
},
{
"answer_id": 43153,
"author": "Erick Sgarbi",
"author_id": 4171,
"author_profile": "https://Stackoverflow.com/users/4171",
"pm_score": 1,
"selected": false,
"text": "<p>\"The original question was already using an <code>IList<T></code>. It was removed when someone edited the formatting. Probably a problem with Markdown.\"</p>\n\n<p>Thats what i saw but it was edited by someone and that's the reason why I put my explanation about covariance but for some reason i was marked down to -1.</p>\n"
},
{
"answer_id": 43160,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 1,
"selected": false,
"text": "<p>@Jonathan Holland</p>\n\n<blockquote>\n <p>T is already a type parameter, you don't need to call typeof on it. TypeOf takes a type and returns its type parameter.</p>\n</blockquote>\n\n<p><code>typeof</code> \"takes\" a type and returns its <code>System.Type</code></p>\n"
},
{
"answer_id": 43195,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p>You have too many temporary variables which are confusing</p>\n\n<p>instead of</p>\n\n<pre><code>var returnList = session.CreateCriteria(typeof(T));\nvar list = returnList.List();\nvar castList = list.Cast<typeof(T)>();\nreturn castList;\n</code></pre>\n\n<p>Just do</p>\n\n<pre><code>return session.CreateCriteria(typeof(T)).List().Cast<T>();\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | ```
public static IList<T> LoadObjectListAll<T>()
{
ISession session = CheckForExistingSession();
var cfg = new NHibernate.Cfg.Configuration().Configure();
var returnList = session.CreateCriteria(typeof(T));
var list = returnList.List();
var castList = list.Cast<typeof(T)>();
return castList;
}
```
So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? | `T` is not a type nor a `System.Type`. `T` is a type parameter. `typeof(T)` returns the type of `T`. The `typeof` operator does not act on an object, it returns the `Type` object of a type. <http://msdn.microsoft.com/en-us/library/58918ffs.aspx>
@John is correct in answering your direct question. But the NHibernate code there is a little off. You shouldn't be configuring the `ISessionFactory` *after* getting the `ISession`, for example.
```
public static T[] LoadObjectListAll()
{
var session = GetNewSession();
var criteria = session.CreateCriteria(typeof(T));
var results = criteria.List<T>();
return results.ToArray();
}
``` |
43,134 | <p>Simple question, but one that I've been curious about...is there a functional difference between the following two commands?</p>
<pre><code>String::class
String.class
</code></pre>
<p>They both do what I expect -- that is to say they return <code>Class</code> -- but what is the difference between using the <code>::</code> and the <code>.</code>?</p>
<p>I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after <code>::</code> but not after <code>.</code>, but I don't know what the reason for this is...</p>
| [
{
"answer_id": 43146,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 6,
"selected": true,
"text": "<p>The <code>.</code> operator basically says \"send this message to the object\". In your example it is calling that particular member. The <code>::</code> operator \"drills down\" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator.</p>\n\n<p>When you use <code>::</code> you have to be referencing members that are defined. When using <code>.</code> you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for <code>.</code> while it does for <code>::</code>.</p>\n"
},
{
"answer_id": 48046,
"author": "Peeja",
"author_id": 4937,
"author_profile": "https://Stackoverflow.com/users/4937",
"pm_score": 4,
"selected": false,
"text": "<p>Actually, auto-completion does work for <code>.</code>. The completion options are found by calling <code>#methods</code> on the object. You can see this for yourself by overriding <code>Object.methods</code>:</p>\n\n<pre><code>>> def Object.methods; [\"foo\", \"bar\"]; end\n=> nil\n>> Object.[TAB]\nObject.foo Object.bar\n>> Object.\n</code></pre>\n\n<p>Note that this only works when the expression to the left of the <code>.</code> is a literal. Otherwise, getting the object to call <code>#methods</code> on would involve evaluating the left-hand side, which could have side-effects. You can see this for yourself as well:</p>\n\n<pre><code>[continuing from above...]\n>> def Object.baz; Object; end\n=> nil\n>> Object.baz.[TAB]\nDisplay all 1022 possibilities? (y or n)\n</code></pre>\n\n<p>We add a method <code>#baz</code> to <code>Object</code> which returns <code>Object</code> itself. Then we auto-complete to get the methods we can call on <code>Object.baz</code>. If IRB called <code>Object.baz.methods</code>, it would get the same thing as <code>Object.methods</code>. Instead, IRB has 1022 suggestions. I'm not sure where they come from, but it's clearly a generic list which isn't actually based on context.</p>\n\n<p>The <code>::</code> operator is (also) used for getting a module's constants, while <code>.</code> is not. That's why <code>HTTP</code> will show up in the completion for <code>Net::</code>, but not for <code>Net.</code>. <code>Net.HTTP</code> isn't correct, but <code>Net::HTTP</code> is.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4142/"
] | Simple question, but one that I've been curious about...is there a functional difference between the following two commands?
```
String::class
String.class
```
They both do what I expect -- that is to say they return `Class` -- but what is the difference between using the `::` and the `.`?
I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after `::` but not after `.`, but I don't know what the reason for this is... | The `.` operator basically says "send this message to the object". In your example it is calling that particular member. The `::` operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator.
When you use `::` you have to be referencing members that are defined. When using `.` you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for `.` while it does for `::`. |
43,157 | <p>I was surprised to find today that I couldn't track down any simple way to write the contents of an <code>InputStream</code> to an <code>OutputStream</code> in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).</p>
<p>So, given an <code>InputStream</code> <code>in</code> and an <code>OutputStream</code> <code>out</code>, is there a simpler way to write the following?</p>
<pre><code>byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
</code></pre>
| [
{
"answer_id": 43163,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 7,
"selected": false,
"text": "<p>I think this will work, but make sure to test it... minor \"improvement\", but it might be a bit of a cost at readability.</p>\n\n<pre><code>byte[] buffer = new byte[1024];\nint len;\nwhile ((len = in.read(buffer)) != -1) {\n out.write(buffer, 0, len);\n}\n</code></pre>\n"
},
{
"answer_id": 43168,
"author": "Arktronic",
"author_id": 4479,
"author_profile": "https://Stackoverflow.com/users/4479",
"pm_score": 0,
"selected": false,
"text": "<p>PipedInputStream and PipedOutputStream may be of some use, as you can connect one to the other.</p>\n"
},
{
"answer_id": 43478,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 3,
"selected": false,
"text": "<p>There's no way to do this a lot easier with JDK methods, but as Apocalisp has already noted, you're not the only one with this idea: You could use <a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html\" rel=\"noreferrer\">IOUtils</a> from <a href=\"http://commons.apache.org/io/\" rel=\"noreferrer\">Jakarta Commons IO</a>, it also has a lot of other useful things, that IMO should actually be part of the JDK...</p>\n"
},
{
"answer_id": 51753,
"author": "Mikezx6r",
"author_id": 5382,
"author_profile": "https://Stackoverflow.com/users/5382",
"pm_score": 9,
"selected": false,
"text": "<p>As WMR mentioned, <code>org.apache.commons.io.IOUtils</code> from Apache has a method called <a href=\"http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/IOUtils.html#copy(java.io.InputStream,%20java.io.OutputStream)\" rel=\"noreferrer\"><code>copy(InputStream,OutputStream)</code></a> which does exactly what you're looking for.</p>\n\n<p>So, you have:</p>\n\n<pre><code>InputStream in;\nOutputStream out;\nIOUtils.copy(in,out);\nin.close();\nout.close();\n</code></pre>\n\n<p>...in your code.</p>\n\n<p>Is there a reason you're avoiding <code>IOUtils</code>? </p>\n"
},
{
"answer_id": 540772,
"author": "Dilum Ranatunga",
"author_id": 64967,
"author_profile": "https://Stackoverflow.com/users/64967",
"pm_score": 4,
"selected": false,
"text": "<p><code>PipedInputStream</code> and <code>PipedOutputStream</code> should only be used when you have multiple threads, as <a href=\"http://docs.oracle.com/javase/8/docs/api/java/io/PipedInputStream.html\" rel=\"noreferrer\">noted by the Javadoc</a>.</p>\n\n<p>Also, note that input streams and output streams do not wrap any thread interruptions with <code>IOException</code>s... So, you should consider incorporating an interruption policy to your code:</p>\n\n<pre><code>byte[] buffer = new byte[1024];\nint len = in.read(buffer);\nwhile (len != -1) {\n out.write(buffer, 0, len);\n len = in.read(buffer);\n if (Thread.interrupted()) {\n throw new InterruptedException();\n }\n}\n</code></pre>\n\n<p>This would be an useful addition if you expect to use this API for copying large volumes of data, or data from streams that get stuck for an intolerably long time.</p>\n"
},
{
"answer_id": 13814318,
"author": "Andrew Mao",
"author_id": 586086,
"author_profile": "https://Stackoverflow.com/users/586086",
"pm_score": 0,
"selected": false,
"text": "<p>Another possible candidate are the Guava I/O utilities:</p>\n\n<p><a href=\"http://code.google.com/p/guava-libraries/wiki/IOExplained\" rel=\"nofollow\">http://code.google.com/p/guava-libraries/wiki/IOExplained</a></p>\n\n<p>I thought I'd use these since Guava is already immensely useful in my project, rather than adding yet another library for one function.</p>\n"
},
{
"answer_id": 18788720,
"author": "Alexander Volkov",
"author_id": 2022586,
"author_profile": "https://Stackoverflow.com/users/2022586",
"pm_score": 2,
"selected": false,
"text": "<p>I think it's better to use a large buffer, because most of the files are greater than 1024 bytes. Also it's a good practice to check the number of read bytes to be positive.</p>\n\n<pre><code>byte[] buffer = new byte[4096];\nint n;\nwhile ((n = in.read(buffer)) > 0) {\n out.write(buffer, 0, n);\n}\nout.close();\n</code></pre>\n"
},
{
"answer_id": 18793899,
"author": "Jordan LaPrise",
"author_id": 2730161,
"author_profile": "https://Stackoverflow.com/users/2730161",
"pm_score": 5,
"selected": false,
"text": "<h2>Simple Function</h2>\n\n<p>If you only need this for writing an <code>InputStream</code> to a <code>File</code> then you can use this simple function:</p>\n\n<pre><code>private void copyInputStreamToFile( InputStream in, File file ) {\n try {\n OutputStream out = new FileOutputStream(file);\n byte[] buf = new byte[1024];\n int len;\n while((len=in.read(buf))>0){\n out.write(buf,0,len);\n }\n out.close();\n in.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19194580,
"author": "user1079877",
"author_id": 1079877,
"author_profile": "https://Stackoverflow.com/users/1079877",
"pm_score": 8,
"selected": false,
"text": "<p>If you are using Java 7, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html\" rel=\"noreferrer\">Files</a> (in the standard library) is the best approach:</p>\n\n<pre><code>/* You can get Path from file also: file.toPath() */\nFiles.copy(InputStream in, Path target)\nFiles.copy(Path source, OutputStream out)\n</code></pre>\n\n<p>Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. Use <code>file.toPath()</code> to get path from file.</p>\n\n<p>To write into an existing file (e.g. one created with <code>File.createTempFile()</code>), you'll need to pass the <code>REPLACE_EXISTING</code> copy option (otherwise <code>FileAlreadyExistsException</code> is thrown):</p>\n\n<pre><code>Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)\n</code></pre>\n"
},
{
"answer_id": 19915774,
"author": "DejanLekic",
"author_id": 876497,
"author_profile": "https://Stackoverflow.com/users/876497",
"pm_score": 2,
"selected": false,
"text": "<p>Use Commons Net's Util class:</p>\n\n<pre><code>import org.apache.commons.net.io.Util;\n...\nUtil.copyStream(in, out);\n</code></pre>\n"
},
{
"answer_id": 22223001,
"author": "Pranav",
"author_id": 2991983,
"author_profile": "https://Stackoverflow.com/users/2991983",
"pm_score": -1,
"selected": false,
"text": "<p>you can use this method</p>\n\n<pre><code>public static void copyStream(InputStream is, OutputStream os)\n {\n final int buffer_size=1024;\n try\n {\n byte[] bytes=new byte[buffer_size];\n for(;;)\n {\n int count=is.read(bytes, 0, buffer_size);\n if(count==-1)\n break;\n os.write(bytes, 0, count);\n }\n }\n catch(Exception ex){}\n }\n</code></pre>\n"
},
{
"answer_id": 22657697,
"author": "Andrejs",
"author_id": 1180621,
"author_profile": "https://Stackoverflow.com/users/1180621",
"pm_score": 6,
"selected": false,
"text": "<p>Using Guava's <a href=\"https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/io/ByteStreams.html#copy-java.io.InputStream-java.io.OutputStream-\" rel=\"noreferrer\"><code>ByteStreams.copy()</code></a>:</p>\n\n<pre><code>ByteStreams.copy(inputStream, outputStream);\n</code></pre>\n"
},
{
"answer_id": 29420264,
"author": "Nour Rteil",
"author_id": 4654101,
"author_profile": "https://Stackoverflow.com/users/4654101",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public static boolean copyFile(InputStream inputStream, OutputStream out) {\n byte buf[] = new byte[1024];\n int len;\n long startTime=System.currentTimeMillis();\n\n try {\n while ((len = inputStream.read(buf)) != -1) {\n out.write(buf, 0, len);\n }\n\n long endTime=System.currentTimeMillis()-startTime;\n Log.v(\"\",\"Time taken to transfer all bytes is : \"+endTime);\n out.close();\n inputStream.close();\n\n } catch (IOException e) {\n\n return false;\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 32136196,
"author": "Sivakumar",
"author_id": 1879388,
"author_profile": "https://Stackoverflow.com/users/1879388",
"pm_score": 3,
"selected": false,
"text": "<p>Using Java7 and <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources</a>, comes with a simplified and readable version.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>try(InputStream inputStream = new FileInputStream(\"C:\\\\mov.mp4\");\n OutputStream outputStream = new FileOutputStream(\"D:\\\\mov.mp4\")) {\n\n byte[] buffer = new byte[10*1024];\n\n for (int length; (length = inputStream.read(buffer)) != -1; ) {\n outputStream.write(buffer, 0, length);\n }\n} catch (FileNotFoundException exception) {\n exception.printStackTrace();\n} catch (IOException ioException) {\n ioException.printStackTrace();\n}\n</code></pre>\n"
},
{
"answer_id": 34191665,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 2,
"selected": false,
"text": "<p>A IMHO more minimal snippet (that also more narrowly scopes the length variable):</p>\n\n<pre><code>byte[] buffer = new byte[2048];\nfor (int n = in.read(buffer); n >= 0; n = in.read(buffer))\n out.write(buffer, 0, n);\n</code></pre>\n\n<p>As a side note, I don't understand why more people don't use a <code>for</code> loop, instead opting for a <code>while</code> with an assign-and-test expression that is regarded by some as \"poor\" style.</p>\n"
},
{
"answer_id": 39070240,
"author": "Jin Kwon",
"author_id": 330457,
"author_profile": "https://Stackoverflow.com/users/330457",
"pm_score": 3,
"selected": false,
"text": "<p>Here comes how I'm doing with a simplest for loop.</p>\n<pre><code>private void copy(final InputStream in, final OutputStream out)\n throws IOException {\n final byte[] b = new byte[8192];\n for (int r; (r = in.read(b)) != -1;) {\n out.write(b, 0, r);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39440936,
"author": "Ali Dehghani",
"author_id": 1393484,
"author_profile": "https://Stackoverflow.com/users/1393484",
"pm_score": 9,
"selected": true,
"text": "<h1>Java 9</h1>\n\n<p>Since Java 9, <code>InputStream</code> provides a method called <code>transferTo</code> with the following signature:</p>\n\n<pre><code>public long transferTo(OutputStream out) throws IOException\n</code></pre>\n\n<p>As the <a href=\"https://docs.oracle.com/javase/9/docs/api/java/io/InputStream.html#transferTo-java.io.OutputStream-\" rel=\"noreferrer\">documentation</a> states, <code>transferTo</code> will:</p>\n\n<blockquote>\n <p>Reads all bytes from this input stream and writes the bytes to the\n given output stream in the order that they are read. On return, this\n input stream will be at end of stream. This method does not close\n either stream. </p>\n \n <p>This method may block indefinitely reading from the\n input stream, or writing to the output stream. The behavior for the\n case where the input and/or output stream is asynchronously closed, or\n the thread interrupted during the transfer, is highly input and output\n stream specific, and therefore not specified</p>\n</blockquote>\n\n<p>So in order to write contents of a Java <code>InputStream</code> to an <code>OutputStream</code>, you can write:</p>\n\n<pre><code>input.transferTo(output);\n</code></pre>\n"
},
{
"answer_id": 40019374,
"author": "BullyWiiPlaza",
"author_id": 3764804,
"author_profile": "https://Stackoverflow.com/users/3764804",
"pm_score": 4,
"selected": false,
"text": "<p>The <code>JDK</code> uses the same code so it seems like there is no \"easier\" way without clunky third party libraries (which probably don't do anything different anyway). The following is directly copied from <code>java.nio.file.Files.java</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// buffer size used for reading and writing\nprivate static final int BUFFER_SIZE = 8192;\n\n/**\n * Reads all bytes from an input stream and writes them to an output stream.\n */\nprivate static long copy(InputStream source, OutputStream sink) throws IOException {\n long nread = 0L;\n byte[] buf = new byte[BUFFER_SIZE];\n int n;\n while ((n = source.read(buf)) > 0) {\n sink.write(buf, 0, n);\n nread += n;\n }\n return nread;\n}\n</code></pre>\n"
},
{
"answer_id": 42004909,
"author": "holmis83",
"author_id": 1463522,
"author_profile": "https://Stackoverflow.com/users/1463522",
"pm_score": 4,
"selected": false,
"text": "<p>For those who use <strong>Spring framework</strong> there is a useful <a href=\"http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/StreamUtils.html\" rel=\"noreferrer\">StreamUtils</a> class:</p>\n\n<pre><code>StreamUtils.copy(in, out);\n</code></pre>\n\n<p>The above does not close the streams. If you want the streams closed after the copy, use <a href=\"http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/FileCopyUtils.html\" rel=\"noreferrer\">FileCopyUtils</a> class instead:</p>\n\n<pre><code>FileCopyUtils.copy(in, out);\n</code></pre>\n"
},
{
"answer_id": 46348544,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": -1,
"selected": false,
"text": "<p>Try <a href=\"http://www.cactoos.org\" rel=\"nofollow noreferrer\">Cactoos</a>:</p>\n\n<pre><code>new LengthOf(new TeeInput(input, output)).value();\n</code></pre>\n\n<p>More details here: <a href=\"http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html\" rel=\"nofollow noreferrer\">http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html</a></p>\n"
},
{
"answer_id": 54272980,
"author": "Archimedes Trajano",
"author_id": 242042,
"author_profile": "https://Stackoverflow.com/users/242042",
"pm_score": 2,
"selected": false,
"text": "<p>I use <code>BufferedInputStream</code> and <code>BufferedOutputStream</code> to remove the buffering semantics from the code</p>\n\n<pre><code>try (OutputStream out = new BufferedOutputStream(...);\n InputStream in = new BufferedInputStream(...))) {\n int ch;\n while ((ch = in.read()) != -1) {\n out.write(ch);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 56980114,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 2,
"selected": false,
"text": "<p><strong>This is my best shot!!</strong></p>\n\n<p><em>And do not use <code>inputStream.transferTo(...)</code> because is too generic.</em>\nYour code performance will be better if you control your buffer memory.</p>\n\n<pre><code>public static void transfer(InputStream in, OutputStream out, int buffer) throws IOException {\n byte[] read = new byte[buffer]; // Your buffer size.\n while (0 < (buffer = in.read(read)))\n out.write(read, 0, buffer);\n}\n</code></pre>\n\n<p>I use it with this (improvable) method when I know in advance the size of the stream.</p>\n\n<pre><code>public static void transfer(int size, InputStream in, OutputStream out) throws IOException {\n transfer(in, out,\n size > 0xFFFF ? 0xFFFF // 16bits 65,536\n : size > 0xFFF ? 0xFFF// 12bits 4096\n : size < 0xFF ? 0xFF // 8bits 256\n : size\n );\n}\n</code></pre>\n"
},
{
"answer_id": 60788219,
"author": "IPP Nerd",
"author_id": 4504727,
"author_profile": "https://Stackoverflow.com/users/4504727",
"pm_score": 2,
"selected": false,
"text": "<p>Not very readable, but effective, has no dependencies and runs with any java version</p>\n<pre><code>byte[] buffer=new byte[1024];\nfor(int n; (n=inputStream.read(buffer))!=-1; outputStream.write(buffer,0,n));\n</code></pre>\n"
},
{
"answer_id": 68497202,
"author": "fullmoon",
"author_id": 1143361,
"author_profile": "https://Stackoverflow.com/users/1143361",
"pm_score": 0,
"selected": false,
"text": "<p>I used <code>ByteStreamKt.copyTo(src, dst, buffer.length)</code> method</p>\n<p>Here is my code</p>\n<pre><code>public static void replaceCurrentDb(Context context, Uri newDbUri) {\n try {\n File currentDb = context.getDatabasePath(DATABASE_NAME);\n if (currentDb.exists()) {\n InputStream src = context.getContentResolver().openInputStream(newDbUri);\n FileOutputStream dst = new FileOutputStream(currentDb);\n final byte[] buffer = new byte[8 * 1024];\n ByteStreamsKt.copyTo(src, dst, buffer.length);\n src.close();\n dst.close();\n Toast.makeText(context, "SUCCESS! Your selected file is set as current menu.", Toast.LENGTH_LONG).show();\n }\n else\n Log.e("DOWNLOAD:::: Database", " fail, database not found");\n }\n catch (IOException e) {\n Toast.makeText(context, "Data Download FAIL.", Toast.LENGTH_LONG).show();\n Log.e("DOWNLOAD FAIL!!!", "fail, reason:", e);\n }\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | I was surprised to find today that I couldn't track down any simple way to write the contents of an `InputStream` to an `OutputStream` in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).
So, given an `InputStream` `in` and an `OutputStream` `out`, is there a simpler way to write the following?
```
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
``` | Java 9
======
Since Java 9, `InputStream` provides a method called `transferTo` with the following signature:
```
public long transferTo(OutputStream out) throws IOException
```
As the [documentation](https://docs.oracle.com/javase/9/docs/api/java/io/InputStream.html#transferTo-java.io.OutputStream-) states, `transferTo` will:
>
> Reads all bytes from this input stream and writes the bytes to the
> given output stream in the order that they are read. On return, this
> input stream will be at end of stream. This method does not close
> either stream.
>
>
> This method may block indefinitely reading from the
> input stream, or writing to the output stream. The behavior for the
> case where the input and/or output stream is asynchronously closed, or
> the thread interrupted during the transfer, is highly input and output
> stream specific, and therefore not specified
>
>
>
So in order to write contents of a Java `InputStream` to an `OutputStream`, you can write:
```
input.transferTo(output);
``` |
43,199 | <p>The login page in my Tapestry application has a property in which the password the user types in is stored, which is then compared against the value from the database. If the user enters a password with multi-byte characters, such as:</p>
<pre><code>áéíóú
</code></pre>
<p>...an inspection of the return value of getPassword() (the abstract method for the corresponding property) gives:</p>
<pre><code>áéÃóú
</code></pre>
<p>Clearly, that's not encoded properly. Yet Firebug reports that the page is served up in UTF-8, so presumably the form submission request would also be encoded in UTF-8. Inspecting the value as it comes from the database produces the correct string, so it wouldn't appear to be an OS or IDE encoding issue. I have not overridden Tapestry's default value for org.apache.tapestry.output-encoding in the .application file, and the Tapestry 4 <a href="http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties" rel="nofollow noreferrer">documentation</a> indicates that the default value for the property is UTF-8.</p>
<p>So why does Tapestry appear to botch the encoding when setting the property?</p>
<p>Relevant code follows:</p>
<h2>Login.html</h2>
<pre class="lang-html prettyprint-override"><code><html jwcid="@Shell" doctype='html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"' ...>
<body jwcid="@Body">
...
<form jwcid="@Form" listener="listener:attemptLogin" ...>
...
<input jwcid="password"/>
...
</form>
...
</body>
</html>
</code></pre>
<h2>Login.page</h2>
<pre class="lang-jsp prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE page-specification
PUBLIC "-//Apache Software Foundation//Tapestry Specification 4.0//EN"
"http://jakarta.apache.org/tapestry/dtd/Tapestry_4_0.dtd">
<page-specification class="mycode.Login">
...
<property name="password" />
...
<component id="password" type="TextField">
<binding name="value" value="password"/>
<binding name="hidden" value="true"/>
...
</component>
...
</page-specification>
</code></pre>
<h2>Login.java</h2>
<pre><code>...
public abstract class Login extends BasePage {
...
public abstract String getPassword();
...
public void attemptLogin() {
// At this point, inspecting getPassword() returns
// the incorrectly encoded String.
}
...
}
</code></pre>
<h2>Updates</h2>
<p>@Jan Soltis: Well, if I inspect the value that comes from the database, it displays the correct string, so it would seem that my editor, OS and database are all encoding the value correctly. I've also checked my .application file; it does not contain an org.apache.tapestry.output-encoding entry, and the Tapestry 4 <a href="http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties" rel="nofollow noreferrer">documentation</a> indicates that the default value for this property is UTF-8. I have updated the description above to reflect the answers to your questions.</p>
<p>@myself: Solution found.</p>
| [
{
"answer_id": 43238,
"author": "Palgar",
"author_id": 3479,
"author_profile": "https://Stackoverflow.com/users/3479",
"pm_score": 2,
"selected": false,
"text": "<p>If you have built them as Hyper-V machines, I don't think you can go back. There are serious differences in the HAL for Virtual PC and Hyper-V. You can move a VPC to Hyper-V permanantly by removing the VPC add-ins ans adding the Hyper-V integration drivers/services and re-detecting the hardware.</p>\n\n<p>A VPC can run in Hyper-V just fine, don't add the machine drivers for Hyper-V and you can go back to VPC with no problem. </p>\n"
},
{
"answer_id": 43369,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 3,
"selected": true,
"text": "<p>VPC to Hyper-V is one way.</p>\n"
},
{
"answer_id": 4978762,
"author": "user614283",
"author_id": 614283,
"author_profile": "https://Stackoverflow.com/users/614283",
"pm_score": 0,
"selected": false,
"text": "<p>You should review Windows 2008 R2 SP1 upgrade with RemoteFX, it comes with a new video driver for VM's that allow 3D, extended desktops and more. It will help resolve some of the issues you are seeing today.</p>\n\n<p>Both the Host server and VM need to be running SP1 of Windows 2008 R2.</p>\n\n<p><a href=\"http://blogs.technet.com/b/virtualization/archive/2010/03/18/explaining-microsoft-remotefx.aspx\" rel=\"nofollow\">http://blogs.technet.com/b/virtualization/archive/2010/03/18/explaining-microsoft-remotefx.aspx</a></p>\n"
},
{
"answer_id": 7784809,
"author": "jaksonn",
"author_id": 997896,
"author_profile": "https://Stackoverflow.com/users/997896",
"pm_score": 1,
"selected": false,
"text": "<p>Hyper-V is designed to be used on the server, obviously. Whereas VirtualPC is designed for the end user. Hyper-V will give you more control, and the ability to create and restore snapshots. However, it does not have a direct console interface to the VM, you would use a browser to access the console. I would go Hyper-V, but it really depends on what you're using your VMs for. Luckily, they share the same format for virtual disks, so you can try it out with your existing VMs.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4287/"
] | The login page in my Tapestry application has a property in which the password the user types in is stored, which is then compared against the value from the database. If the user enters a password with multi-byte characters, such as:
```
áéíóú
```
...an inspection of the return value of getPassword() (the abstract method for the corresponding property) gives:
```
áéÃóú
```
Clearly, that's not encoded properly. Yet Firebug reports that the page is served up in UTF-8, so presumably the form submission request would also be encoded in UTF-8. Inspecting the value as it comes from the database produces the correct string, so it wouldn't appear to be an OS or IDE encoding issue. I have not overridden Tapestry's default value for org.apache.tapestry.output-encoding in the .application file, and the Tapestry 4 [documentation](http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties) indicates that the default value for the property is UTF-8.
So why does Tapestry appear to botch the encoding when setting the property?
Relevant code follows:
Login.html
----------
```html
<html jwcid="@Shell" doctype='html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"' ...>
<body jwcid="@Body">
...
<form jwcid="@Form" listener="listener:attemptLogin" ...>
...
<input jwcid="password"/>
...
</form>
...
</body>
</html>
```
Login.page
----------
```jsp
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE page-specification
PUBLIC "-//Apache Software Foundation//Tapestry Specification 4.0//EN"
"http://jakarta.apache.org/tapestry/dtd/Tapestry_4_0.dtd">
<page-specification class="mycode.Login">
...
<property name="password" />
...
<component id="password" type="TextField">
<binding name="value" value="password"/>
<binding name="hidden" value="true"/>
...
</component>
...
</page-specification>
```
Login.java
----------
```
...
public abstract class Login extends BasePage {
...
public abstract String getPassword();
...
public void attemptLogin() {
// At this point, inspecting getPassword() returns
// the incorrectly encoded String.
}
...
}
```
Updates
-------
@Jan Soltis: Well, if I inspect the value that comes from the database, it displays the correct string, so it would seem that my editor, OS and database are all encoding the value correctly. I've also checked my .application file; it does not contain an org.apache.tapestry.output-encoding entry, and the Tapestry 4 [documentation](http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties) indicates that the default value for this property is UTF-8. I have updated the description above to reflect the answers to your questions.
@myself: Solution found. | VPC to Hyper-V is one way. |
43,201 | <p>I'm looking for some examples or samples of routing for the following sort of scenario:</p>
<p>The general example of doing things is: {controller}/{action}/{id}</p>
<p>So in the scenario of doing a product search for a store you'd have:</p>
<pre><code>public class ProductsController: Controller
{
public ActionResult Search(string id) // id being the search string
{ ... }
}
</code></pre>
<p>Say you had a few stores to do this and you wanted that consistently, is there any way to then have: {category}/{controller}/{action}/{id}</p>
<p>So that you could have a particular search for a particular store, but use a different search method for a different store?</p>
<p>(If you required the store name to be a higher priority than the function itself in the url)</p>
<p>Or would it come down to:</p>
<pre><code>public class ProductsController: Controller
{
public ActionResult Search(int category, string id) // id being the search string
{
if(category == 1) return Category1Search();
if(category == 2) return Category2Search();
...
}
}
</code></pre>
<p>It may not be a great example, but basically the idea is to use the same controller name and therefore have a simple URL across a few different scenarios, or are you kind of stuck with requiring unique controller names, and no way to put them in slightly different namespaces/directories?</p>
<p>Edit to add:</p>
<p>The other reason I want this is because I might want a url that has the categories, and that certain controllers will only work under certain categories.</p>
<p>IE:</p>
<p>/this/search/items/search+term <-- works</p>
<p>/that/search/items/search+term <-- won't work - because the search controller isn't allowed.</p>
| [
{
"answer_id": 43623,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 1,
"selected": false,
"text": "<p>The best way to do this without any compromises would be to implement your own ControllerFactory by inheriting off of IControllerFactory. The CreateController method that you will implement handles creating the controller instance to handle the request by the RouteHandler and the ControllerActionInvoker. The convention is to use the name of the controller, when creating it, therefore you will need to override this functionality. This will be where you put your custom logic for creating the controller based on the route since you will have multiple controllers with the same name, but in different folders. Then you will need to register your custom controller factory in the application startup, just like your routes.</p>\n\n<p>Another area you will need to take into consideration is finding your views when creating the controller. If you plan on using the same view for all of them, then you shouldn't have to do anything different than the convention being used. If you plan on organizing your views also, then you will need to create your own ViewLocator also and assign it to the controller when creating it in your controller factory.</p>\n\n<p>To get an idea of code, there are a few questions I have answered on SO that relate to this question, but this one is different to some degree, because the controller names will be the same. I included links for reference.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc\">Views in separate assemblies in ASP.NET MVC</a></li>\n<li><a href=\"https://stackoverflow.com/questions/26715/aspnet-mvc-subfolders\">asp.net mvc - subfolders</a></li>\n</ul>\n\n<p>Another route, but may require some compromises will be to use the new AcceptVerbs attribute. Check this <a href=\"https://stackoverflow.com/questions/36197/aspnet-mvc-structuring-controllers\">question</a> out for more details. I haven't played with this new functionality yet, but it could be another route.</p>\n"
},
{
"answer_id": 45076,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 2,
"selected": false,
"text": "<p>I actually found it not even by searching, but by scanning through the ASP .NET forums in <a href=\"http://forums.asp.net/t/1296928.aspx?PageIndex=1\" rel=\"nofollow noreferrer\">this question</a>.</p>\n\n<p>Using this you can have the controllers of the same name under any part of the namespace, so long as you qualify which routes belong to which namespaces (you can have multiple namespaces per routes if you need be!)</p>\n\n<p>But from here, you can put in a directory under your controller, so if your controller was \"MyWebShop.Controllers\", you'd put a directory of \"Shop1\" and the namespace would be \"MyWebShop.Controllers.Shop1\"</p>\n\n<p>Then this works:</p>\n\n<pre><code> public static void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\n var shop1namespace = new RouteValueDictionary();\n shop1namespace.Add(\"namespaces\", new HashSet<string>(new string[] \n { \n \"MyWebShop.Controllers.Shop1\"\n }));\n\n routes.Add(\"Shop1\", new Route(\"Shop1/{controller}/{action}/{id}\", new MvcRouteHandler())\n {\n Defaults = new RouteValueDictionary(new\n {\n action = \"Index\",\n id = (string)null\n }),\n DataTokens = shop1namespace\n });\n\n var shop2namespace = new RouteValueDictionary();\n shop2namespace.Add(\"namespaces\", new HashSet<string>(new string[] \n { \n \"MyWebShop.Controllers.Shop2\"\n }));\n\n routes.Add(\"Shop2\", new Route(\"Shop2/{controller}/{action}/{id}\", new MvcRouteHandler())\n {\n Defaults = new RouteValueDictionary(new\n {\n action = \"Index\",\n id = (string)null\n }),\n DataTokens = shop2namespace\n });\n\n var defaultnamespace = new RouteValueDictionary();\n defaultnamespace.Add(\"namespaces\", new HashSet<string>(new string[] \n { \n \"MyWebShop.Controllers\"\n }));\n\n routes.Add(\"Default\", new Route(\"{controller}/{action}/{id}\", new MvcRouteHandler())\n {\n Defaults = new RouteValueDictionary(new { controller = \"Home\", action = \"Index\", id = \"\" }),\n DataTokens = defaultnamespace \n });\n }\n</code></pre>\n\n<p>The only other thing is that it will reference a view still in the base directory, so if you put the view into directories to match, you will have to put the view name in when you return it inside the controller.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] | I'm looking for some examples or samples of routing for the following sort of scenario:
The general example of doing things is: {controller}/{action}/{id}
So in the scenario of doing a product search for a store you'd have:
```
public class ProductsController: Controller
{
public ActionResult Search(string id) // id being the search string
{ ... }
}
```
Say you had a few stores to do this and you wanted that consistently, is there any way to then have: {category}/{controller}/{action}/{id}
So that you could have a particular search for a particular store, but use a different search method for a different store?
(If you required the store name to be a higher priority than the function itself in the url)
Or would it come down to:
```
public class ProductsController: Controller
{
public ActionResult Search(int category, string id) // id being the search string
{
if(category == 1) return Category1Search();
if(category == 2) return Category2Search();
...
}
}
```
It may not be a great example, but basically the idea is to use the same controller name and therefore have a simple URL across a few different scenarios, or are you kind of stuck with requiring unique controller names, and no way to put them in slightly different namespaces/directories?
Edit to add:
The other reason I want this is because I might want a url that has the categories, and that certain controllers will only work under certain categories.
IE:
/this/search/items/search+term <-- works
/that/search/items/search+term <-- won't work - because the search controller isn't allowed. | I actually found it not even by searching, but by scanning through the ASP .NET forums in [this question](http://forums.asp.net/t/1296928.aspx?PageIndex=1).
Using this you can have the controllers of the same name under any part of the namespace, so long as you qualify which routes belong to which namespaces (you can have multiple namespaces per routes if you need be!)
But from here, you can put in a directory under your controller, so if your controller was "MyWebShop.Controllers", you'd put a directory of "Shop1" and the namespace would be "MyWebShop.Controllers.Shop1"
Then this works:
```
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var shop1namespace = new RouteValueDictionary();
shop1namespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers.Shop1"
}));
routes.Add("Shop1", new Route("Shop1/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
action = "Index",
id = (string)null
}),
DataTokens = shop1namespace
});
var shop2namespace = new RouteValueDictionary();
shop2namespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers.Shop2"
}));
routes.Add("Shop2", new Route("Shop2/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
action = "Index",
id = (string)null
}),
DataTokens = shop2namespace
});
var defaultnamespace = new RouteValueDictionary();
defaultnamespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers"
}));
routes.Add("Default", new Route("{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
DataTokens = defaultnamespace
});
}
```
The only other thing is that it will reference a view still in the base directory, so if you put the view into directories to match, you will have to put the view name in when you return it inside the controller. |
43,218 | <p>I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.</p>
<p>However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.</p>
<p>Does anybody have any ideas for resolving this?</p>
| [
{
"answer_id": 43222,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 5,
"selected": true,
"text": "<p>If you reference the JS-file in a section that is \"runat=server\" you could write src=\"~/Javascript/jsfile.js\" and it will always work.</p>\n\n<p>You could also do this in your Page_Load (In your masterpage):</p>\n\n<pre><code>Page.ClientScript.RegisterClientScriptInclude(\"myJsFile\", Page.ResolveClientUrl(\"~/Javascript/jsfile.js\"))\n</code></pre>\n"
},
{
"answer_id": 43252,
"author": "Jared",
"author_id": 3442,
"author_profile": "https://Stackoverflow.com/users/3442",
"pm_score": 2,
"selected": false,
"text": "<p>Try something like this in the Master Page:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"<%= Response.ApplyAppPathModifier(\"~/javascript/globaljs.aspx\") %>\"></script>\n</code></pre>\n\n<p>For whatever reason, I've found the browsers to be quite finicky about the final tag, so just ending the tag with /> doesn't seem to work.</p>\n"
},
{
"answer_id": 43287,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 0,
"selected": false,
"text": "<p>@Jared: IE needs that /script . FF doesn't care.</p>\n"
},
{
"answer_id": 43734,
"author": "Brad Tutterow",
"author_id": 308,
"author_profile": "https://Stackoverflow.com/users/308",
"pm_score": 2,
"selected": false,
"text": "<p>The brand-new version of ASP.NET (<a href=\"http://msdn.microsoft.com/en-us/vstudio/products/cc533447.aspx\" rel=\"nofollow noreferrer\">3.5 SP1</a>) has a nifty feature called <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.compositescriptreference.aspx\" rel=\"nofollow noreferrer\">CompositeScript</a>. This allows you to use a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.scriptreference.aspx\" rel=\"nofollow noreferrer\">ScriptManager</a> to reference lots of tiny little .js files server-side and have them delivered as a single .js file to the client. </p>\n\n<p>Good for the client since it only has to download one file. Good for you since you can maintain the files however you want on the server side.</p>\n\n<pre><code><asp:ScriptManager ID=\"ScriptManager1\" \n EnablePartialRendering=\"True\"\n runat=\"server\">\n <Scripts>\n <asp:ScriptReference \n Assembly=\"SampleControl\" \n Name=\"SampleControl.UpdatePanelAnimation.js\" />\n </Scripts>\n</asp:ScriptManager>\n</code></pre>\n"
},
{
"answer_id": 262558,
"author": "Chris Zwiryk",
"author_id": 734,
"author_profile": "https://Stackoverflow.com/users/734",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to take a look at <a href=\"http://www.codeproject.com/KB/aspnet/UsingTheFileResolver.aspx\" rel=\"nofollow noreferrer\">FileResolver</a>. It's an HTTP Handler that allows you to do this:</p>\n\n<pre><code><link rel=\"stylesheet\" href=\"~/resources/stylesheet.css.ashx\" />\n</code></pre>\n\n<p>And have the tilde (as well as any tildes within the file) expanded properly.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.
However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.
Does anybody have any ideas for resolving this? | If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work.
You could also do this in your Page\_Load (In your masterpage):
```
Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js"))
``` |
43,249 | <p>Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure? </p>
<p>For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it. </p>
<p>SQL Server 2005 is my only applicable limitation I think.</p>
<pre><code>create procedure getDepartments
@DepartmentIds varchar(max)
as
declare @Sql varchar(max)
select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')'
exec(@Sql)
</code></pre>
| [
{
"answer_id": 43260,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": false,
"text": "<p>Yeah, your current solution is prone to SQL injection attacks.</p>\n\n<p>The best solution that I've found is to use a function that splits text into words (there are a few posted here, or you can use <a href=\"http://www.madprops.org/blog/splitting-text-into-words-in-sql-revisited/\" rel=\"noreferrer\">this one from my blog</a>) and then join that to your table. Something like:</p>\n\n<pre><code>SELECT d.[Name]\nFROM Department d\n JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId\n</code></pre>\n"
},
{
"answer_id": 43263,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 2,
"selected": false,
"text": "<p>You could use XML. </p>\n\n<p>E.g. </p>\n\n<pre><code>declare @xmlstring as varchar(100) \nset @xmlstring = '<args><arg value=\"42\" /><arg2>-1</arg2></args>' \n\ndeclare @docid int \n\nexec sp_xml_preparedocument @docid output, @xmlstring\n\nselect [id],parentid,nodetype,localname,[text]\nfrom openxml(@docid, '/args', 1) \n</code></pre>\n\n<p>The command <a href=\"http://msdn.microsoft.com/en-us/library/ms187367.aspx\" rel=\"nofollow noreferrer\">sp_xml_preparedocument</a> is built in. </p>\n\n<p>This would produce the output: </p>\n\n<pre><code>id parentid nodetype localname text\n0 NULL 1 args NULL\n2 0 1 arg NULL\n3 2 2 value NULL\n5 3 3 #text 42\n4 0 1 arg2 NULL\n6 4 3 #text -1\n</code></pre>\n\n<p>which has all (more?) of what you you need.</p>\n"
},
{
"answer_id": 43767,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 9,
"selected": true,
"text": "<p>Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: <em><a href=\"http://www.sommarskog.se/arrays-in-sql.html\" rel=\"noreferrer\">Arrays and Lists in SQL Server</a></em>.</p>\n\n<p>There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons. </p>\n\n<ul>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2008.html\" rel=\"noreferrer\">Table-Valued Parameters</a>. SQL Server 2008 and higher only, and probably the closest to a universal \"best\" approach.</li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#iterative\" rel=\"noreferrer\">The Iterative Method</a>. Pass a delimited string and loop through it. </li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#CLR\" rel=\"noreferrer\">Using the CLR</a>. SQL Server 2005 and higher from .NET languages only. </li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#XML\" rel=\"noreferrer\">XML</a>. Very good for inserting many rows; may be overkill for SELECTs.</li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#tblnum\" rel=\"noreferrer\">Table of Numbers</a>. Higher performance/complexity than simple iterative method.</li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#fixed-length\" rel=\"noreferrer\">Fixed-length Elements</a>. Fixed length improves speed over the delimited string</li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#fn_nums\" rel=\"noreferrer\">Function of Numbers</a>. Variations of Table of Numbers and fixed-length where the number are generated in a function rather than taken from a table.</li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#CTEs\" rel=\"noreferrer\">Recursive Common Table Expression</a> (CTE). SQL Server 2005 and higher, still not too complex and higher performance than iterative method.</li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#dynamic-sql\" rel=\"noreferrer\">Dynamic SQL</a>. Can be slow and has security implications. </li>\n<li>Passing the List as <a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#manyparameters\" rel=\"noreferrer\">Many Parameters</a>. Tedious and error prone, but simple. </li>\n<li><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#realslow\" rel=\"noreferrer\">Really Slow Methods</a>. Methods that uses charindex, patindex or LIKE.</li>\n</ul>\n\n<p>I really can't recommend enough to <a href=\"http://www.sommarskog.se/arrays-in-sql.html\" rel=\"noreferrer\">read the article</a> to learn about the tradeoffs among all these options.</p>\n"
},
{
"answer_id": 44136,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 2,
"selected": false,
"text": "<p>One method you might want to consider if you're going to be working with the values a lot is to write them to a temporary table first. Then you just join on it like normal.</p>\n\n<p>This way, you're only parsing once.</p>\n\n<p>It's easiest to use one of the 'Split' UDFs, but so many people have posted examples of those, I figured I'd go a different route ;)</p>\n\n<p>This example will create a temporary table for you to join on (#tmpDept) and fill it with the department id's that you passed in. I'm assuming you're separating them with commas, but you can -- of course -- change it to whatever you want.</p>\n\n<pre><code>IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL\nBEGIN\n DROP TABLE #tmpDept\nEND\n\nSET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','')\n\nCREATE TABLE #tmpDept (DeptID INT)\nDECLARE @DeptID INT\nIF IsNumeric(@DepartmentIDs)=1\nBEGIN\n SET @DeptID=@DepartmentIDs\n INSERT INTO #tmpDept (DeptID) SELECT @DeptID\nEND\nELSE\nBEGIN\n WHILE CHARINDEX(',',@DepartmentIDs)>0\n BEGIN\n SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1)\n SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs))\n INSERT INTO #tmpDept (DeptID) SELECT @DeptID\n END\nEND\n</code></pre>\n\n<p>This will allow you to pass in one department id, multiple id's with commas in between them, or even multiple id's with commas and spaces between them.</p>\n\n<p>So if you did something like:</p>\n\n<pre><code>SELECT Dept.Name \nFROM Departments \nJOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID\nORDER BY Dept.Name\n</code></pre>\n\n<p>You would see the names of all of the department IDs that you passed in...</p>\n\n<p>Again, this can be simplified by using a function to populate the temporary table... I mainly did it without one just to kill some boredom :-P</p>\n\n<p>-- Kevin Fairchild</p>\n"
},
{
"answer_id": 15191592,
"author": "Nishant",
"author_id": 2089165,
"author_profile": "https://Stackoverflow.com/users/2089165",
"pm_score": 2,
"selected": false,
"text": "<p>A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs : </p>\n\n<pre><code>Declare @XMLList xml\nSET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)\nSELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))\n</code></pre>\n\n<p>All credit goes to Guru <a href=\"http://beyondrelational.com/modules/2/blogs/114/posts/14617/delimited-string-tennis-anyone.aspx\" rel=\"nofollow\">Brad Schulz's Blog</a></p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865/"
] | Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure?
For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it.
SQL Server 2005 is my only applicable limitation I think.
```
create procedure getDepartments
@DepartmentIds varchar(max)
as
declare @Sql varchar(max)
select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')'
exec(@Sql)
``` | Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: *[Arrays and Lists in SQL Server](http://www.sommarskog.se/arrays-in-sql.html)*.
There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons.
* [Table-Valued Parameters](http://www.sommarskog.se/arrays-in-sql-2008.html). SQL Server 2008 and higher only, and probably the closest to a universal "best" approach.
* [The Iterative Method](http://www.sommarskog.se/arrays-in-sql-2005.html#iterative). Pass a delimited string and loop through it.
* [Using the CLR](http://www.sommarskog.se/arrays-in-sql-2005.html#CLR). SQL Server 2005 and higher from .NET languages only.
* [XML](http://www.sommarskog.se/arrays-in-sql-2005.html#XML). Very good for inserting many rows; may be overkill for SELECTs.
* [Table of Numbers](http://www.sommarskog.se/arrays-in-sql-2005.html#tblnum). Higher performance/complexity than simple iterative method.
* [Fixed-length Elements](http://www.sommarskog.se/arrays-in-sql-2005.html#fixed-length). Fixed length improves speed over the delimited string
* [Function of Numbers](http://www.sommarskog.se/arrays-in-sql-2005.html#fn_nums). Variations of Table of Numbers and fixed-length where the number are generated in a function rather than taken from a table.
* [Recursive Common Table Expression](http://www.sommarskog.se/arrays-in-sql-2005.html#CTEs) (CTE). SQL Server 2005 and higher, still not too complex and higher performance than iterative method.
* [Dynamic SQL](http://www.sommarskog.se/arrays-in-sql-2005.html#dynamic-sql). Can be slow and has security implications.
* Passing the List as [Many Parameters](http://www.sommarskog.se/arrays-in-sql-2005.html#manyparameters). Tedious and error prone, but simple.
* [Really Slow Methods](http://www.sommarskog.se/arrays-in-sql-2005.html#realslow). Methods that uses charindex, patindex or LIKE.
I really can't recommend enough to [read the article](http://www.sommarskog.se/arrays-in-sql.html) to learn about the tradeoffs among all these options. |
43,289 | <p>How can I do this fast?</p>
<p>Sure I can do this:</p>
<pre><code>static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if (a1.Length != a2.Length)
return false;
for (int i=0; i<a1.Length; i++)
if (a1[i]!=a2[i])
return false;
return true;
}
</code></pre>
<p>But I'm looking for either a <a href="https://en.wikipedia.org/wiki/Standard_Libraries_%28CLI%29#Base_Class_Library" rel="noreferrer">BCL</a> function or some highly optimized proven way to do this.</p>
<pre><code>java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2);
</code></pre>
<p>works nicely, but it doesn't look like that would work for x64.</p>
<p>Note my super-fast answer <a href="https://stackoverflow.com/a/8808245/4489">here</a>.</p>
| [
{
"answer_id": 43300,
"author": "gil",
"author_id": 195,
"author_profile": "https://Stackoverflow.com/users/195",
"pm_score": 3,
"selected": false,
"text": "<p>I would use unsafe code and run the <code>for</code> loop comparing Int32 pointers.</p>\n\n<p>Maybe you should also consider checking the arrays to be non-null.</p>\n"
},
{
"answer_id": 43303,
"author": "Markus Olsson",
"author_id": 2114,
"author_profile": "https://Stackoverflow.com/users/2114",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry, if you're looking for a managed way you're already doing it correctly and to my knowledge there's no built in method in the BCL for doing this.</p>\n\n<p>You should add some initial null checks and then just reuse it as if it where in BCL.</p>\n"
},
{
"answer_id": 43305,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 5,
"selected": false,
"text": "<p>If you are not opposed to doing it, you can import the J# assembly \"vjslib.dll\" and use its <a href=\"http://msdn.microsoft.com/en-us/library/aa988508(VS.80).aspx\" rel=\"noreferrer\"><strong>Arrays.equals(byte[], byte[]) method</strong></a>...</p>\n\n<p>Don't blame me if someone laughs at you though...</p>\n\n<hr>\n\n<p>EDIT: For what little it is worth, I used Reflector to disassemble the code for that, and here is what it looks like:</p>\n\n<pre><code>public static bool equals(sbyte[] a1, sbyte[] a2)\n{\n if (a1 == a2)\n {\n return true;\n }\n if ((a1 != null) && (a2 != null))\n {\n if (a1.Length != a2.Length)\n {\n return false;\n }\n for (int i = 0; i < a1.Length; i++)\n {\n if (a1[i] != a2[i])\n {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 43310,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 9,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/bb348567.aspx\" rel=\"noreferrer\">Enumerable.SequenceEqual</a> method.</p>\n\n<pre><code>using System;\nusing System.Linq;\n...\nvar a1 = new int[] { 1, 2, 3};\nvar a2 = new int[] { 1, 2, 3};\nvar a3 = new int[] { 1, 2, 4};\nvar x = a1.SequenceEqual(a2); // true\nvar y = a1.SequenceEqual(a3); // false\n</code></pre>\n\n<p>If you can't use .NET 3.5 for some reason, your method is OK.<br>\nCompiler\\run-time environment will optimize your loop so you don't need to worry about performance. </p>\n"
},
{
"answer_id": 811292,
"author": "Milan Gardian",
"author_id": 23843,
"author_profile": "https://Stackoverflow.com/users/23843",
"pm_score": 5,
"selected": false,
"text": "<p>.NET 3.5 and newer have a new public type, <code>System.Data.Linq.Binary</code> that encapsulates <code>byte[]</code>. It implements <code>IEquatable<Binary></code> that (in effect) compares two byte arrays. Note that <code>System.Data.Linq.Binary</code> also has implicit conversion operator from <code>byte[]</code>.</p>\n\n<p>MSDN documentation:<a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.binary(loband).aspx\" rel=\"noreferrer\">System.Data.Linq.Binary</a></p>\n\n<p>Reflector decompile of the Equals method:</p>\n\n<pre><code>private bool EqualsTo(Binary binary)\n{\n if (this != binary)\n {\n if (binary == null)\n {\n return false;\n }\n if (this.bytes.Length != binary.bytes.Length)\n {\n return false;\n }\n if (this.hashCode != binary.hashCode)\n {\n return false;\n }\n int index = 0;\n int length = this.bytes.Length;\n while (index < length)\n {\n if (this.bytes[index] != binary.bytes[index])\n {\n return false;\n }\n index++;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Interesting twist is that they only proceed to byte-by-byte comparison loop if hashes of the two Binary objects are the same. This, however, comes at the cost of computing the hash in constructor of <code>Binary</code> objects (by traversing the array with <code>for</code> loop :-) ).</p>\n\n<p>The above implementation means that in the worst case you may have to traverse the arrays three times: first to compute hash of array1, then to compute hash of array2 and finally (because this is the worst case scenario, lengths and hashes equal) to compare bytes in array1 with bytes in array 2.</p>\n\n<p>Overall, even though <code>System.Data.Linq.Binary</code> is built into BCL, I don't think it is the fastest way to compare two byte arrays :-|.</p>\n"
},
{
"answer_id": 1244181,
"author": "Mirko Klemm",
"author_id": 488454,
"author_profile": "https://Stackoverflow.com/users/488454",
"pm_score": 2,
"selected": false,
"text": "<p>I thought about block-transfer acceleration methods built into many graphics cards. But then you would have to copy over all the data byte-wise, so this doesn't help you much if you don't want to implement a whole portion of your logic in unmanaged and hardware-dependent code...</p>\n\n<p>Another way of optimization similar to the approach shown above would be to store as much of your data as possible in a long[] rather than a byte[] right from the start, for example if you are reading it sequentially from a binary file, or if you use a memory mapped file, read in data as long[] or single long values. Then, your comparison loop will only need 1/8th of the number of iterations it would have to do for a byte[] containing the same amount of data.\nIt is a matter of when and how often you need to compare vs. when and how often you need to access the data in a byte-by-byte manner, e.g. to use it in an API call as a parameter in a method that expects a byte[]. In the end, you only can tell if you really know the use case...</p>\n"
},
{
"answer_id": 1252217,
"author": "Mikael Svenson",
"author_id": 153390,
"author_profile": "https://Stackoverflow.com/users/153390",
"pm_score": 3,
"selected": false,
"text": "<p>If you look at how .NET does string.Equals, you see that it uses a private method called EqualsHelper which has an \"unsafe\" pointer implementation. <a href=\"http://en.wikipedia.org/wiki/.NET_Reflector\" rel=\"nofollow noreferrer\">.NET Reflector</a> is your friend to see how things are done internally.</p>\n\n<p>This can be used as a template for byte array comparison which I did an implementation on in blog post <em><a href=\"http://techmikael.blogspot.com/2009/01/fast-byte-array-comparison-in-c.html\" rel=\"nofollow noreferrer\">Fast byte array comparison in C#</a></em>. I also did some rudimentary benchmarks to see when a safe implementation is faster than the unsafe.</p>\n\n<p>That said, unless you really need killer performance, I'd go for a simple fr loop comparison.</p>\n"
},
{
"answer_id": 1445280,
"author": "Kevin Driedger",
"author_id": 9587,
"author_profile": "https://Stackoverflow.com/users/9587",
"pm_score": 2,
"selected": false,
"text": "<p>For comparing short byte arrays the following is an interesting hack:</p>\n\n<pre><code>if(myByteArray1.Length != myByteArray2.Length) return false;\nif(myByteArray1.Length == 8)\n return BitConverter.ToInt64(myByteArray1, 0) == BitConverter.ToInt64(myByteArray2, 0); \nelse if(myByteArray.Length == 4)\n return BitConverter.ToInt32(myByteArray2, 0) == BitConverter.ToInt32(myByteArray2, 0); \n</code></pre>\n\n<p>Then I would probably fall out to the solution listed in the question.</p>\n\n<p>It'd be interesting to do a performance analysis of this code.</p>\n"
},
{
"answer_id": 1445405,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Platform_Invocation_Services\" rel=\"noreferrer\">P/Invoke</a> powers activate!</p>\n\n<pre><code>[DllImport(\"msvcrt.dll\", CallingConvention=CallingConvention.Cdecl)]\nstatic extern int memcmp(byte[] b1, byte[] b2, long count);\n\nstatic bool ByteArrayCompare(byte[] b1, byte[] b2)\n{\n // Validate buffers are the same length.\n // This also ensures that the count does not exceed the length of either buffer. \n return b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0;\n}\n</code></pre>\n"
},
{
"answer_id": 4617030,
"author": "user565710",
"author_id": 565710,
"author_profile": "https://Stackoverflow.com/users/565710",
"pm_score": 4,
"selected": false,
"text": "<pre><code> using System.Linq; //SequenceEqual\n\n byte[] ByteArray1 = null;\n byte[] ByteArray2 = null;\n\n ByteArray1 = MyFunct1();\n ByteArray2 = MyFunct2();\n\n if (ByteArray1.SequenceEqual<byte>(ByteArray2) == true)\n {\n MessageBox.Show(\"Match\");\n }\n else\n {\n MessageBox.Show(\"Don't match\");\n }\n</code></pre>\n"
},
{
"answer_id": 8140664,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 7,
"selected": false,
"text": "<p>There's a new built-in solution for this in .NET 4 - <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.istructuralequatable.aspx\">IStructuralEquatable</a></p>\n\n<pre><code>static bool ByteArrayCompare(byte[] a1, byte[] a2) \n{\n return StructuralComparisons.StructuralEqualityComparer.Equals(a1, a2);\n}\n</code></pre>\n"
},
{
"answer_id": 8808245,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 7,
"selected": true,
"text": "<p>Edit: modern fast way is to use <code>a1.SequenceEquals(a2)</code></p>\n<p>User <em>gil</em> suggested unsafe code which spawned this solution:</p>\n<pre><code>// Copyright (c) 2008-2013 Hafthor Stefansson\n// Distributed under the MIT/X11 software license\n// Ref: http://www.opensource.org/licenses/mit-license.php.\nstatic unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {\n unchecked {\n if(a1==a2) return true;\n if(a1==null || a2==null || a1.Length!=a2.Length)\n return false;\n fixed (byte* p1=a1, p2=a2) {\n byte* x1=p1, x2=p2;\n int l = a1.Length;\n for (int i=0; i < l/8; i++, x1+=8, x2+=8)\n if (*((long*)x1) != *((long*)x2)) return false;\n if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }\n if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }\n if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;\n return true;\n }\n }\n}\n</code></pre>\n<p>which does 64-bit based comparison for as much of the array as possible. This kind of counts on the fact that the arrays start qword aligned. It'll work if not qword aligned, just not as fast as if it were.</p>\n<p>It performs about seven timers faster than the simple `for` loop. Using the J# library performed equivalently to the original `for` loop. Using .SequenceEqual runs around seven times slower; I think just because it is using IEnumerator.MoveNext. I imagine LINQ-based solutions being at least that slow or worse.\n"
},
{
"answer_id": 24529567,
"author": "Kris Dimitrov",
"author_id": 1024488,
"author_profile": "https://Stackoverflow.com/users/1024488",
"pm_score": -1,
"selected": false,
"text": "<p>If you are looking for a very fast byte array equality comparer, I suggest you take a look at this STSdb Labs article: <a href=\"http://stsdb.com/forum/stsdb-4-x/sts-labs/466-byte-array-equality-comparer.html#post1249\" rel=\"nofollow\">Byte array equality comparer.</a> It features some of the fastest implementations for byte[] array equality comparing, which are presented, performance tested and summarized.</p>\n\n<p>You can also focus on these implementations:</p>\n\n<p><a href=\"http://svn.stsdb.com:221/svn/STSdb/STSdb4/STSdb4/General/Comparers/BigEndianByteArrayComparer.cs\" rel=\"nofollow\">BigEndianByteArrayComparer</a> - fast byte[] array comparer from left to right (BigEndian)\n<a href=\"http://svn.stsdb.com:221/svn/STSdb/STSdb4/STSdb4/General/Comparers/BigEndianByteArrayComparer.cs\" rel=\"nofollow\">BigEndianByteArrayEqualityComparer</a> - - fast byte[] equality comparer from left to right (BigEndian)\n<a href=\"http://svn.stsdb.com:221/svn/STSdb/STSdb4/STSdb4/General/Comparers/BigEndianByteArrayEqualityComparer.cs\" rel=\"nofollow\">LittleEndianByteArrayComparer</a> - fast byte[] array comparer from right to left (LittleEndian)\n<a href=\"http://svn.stsdb.com:221/svn/STSdb/STSdb4/STSdb4/General/Comparers/LittleEndianByteArrayEqualityComparer.cs\" rel=\"nofollow\">LittleEndianByteArrayEqualityComparer</a> - fast byte[] equality comparer from right to left (LittleEndian)</p>\n"
},
{
"answer_id": 29831846,
"author": "API_Base",
"author_id": 4691027,
"author_profile": "https://Stackoverflow.com/users/4691027",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>SequenceEquals</code> for this to comparison.</p>\n"
},
{
"answer_id": 30740076,
"author": "Alon",
"author_id": 2327376,
"author_profile": "https://Stackoverflow.com/users/2327376",
"pm_score": -1,
"selected": false,
"text": "<p>The short answer is this:</p>\n\n<pre><code> public bool Compare(byte[] b1, byte[] b2)\n {\n return Encoding.ASCII.GetString(b1) == Encoding.ASCII.GetString(b2);\n }\n</code></pre>\n\n<p>In such a way you can use the optimized .NET string compare to make a byte array compare without the need to write unsafe code. This is how it is done in the <a href=\"http://referencesource.microsoft.com/#mscorlib/system/string.cs,11648d2d83718c5e\" rel=\"nofollow\">background</a>:</p>\n\n<pre><code>private unsafe static bool EqualsHelper(String strA, String strB)\n{\n Contract.Requires(strA != null);\n Contract.Requires(strB != null);\n Contract.Requires(strA.Length == strB.Length);\n\n int length = strA.Length;\n\n fixed (char* ap = &strA.m_firstChar) fixed (char* bp = &strB.m_firstChar)\n {\n char* a = ap;\n char* b = bp;\n\n // Unroll the loop\n\n #if AMD64\n // For the AMD64 bit platform we unroll by 12 and\n // check three qwords at a time. This is less code\n // than the 32 bit case and is shorter\n // pathlength.\n\n while (length >= 12)\n {\n if (*(long*)a != *(long*)b) return false;\n if (*(long*)(a+4) != *(long*)(b+4)) return false;\n if (*(long*)(a+8) != *(long*)(b+8)) return false;\n a += 12; b += 12; length -= 12;\n }\n #else\n while (length >= 10)\n {\n if (*(int*)a != *(int*)b) return false;\n if (*(int*)(a+2) != *(int*)(b+2)) return false;\n if (*(int*)(a+4) != *(int*)(b+4)) return false;\n if (*(int*)(a+6) != *(int*)(b+6)) return false;\n if (*(int*)(a+8) != *(int*)(b+8)) return false;\n a += 10; b += 10; length -= 10;\n }\n #endif\n\n // This depends on the fact that the String objects are\n // always zero terminated and that the terminating zero is not included\n // in the length. For odd string sizes, the last compare will include\n // the zero terminator.\n while (length > 0)\n {\n if (*(int*)a != *(int*)b) break;\n a += 2; b += 2; length -= 2;\n }\n\n return (length <= 0);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 33307903,
"author": "ArekBulski",
"author_id": 2375119,
"author_profile": "https://Stackoverflow.com/users/2375119",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/33294580/sse-instruction-to-check-if-byte-array-is-zeroes-c-sharp\">I posted</a> a similar question about checking if byte[] is full of zeroes. (SIMD code was beaten so I removed it from this answer.) Here is fastest code from my comparisons:</p>\n\n<pre><code>static unsafe bool EqualBytesLongUnrolled (byte[] data1, byte[] data2)\n{\n if (data1 == data2)\n return true;\n if (data1.Length != data2.Length)\n return false;\n\n fixed (byte* bytes1 = data1, bytes2 = data2) {\n int len = data1.Length;\n int rem = len % (sizeof(long) * 16);\n long* b1 = (long*)bytes1;\n long* b2 = (long*)bytes2;\n long* e1 = (long*)(bytes1 + len - rem);\n\n while (b1 < e1) {\n if (*(b1) != *(b2) || *(b1 + 1) != *(b2 + 1) || \n *(b1 + 2) != *(b2 + 2) || *(b1 + 3) != *(b2 + 3) ||\n *(b1 + 4) != *(b2 + 4) || *(b1 + 5) != *(b2 + 5) || \n *(b1 + 6) != *(b2 + 6) || *(b1 + 7) != *(b2 + 7) ||\n *(b1 + 8) != *(b2 + 8) || *(b1 + 9) != *(b2 + 9) || \n *(b1 + 10) != *(b2 + 10) || *(b1 + 11) != *(b2 + 11) ||\n *(b1 + 12) != *(b2 + 12) || *(b1 + 13) != *(b2 + 13) || \n *(b1 + 14) != *(b2 + 14) || *(b1 + 15) != *(b2 + 15))\n return false;\n b1 += 16;\n b2 += 16;\n }\n\n for (int i = 0; i < rem; i++)\n if (data1 [len - 1 - i] != data2 [len - 1 - i])\n return false;\n\n return true;\n }\n}\n</code></pre>\n\n<p>Measured on two 256MB byte arrays:</p>\n\n<pre><code>UnsafeCompare : 86,8784 ms\nEqualBytesSimd : 71,5125 ms\nEqualBytesSimdUnrolled : 73,1917 ms\nEqualBytesLongUnrolled : 39,8623 ms\n</code></pre>\n"
},
{
"answer_id": 36291188,
"author": "Zar Shardan",
"author_id": 913845,
"author_profile": "https://Stackoverflow.com/users/913845",
"pm_score": 2,
"selected": false,
"text": "<p>Couldn't find a solution I'm completely happy with (reasonable performance, but no unsafe code/pinvoke) so I came up with this, nothing really original, but works:</p>\n\n<pre><code> /// <summary>\n /// \n /// </summary>\n /// <param name=\"array1\"></param>\n /// <param name=\"array2\"></param>\n /// <param name=\"bytesToCompare\"> 0 means compare entire arrays</param>\n /// <returns></returns>\n public static bool ArraysEqual(byte[] array1, byte[] array2, int bytesToCompare = 0)\n {\n if (array1.Length != array2.Length) return false;\n\n var length = (bytesToCompare == 0) ? array1.Length : bytesToCompare;\n var tailIdx = length - length % sizeof(Int64);\n\n //check in 8 byte chunks\n for (var i = 0; i < tailIdx; i += sizeof(Int64))\n {\n if (BitConverter.ToInt64(array1, i) != BitConverter.ToInt64(array2, i)) return false;\n }\n\n //check the remainder of the array, always shorter than 8 bytes\n for (var i = tailIdx; i < length; i++)\n {\n if (array1[i] != array2[i]) return false;\n }\n\n return true;\n }\n</code></pre>\n\n<p>Performance compared with some of the other solutions on this page:</p>\n\n<p>Simple Loop: 19837 ticks, 1.00</p>\n\n<p>*BitConverter: 4886 ticks, 4.06</p>\n\n<p>UnsafeCompare: 1636 ticks, 12.12</p>\n\n<p>EqualBytesLongUnrolled: 637 ticks, 31.09</p>\n\n<p>P/Invoke memcmp: 369 ticks, 53.67</p>\n\n<p>Tested in linqpad, 1000000 bytes identical arrays (worst case scenario), 500 iterations each.</p>\n"
},
{
"answer_id": 38002854,
"author": "Mr Anderson",
"author_id": 6196648,
"author_profile": "https://Stackoverflow.com/users/6196648",
"pm_score": 3,
"selected": false,
"text": "<p>I developed a method that slightly beats <code>memcmp()</code> (plinth's answer) and very slighly beats <code>EqualBytesLongUnrolled()</code> (Arek Bulski's answer) on my PC. Basically, it unrolls the loop by 4 instead of 8.</p>\n\n<p><strong>Update 30 Mar. 2019</strong>:</p>\n\n<p>Starting in .NET core 3.0, we have SIMD support!</p>\n\n<p>This solution is fastest by a considerable margin on my PC:</p>\n\n<pre><code>#if NETCOREAPP3_0\nusing System.Runtime.Intrinsics.X86;\n#endif\n…\n\npublic static unsafe bool Compare(byte[] arr0, byte[] arr1)\n{\n if (arr0 == arr1)\n {\n return true;\n }\n if (arr0 == null || arr1 == null)\n {\n return false;\n }\n if (arr0.Length != arr1.Length)\n {\n return false;\n }\n if (arr0.Length == 0)\n {\n return true;\n }\n fixed (byte* b0 = arr0, b1 = arr1)\n {\n#if NETCOREAPP3_0\n if (Avx2.IsSupported)\n {\n return Compare256(b0, b1, arr0.Length);\n }\n else if (Sse2.IsSupported)\n {\n return Compare128(b0, b1, arr0.Length);\n }\n else\n#endif\n {\n return Compare64(b0, b1, arr0.Length);\n }\n }\n}\n#if NETCOREAPP3_0\npublic static unsafe bool Compare256(byte* b0, byte* b1, int length)\n{\n byte* lastAddr = b0 + length;\n byte* lastAddrMinus128 = lastAddr - 128;\n const int mask = -1;\n while (b0 < lastAddrMinus128) // unroll the loop so that we are comparing 128 bytes at a time.\n {\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0), Avx.LoadVector256(b1))) != mask)\n {\n return false;\n }\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 32), Avx.LoadVector256(b1 + 32))) != mask)\n {\n return false;\n }\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 64), Avx.LoadVector256(b1 + 64))) != mask)\n {\n return false;\n }\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 96), Avx.LoadVector256(b1 + 96))) != mask)\n {\n return false;\n }\n b0 += 128;\n b1 += 128;\n }\n while (b0 < lastAddr)\n {\n if (*b0 != *b1) return false;\n b0++;\n b1++;\n }\n return true;\n}\npublic static unsafe bool Compare128(byte* b0, byte* b1, int length)\n{\n byte* lastAddr = b0 + length;\n byte* lastAddrMinus64 = lastAddr - 64;\n const int mask = 0xFFFF;\n while (b0 < lastAddrMinus64) // unroll the loop so that we are comparing 64 bytes at a time.\n {\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0), Sse2.LoadVector128(b1))) != mask)\n {\n return false;\n }\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 16), Sse2.LoadVector128(b1 + 16))) != mask)\n {\n return false;\n }\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 32), Sse2.LoadVector128(b1 + 32))) != mask)\n {\n return false;\n }\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 48), Sse2.LoadVector128(b1 + 48))) != mask)\n {\n return false;\n }\n b0 += 64;\n b1 += 64;\n }\n while (b0 < lastAddr)\n {\n if (*b0 != *b1) return false;\n b0++;\n b1++;\n }\n return true;\n}\n#endif\npublic static unsafe bool Compare64(byte* b0, byte* b1, int length)\n{\n byte* lastAddr = b0 + length;\n byte* lastAddrMinus32 = lastAddr - 32;\n while (b0 < lastAddrMinus32) // unroll the loop so that we are comparing 32 bytes at a time.\n {\n if (*(ulong*)b0 != *(ulong*)b1) return false;\n if (*(ulong*)(b0 + 8) != *(ulong*)(b1 + 8)) return false;\n if (*(ulong*)(b0 + 16) != *(ulong*)(b1 + 16)) return false;\n if (*(ulong*)(b0 + 24) != *(ulong*)(b1 + 24)) return false;\n b0 += 32;\n b1 += 32;\n }\n while (b0 < lastAddr)\n {\n if (*b0 != *b1) return false;\n b0++;\n b1++;\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 39701555,
"author": "Motlicek Petr",
"author_id": 819843,
"author_profile": "https://Stackoverflow.com/users/819843",
"pm_score": 2,
"selected": false,
"text": "<p>It seems that <em>EqualBytesLongUnrolled</em> is the best from the above suggested.</p>\n\n<p>Skipped methods (Enumerable.SequenceEqual,StructuralComparisons.StructuralEqualityComparer.Equals), were not-patient-for-slow. On 265MB arrays I have measured this:</p>\n\n<pre><code>Host Process Environment Information:\nBenchmarkDotNet.Core=v0.9.9.0\nOS=Microsoft Windows NT 6.2.9200.0\nProcessor=Intel(R) Core(TM) i7-3770 CPU 3.40GHz, ProcessorCount=8\nFrequency=3323582 ticks, Resolution=300.8802 ns, Timer=TSC\nCLR=MS.NET 4.0.30319.42000, Arch=64-bit RELEASE [RyuJIT]\nGC=Concurrent Workstation\nJitModules=clrjit-v4.6.1590.0\n\nType=CompareMemoriesBenchmarks Mode=Throughput \n\n Method | Median | StdDev | Scaled | Scaled-SD |\n----------------------- |------------ |---------- |------- |---------- |\n NewMemCopy | 30.0443 ms | 1.1880 ms | 1.00 | 0.00 |\n EqualBytesLongUnrolled | 29.9917 ms | 0.7480 ms | 0.99 | 0.04 |\n msvcrt_memcmp | 30.0930 ms | 0.2964 ms | 1.00 | 0.03 |\n UnsafeCompare | 31.0520 ms | 0.7072 ms | 1.03 | 0.04 |\n ByteArrayCompare | 212.9980 ms | 2.0776 ms | 7.06 | 0.25 |\n</code></pre>\n\n<hr>\n\n<pre><code>OS=Windows\nProcessor=?, ProcessorCount=8\nFrequency=3323582 ticks, Resolution=300.8802 ns, Timer=TSC\nCLR=CORE, Arch=64-bit ? [RyuJIT]\nGC=Concurrent Workstation\ndotnet cli version: 1.0.0-preview2-003131\n\nType=CompareMemoriesBenchmarks Mode=Throughput \n\n Method | Median | StdDev | Scaled | Scaled-SD |\n----------------------- |------------ |---------- |------- |---------- |\n NewMemCopy | 30.1789 ms | 0.0437 ms | 1.00 | 0.00 |\n EqualBytesLongUnrolled | 30.1985 ms | 0.1782 ms | 1.00 | 0.01 |\n msvcrt_memcmp | 30.1084 ms | 0.0660 ms | 1.00 | 0.00 |\n UnsafeCompare | 31.1845 ms | 0.4051 ms | 1.03 | 0.01 |\n ByteArrayCompare | 212.0213 ms | 0.1694 ms | 7.03 | 0.01 |\n</code></pre>\n"
},
{
"answer_id": 43191293,
"author": "Eli Arbel",
"author_id": 276083,
"author_profile": "https://Stackoverflow.com/users/276083",
"pm_score": 4,
"selected": false,
"text": "<p>Let's add one more!</p>\n\n<p>Recently Microsoft released a special NuGet package, <a href=\"https://www.nuget.org/packages/System.Runtime.CompilerServices.Unsafe\" rel=\"noreferrer\">System.Runtime.CompilerServices.Unsafe</a>. It's special because it's written in <a href=\"https://github.com/dotnet/corefx/blob/50ec3a52306df5e96d9d90543f8a6941e699b8d3/src/System.Runtime.CompilerServices.Unsafe/src/System.Runtime.CompilerServices.Unsafe.il\" rel=\"noreferrer\">IL</a>, and provides low-level functionality not directly available in C#.</p>\n\n<p>One of its methods, <code>Unsafe.As<T>(object)</code> allows casting any reference type to another reference type, skipping any safety checks. This is usually a <strong>very</strong> bad idea, but if both types have the same structure, it can work. So we can use this to cast a <code>byte[]</code> to a <code>long[]</code>:</p>\n\n<pre><code>bool CompareWithUnsafeLibrary(byte[] a1, byte[] a2)\n{\n if (a1.Length != a2.Length) return false;\n\n var longSize = (int)Math.Floor(a1.Length / 8.0);\n var long1 = Unsafe.As<long[]>(a1);\n var long2 = Unsafe.As<long[]>(a2);\n\n for (var i = 0; i < longSize; i++)\n {\n if (long1[i] != long2[i]) return false;\n }\n\n for (var i = longSize * 8; i < a1.Length; i++)\n {\n if (a1[i] != a2[i]) return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>Note that <code>long1.Length</code> would still return the original array's length, since it's stored in a field in the array's memory structure.</p>\n\n<p>This method is not quite as fast as other methods demonstrated here, but it is a lot faster than the naive method, doesn't use unsafe code or P/Invoke or pinning, and the implementation is quite straightforward (IMO). Here are some <a href=\"http://benchmarkdotnet.org/\" rel=\"noreferrer\">BenchmarkDotNet</a> results from my machine:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>BenchmarkDotNet=v0.10.3.0, OS=Microsoft Windows NT 6.2.9200.0\nProcessor=Intel(R) Core(TM) i7-4870HQ CPU 2.50GHz, ProcessorCount=8\nFrequency=2435775 Hz, Resolution=410.5470 ns, Timer=TSC\n [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0\n DefaultJob : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0\n\n Method | Mean | StdDev |\n----------------------- |-------------- |---------- |\n UnsafeLibrary | 125.8229 ns | 0.3588 ns |\n UnsafeCompare | 89.9036 ns | 0.8243 ns |\n JSharpEquals | 1,432.1717 ns | 1.3161 ns |\n EqualBytesLongUnrolled | 43.7863 ns | 0.8923 ns |\n NewMemCmp | 65.4108 ns | 0.2202 ns |\n ArraysEqual | 910.8372 ns | 2.6082 ns |\n PInvokeMemcmp | 52.7201 ns | 0.1105 ns |\n</code></pre>\n\n<p>I've also created a <a href=\"https://gist.github.com/aelij/b62d149e1a85c3edfad7598e9c2f12cb\" rel=\"noreferrer\">gist with all the tests</a>.</p>\n"
},
{
"answer_id": 46005655,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>This is almost certainly much slower than any other version given here, but it was fun to write.</p>\n\n<pre><code>static bool ByteArrayEquals(byte[] a1, byte[] a2) \n{\n return a1.Zip(a2, (l, r) => l == r).All(x => x);\n}\n</code></pre>\n"
},
{
"answer_id": 46471559,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 3,
"selected": false,
"text": "<p>I did some measurements using attached program .net 4.7 release build without the debugger attached. I think people have been using the wrong metric since what you are about if you care about speed here is how long it takes to figure out if two byte arrays are equal. i.e. throughput in bytes.</p>\n\n<pre><code>StructuralComparison : 4.6 MiB/s\nfor : 274.5 MiB/s\nToUInt32 : 263.6 MiB/s\nToUInt64 : 474.9 MiB/s\nmemcmp : 8500.8 MiB/s\n</code></pre>\n\n<p>As you can see, there's no better way than <code>memcmp</code> and it's orders of magnitude faster. A simple <code>for</code> loop is the second best option. And it still boggles my mind why Microsoft cannot simply include a <code>Buffer.Compare</code> method.</p>\n\n<p>[Program.cs]:</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace memcmp\n{\n class Program\n {\n static byte[] TestVector(int size)\n {\n var data = new byte[size];\n using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())\n {\n rng.GetBytes(data);\n }\n return data;\n }\n\n static TimeSpan Measure(string testCase, TimeSpan offset, Action action, bool ignore = false)\n {\n var t = Stopwatch.StartNew();\n var n = 0L;\n while (t.Elapsed < TimeSpan.FromSeconds(10))\n {\n action();\n n++;\n }\n var elapsed = t.Elapsed - offset;\n if (!ignore)\n {\n Console.WriteLine($\"{testCase,-16} : {n / elapsed.TotalSeconds,16:0.0} MiB/s\");\n }\n return elapsed;\n }\n\n [DllImport(\"msvcrt.dll\", CallingConvention = CallingConvention.Cdecl)]\n static extern int memcmp(byte[] b1, byte[] b2, long count);\n\n static void Main(string[] args)\n {\n // how quickly can we establish if two sequences of bytes are equal?\n\n // note that we are testing the speed of different comparsion methods\n\n var a = TestVector(1024 * 1024); // 1 MiB\n var b = (byte[])a.Clone();\n\n // was meant to offset the overhead of everything but copying but my attempt was a horrible mistake... should have reacted sooner due to the initially ridiculous throughput values...\n // Measure(\"offset\", new TimeSpan(), () => { return; }, ignore: true);\n var offset = TimeZone.Zero\n\n Measure(\"StructuralComparison\", offset, () =>\n {\n StructuralComparisons.StructuralEqualityComparer.Equals(a, b);\n });\n\n Measure(\"for\", offset, () =>\n {\n for (int i = 0; i < a.Length; i++)\n {\n if (a[i] != b[i]) break;\n }\n });\n\n Measure(\"ToUInt32\", offset, () =>\n {\n for (int i = 0; i < a.Length; i += 4)\n {\n if (BitConverter.ToUInt32(a, i) != BitConverter.ToUInt32(b, i)) break;\n }\n });\n\n Measure(\"ToUInt64\", offset, () =>\n {\n for (int i = 0; i < a.Length; i += 8)\n {\n if (BitConverter.ToUInt64(a, i) != BitConverter.ToUInt64(b, i)) break;\n }\n });\n\n Measure(\"memcmp\", offset, () =>\n {\n memcmp(a, b, a.Length);\n });\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 48577229,
"author": "Zapnologica",
"author_id": 1331971,
"author_profile": "https://Stackoverflow.com/users/1331971",
"pm_score": 2,
"selected": false,
"text": "<p>I have not seen many linq solutions here.</p>\n\n<p>I am not sure of the performance implications, however I generally stick to <code>linq</code> as rule of thumb and then optimize later if necessary.</p>\n\n<pre><code>public bool CompareTwoArrays(byte[] array1, byte[] array2)\n {\n return !array1.Where((t, i) => t != array2[i]).Any();\n }\n</code></pre>\n\n<p>Please do note this only works if they are the same size arrays.\nan extension could look like so</p>\n\n<pre><code>public bool CompareTwoArrays(byte[] array1, byte[] array2)\n {\n if (array1.Length != array2.Length) return false;\n return !array1.Where((t, i) => t != array2[i]).Any();\n }\n</code></pre>\n"
},
{
"answer_id": 48599119,
"author": "Joe Amenta",
"author_id": 1083771,
"author_profile": "https://Stackoverflow.com/users/1083771",
"pm_score": 7,
"selected": false,
"text": "<p><code>Span<T></code> offers an extremely competitive alternative without having to throw confusing and/or non-portable fluff into your own application's code base:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// byte[] is implicitly convertible to ReadOnlySpan<byte>\nstatic bool ByteArrayCompare(ReadOnlySpan<byte> a1, ReadOnlySpan<byte> a2)\n{\n return a1.SequenceEqual(a2);\n}\n</code></pre>\n<p>The (guts of the) implementation as of .NET 6.0.4 can be found <a href=\"https://github.com/dotnet/runtime/blob/v6.0.4/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Byte.cs#L1420-L1634\" rel=\"noreferrer\">here</a>.</p>\n<p>I've <a href=\"https://gist.github.com/airbreather/90c5fd3ba9d77fcd7c106db3beeb569b/revisions\" rel=\"noreferrer\">revised</a> @EliArbel's gist to add this method as <code>SpansEqual</code>, drop most of the less interesting performers in others' benchmarks, run it with different array sizes, output graphs, and mark <code>SpansEqual</code> as the baseline so that it reports how the different methods compare to <code>SpansEqual</code>.</p>\n<p>The below numbers are from the results, lightly edited to remove "Error" column.</p>\n<pre><code>| Method | ByteCount | Mean | StdDev | Ratio | RatioSD |\n|-------------- |----------- |-------------------:|----------------:|------:|--------:|\n| SpansEqual | 15 | 2.074 ns | 0.0233 ns | 1.00 | 0.00 |\n| LongPointers | 15 | 2.854 ns | 0.0632 ns | 1.38 | 0.03 |\n| Unrolled | 15 | 12.449 ns | 0.2487 ns | 6.00 | 0.13 |\n| PInvokeMemcmp | 15 | 7.525 ns | 0.1057 ns | 3.63 | 0.06 |\n| | | | | | |\n| SpansEqual | 1026 | 15.629 ns | 0.1712 ns | 1.00 | 0.00 |\n| LongPointers | 1026 | 46.487 ns | 0.2938 ns | 2.98 | 0.04 |\n| Unrolled | 1026 | 23.786 ns | 0.1044 ns | 1.52 | 0.02 |\n| PInvokeMemcmp | 1026 | 28.299 ns | 0.2781 ns | 1.81 | 0.03 |\n| | | | | | |\n| SpansEqual | 1048585 | 17,920.329 ns | 153.0750 ns | 1.00 | 0.00 |\n| LongPointers | 1048585 | 42,077.448 ns | 309.9067 ns | 2.35 | 0.02 |\n| Unrolled | 1048585 | 29,084.901 ns | 428.8496 ns | 1.62 | 0.03 |\n| PInvokeMemcmp | 1048585 | 30,847.572 ns | 213.3162 ns | 1.72 | 0.02 |\n| | | | | | |\n| SpansEqual | 2147483591 | 124,752,376.667 ns | 552,281.0202 ns | 1.00 | 0.00 |\n| LongPointers | 2147483591 | 139,477,269.231 ns | 331,458.5429 ns | 1.12 | 0.00 |\n| Unrolled | 2147483591 | 137,617,423.077 ns | 238,349.5093 ns | 1.10 | 0.00 |\n| PInvokeMemcmp | 2147483591 | 138,373,253.846 ns | 288,447.8278 ns | 1.11 | 0.01 |\n</code></pre>\n<p><s>I was surprised to see <code>SpansEqual</code> not come out on top for the max-array-size methods, but the difference is so minor that I don't think it'll ever matter.</s> After refreshing to run on .NET 6.0.4 with my newer hardware, <code>SpansEqual</code> now comfortably outperforms all others at all array sizes.</p>\n<p>My system info:</p>\n<pre><code>BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000\nAMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores\n.NET SDK=6.0.202\n [Host] : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT\n DefaultJob : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT\n</code></pre>\n"
},
{
"answer_id": 48666556,
"author": "Raymond Osterbrink",
"author_id": 2576585,
"author_profile": "https://Stackoverflow.com/users/2576585",
"pm_score": -1,
"selected": false,
"text": "<p>Since many of the fancy solutions above don't work with UWP and because I love Linq and functional approaches I pressent you my version to this problem.\nTo escape the comparison when the first difference occures, I chose .FirstOrDefault()</p>\n\n<pre><code>public static bool CompareByteArrays(byte[] ba0, byte[] ba1) =>\n !(ba0.Length != ba1.Length || Enumerable.Range(1,ba0.Length)\n .FirstOrDefault(n => ba0[n] != ba1[n]) > 0);\n</code></pre>\n"
},
{
"answer_id": 48975665,
"author": "Casey Chester",
"author_id": 2726757,
"author_profile": "https://Stackoverflow.com/users/2726757",
"pm_score": 1,
"selected": false,
"text": "<p>I settled on a solution inspired by the EqualBytesLongUnrolled method posted by ArekBulski with an additional optimization. In my instance, array differences in arrays tend to be near the tail of the arrays. In testing, I found that when this is the case for large arrays, being able to compare array elements in reverse order gives this solution a huge performance gain over the memcmp based solution. Here is that solution:</p>\n\n<pre><code>public enum CompareDirection { Forward, Backward }\n\nprivate static unsafe bool UnsafeEquals(byte[] a, byte[] b, CompareDirection direction = CompareDirection.Forward)\n{\n // returns when a and b are same array or both null\n if (a == b) return true;\n\n // if either is null or different lengths, can't be equal\n if (a == null || b == null || a.Length != b.Length)\n return false;\n\n const int UNROLLED = 16; // count of longs 'unrolled' in optimization\n int size = sizeof(long) * UNROLLED; // 128 bytes (min size for 'unrolled' optimization)\n int len = a.Length;\n int n = len / size; // count of full 128 byte segments\n int r = len % size; // count of remaining 'unoptimized' bytes\n\n // pin the arrays and access them via pointers\n fixed (byte* pb_a = a, pb_b = b)\n {\n if (r > 0 && direction == CompareDirection.Backward)\n {\n byte* pa = pb_a + len - 1;\n byte* pb = pb_b + len - 1;\n byte* phead = pb_a + len - r;\n while(pa >= phead)\n {\n if (*pa != *pb) return false;\n pa--;\n pb--;\n }\n }\n\n if (n > 0)\n {\n int nOffset = n * size;\n if (direction == CompareDirection.Forward)\n {\n long* pa = (long*)pb_a;\n long* pb = (long*)pb_b;\n long* ptail = (long*)(pb_a + nOffset);\n while (pa < ptail)\n {\n if (*(pa + 0) != *(pb + 0) || *(pa + 1) != *(pb + 1) ||\n *(pa + 2) != *(pb + 2) || *(pa + 3) != *(pb + 3) ||\n *(pa + 4) != *(pb + 4) || *(pa + 5) != *(pb + 5) ||\n *(pa + 6) != *(pb + 6) || *(pa + 7) != *(pb + 7) ||\n *(pa + 8) != *(pb + 8) || *(pa + 9) != *(pb + 9) ||\n *(pa + 10) != *(pb + 10) || *(pa + 11) != *(pb + 11) ||\n *(pa + 12) != *(pb + 12) || *(pa + 13) != *(pb + 13) ||\n *(pa + 14) != *(pb + 14) || *(pa + 15) != *(pb + 15)\n )\n {\n return false;\n }\n pa += UNROLLED;\n pb += UNROLLED;\n }\n }\n else\n {\n long* pa = (long*)(pb_a + nOffset);\n long* pb = (long*)(pb_b + nOffset);\n long* phead = (long*)pb_a;\n while (phead < pa)\n {\n if (*(pa - 1) != *(pb - 1) || *(pa - 2) != *(pb - 2) ||\n *(pa - 3) != *(pb - 3) || *(pa - 4) != *(pb - 4) ||\n *(pa - 5) != *(pb - 5) || *(pa - 6) != *(pb - 6) ||\n *(pa - 7) != *(pb - 7) || *(pa - 8) != *(pb - 8) ||\n *(pa - 9) != *(pb - 9) || *(pa - 10) != *(pb - 10) ||\n *(pa - 11) != *(pb - 11) || *(pa - 12) != *(pb - 12) ||\n *(pa - 13) != *(pb - 13) || *(pa - 14) != *(pb - 14) ||\n *(pa - 15) != *(pb - 15) || *(pa - 16) != *(pb - 16)\n )\n {\n return false;\n }\n pa -= UNROLLED;\n pb -= UNROLLED;\n }\n }\n }\n\n if (r > 0 && direction == CompareDirection.Forward)\n {\n byte* pa = pb_a + len - r;\n byte* pb = pb_b + len - r;\n byte* ptail = pb_a + len;\n while(pa < ptail)\n {\n if (*pa != *pb) return false;\n pa++;\n pb++;\n }\n }\n }\n\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 56553320,
"author": "Mahmoud Al-Qudsi",
"author_id": 17027,
"author_profile": "https://Stackoverflow.com/users/17027",
"pm_score": 3,
"selected": false,
"text": "<p>For those of you that care about order (i.e. want your <code>memcmp</code> to return an <code>int</code> like it should instead of nothing), .NET Core 3.0 (and presumably .NET Standard 2.1 aka .NET 5.0) <a href=\"https://github.com/dotnet/corefx/pull/26232/files\" rel=\"nofollow noreferrer\">will include a <code>Span.SequenceCompareTo(...)</code> extension method</a> (plus a <code>Span.SequenceEqualTo</code>) that can be used to compare two <code>ReadOnlySpan<T></code> instances (<code>where T: IComparable<T></code>).</p>\n<p>In <a href=\"https://github.com/dotnet/corefx/issues/16878\" rel=\"nofollow noreferrer\">the original GitHub proposal</a>, the discussion included approach comparisons with jump table calculations, reading a <code>byte[]</code> as <code>long[]</code>, SIMD usage, and p/invoke to the CLR implementation's <code>memcmp</code>.</p>\n<p>Going forward, this should be your go-to method for comparing byte arrays or byte ranges (as should using <code>Span<byte></code> instead of <code>byte[]</code> for your .NET Standard 2.1 APIs), and it is sufficiently fast enough that you should no longer care about optimizing it (and no, despite the similarities in name it does not perform as abysmally as the horrid <code>Enumerable.SequenceEqual</code>).</p>\n<pre><code>#if NETCOREAPP3_0_OR_GREATER\n// Using the platform-native Span<T>.SequenceEqual<T>(..)\npublic static int Compare(byte[] range1, int offset1, byte[] range2, int offset2, int count)\n{\n var span1 = range1.AsSpan(offset1, count);\n var span2 = range2.AsSpan(offset2, count);\n\n return span1.SequenceCompareTo(span2);\n // or, if you don't care about ordering\n // return span1.SequenceEqual(span2);\n}\n#else\n// The most basic implementation, in platform-agnostic, safe C#\npublic static bool Compare(byte[] range1, int offset1, byte[] range2, int offset2, int count)\n{\n // Working backwards lets the compiler optimize away bound checking after the first loop\n for (int i = count - 1; i >= 0; --i)\n {\n if (range1[offset1 + i] != range2[offset2 + i])\n {\n return false;\n }\n }\n\n return true;\n}\n#endif\n</code></pre>\n"
},
{
"answer_id": 69280107,
"author": "Antidisestablishmentarianism",
"author_id": 13843929,
"author_profile": "https://Stackoverflow.com/users/13843929",
"pm_score": 0,
"selected": false,
"text": "<p>This is similar to others, but the difference here is that there is no falling through to the next highest number of bytes I can check at once, e.g. if I have 63 bytes (in my SIMD example) I can check the equality of the first 32 bytes, and then the last 32 bytes, which is faster than checking 32 bytes, 16 bytes, 8 bytes, and so on. The first check you enter is the only check you will need to compare all of the bytes.</p>\n<p>This does come out on top in my tests, but just by a hair.</p>\n<p>The following code is exactly how I tested it in airbreather/ArrayComparePerf.cs.</p>\n<pre><code>public unsafe bool SIMDNoFallThrough() #requires System.Runtime.Intrinsics.X86\n{\n if (a1 == null || a2 == null)\n return false;\n\n int length0 = a1.Length;\n\n if (length0 != a2.Length) return false;\n\n fixed (byte* b00 = a1, b01 = a2)\n {\n byte* b0 = b00, b1 = b01, last0 = b0 + length0, last1 = b1 + length0, last32 = last0 - 31;\n\n if (length0 > 31)\n {\n while (b0 < last32)\n {\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0), Avx.LoadVector256(b1))) != -1)\n return false;\n b0 += 32;\n b1 += 32;\n }\n return Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(last0 - 32), Avx.LoadVector256(last1 - 32))) == -1;\n }\n\n if (length0 > 15)\n {\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0), Sse2.LoadVector128(b1))) != 65535)\n return false;\n return Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(last0 - 16), Sse2.LoadVector128(last1 - 16))) == 65535;\n }\n\n if (length0 > 7)\n {\n if (*(ulong*)b0 != *(ulong*)b1)\n return false;\n return *(ulong*)(last0 - 8) == *(ulong*)(last1 - 8);\n }\n\n if (length0 > 3)\n {\n if (*(uint*)b0 != *(uint*)b1)\n return false;\n return *(uint*)(last0 - 4) == *(uint*)(last1 - 4);\n }\n\n if (length0 > 1)\n {\n if (*(ushort*)b0 != *(ushort*)b1)\n return false;\n return *(ushort*)(last0 - 2) == *(ushort*)(last1 - 2);\n }\n\n return *b0 == *b1;\n }\n}\n</code></pre>\n<p>If no SIMD is preferred, the same method applied to the the existing LongPointers algorithm:</p>\n<pre><code>public unsafe bool LongPointersNoFallThrough()\n{\n if (a1 == null || a2 == null || a1.Length != a2.Length)\n return false;\n fixed (byte* p1 = a1, p2 = a2)\n {\n byte* x1 = p1, x2 = p2;\n int l = a1.Length;\n if ((l & 8) != 0)\n {\n for (int i = 0; i < l / 8; i++, x1 += 8, x2 += 8)\n if (*(long*)x1 != *(long*)x2) return false;\n return *(long*)(x1 + (l - 8)) == *(long*)(x2 + (l - 8));\n }\n if ((l & 4) != 0)\n {\n if (*(int*)x1 != *(int*)x2) return false; x1 += 4; x2 += 4;\n return *(int*)(x1 + (l - 4)) == *(int*)(x2 + (l - 4));\n }\n if ((l & 2) != 0)\n {\n if (*(short*)x1 != *(short*)x2) return false; x1 += 2; x2 += 2;\n return *(short*)(x1 + (l - 2)) == *(short*)(x2 + (l - 2));\n }\n return *x1 == *x2;\n }\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489/"
] | How can I do this fast?
Sure I can do this:
```
static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if (a1.Length != a2.Length)
return false;
for (int i=0; i<a1.Length; i++)
if (a1[i]!=a2[i])
return false;
return true;
}
```
But I'm looking for either a [BCL](https://en.wikipedia.org/wiki/Standard_Libraries_%28CLI%29#Base_Class_Library) function or some highly optimized proven way to do this.
```
java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2);
```
works nicely, but it doesn't look like that would work for x64.
Note my super-fast answer [here](https://stackoverflow.com/a/8808245/4489). | Edit: modern fast way is to use `a1.SequenceEquals(a2)`
User *gil* suggested unsafe code which spawned this solution:
```
// Copyright (c) 2008-2013 Hafthor Stefansson
// Distributed under the MIT/X11 software license
// Ref: http://www.opensource.org/licenses/mit-license.php.
static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {
unchecked {
if(a1==a2) return true;
if(a1==null || a2==null || a1.Length!=a2.Length)
return false;
fixed (byte* p1=a1, p2=a2) {
byte* x1=p1, x2=p2;
int l = a1.Length;
for (int i=0; i < l/8; i++, x1+=8, x2+=8)
if (*((long*)x1) != *((long*)x2)) return false;
if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }
if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }
if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;
return true;
}
}
}
```
which does 64-bit based comparison for as much of the array as possible. This kind of counts on the fact that the arrays start qword aligned. It'll work if not qword aligned, just not as fast as if it were.
It performs about seven timers faster than the simple `for` loop. Using the J# library performed equivalently to the original `for` loop. Using .SequenceEqual runs around seven times slower; I think just because it is using IEnumerator.MoveNext. I imagine LINQ-based solutions being at least that slow or worse. |
43,290 | <p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p>
<p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
| [
{
"answer_id": 43312,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 7,
"selected": true,
"text": "<p>If you need to use something similar to the <code>{% url %}</code> template tag in your code, Django provides the <code>django.core.urlresolvers.reverse()</code>. The <code>reverse</code> function has the following signature:</p>\n\n<pre><code>reverse(viewname, urlconf=None, args=None, kwargs=None)\n</code></pre>\n\n<p><a href=\"https://docs.djangoproject.com/en/dev/ref/urlresolvers/\" rel=\"noreferrer\">https://docs.djangoproject.com/en/dev/ref/urlresolvers/</a></p>\n\n<p>At the time of this edit the import is <code>django.urls import reverse</code></p>\n"
},
{
"answer_id": 55734,
"author": "Garth Kidd",
"author_id": 5700,
"author_profile": "https://Stackoverflow.com/users/5700",
"pm_score": 4,
"selected": false,
"text": "<p>I'm using two different approaches in my <code>models.py</code>. The first is the <code>permalink</code> decorator:</p>\n\n<pre><code>from django.db.models import permalink\n\ndef get_absolute_url(self): \n \"\"\"Construct the absolute URL for this Item.\"\"\"\n return ('project.app.views.view_name', [str(self.id)])\nget_absolute_url = permalink(get_absolute_url)\n</code></pre>\n\n<p>You can also call <code>reverse</code> directly:</p>\n\n<pre><code>from django.core.urlresolvers import reverse\n\ndef get_absolute_url(self): \n \"\"\"Construct the absolute URL for this Item.\"\"\"\n return reverse('project.app.views.view_name', None, [str(self.id)])\n</code></pre>\n"
},
{
"answer_id": 72249,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 2,
"selected": false,
"text": "<p>Be aware that using <code>reverse()</code> requires that your urlconf module is 100% error free and can be processed - iow no <code>ViewDoesNotExist</code> errors or so, or you get the dreaded <code>NoReverseMatch</code> exception (errors in templates usually fail silently resulting in <code>None</code>).</p>\n"
},
{
"answer_id": 57151646,
"author": "juan Isaza",
"author_id": 2394901,
"author_profile": "https://Stackoverflow.com/users/2394901",
"pm_score": 3,
"selected": false,
"text": "<p>For Python3 and Django 2:</p>\n<pre><code>from django.urls import reverse\n\nurl = reverse('my_app:endpoint', kwargs={'arg1': arg_1})\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
] | In Django's template language, you can use `{% url [viewname] [args] %}` to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?
What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language. | If you need to use something similar to the `{% url %}` template tag in your code, Django provides the `django.core.urlresolvers.reverse()`. The `reverse` function has the following signature:
```
reverse(viewname, urlconf=None, args=None, kwargs=None)
```
<https://docs.djangoproject.com/en/dev/ref/urlresolvers/>
At the time of this edit the import is `django.urls import reverse` |
43,291 | <p>I know that I can do something like</p>
<pre><code>$int = (int)99; //(int) has a maximum or 99
</code></pre>
<p>To set the variable <code>$int</code> to an integer and give it a value of <code>99</code>. </p>
<p>Is there a way to set the type to something like <code>LongBlob</code> in MySQL for <code>LARGE</code> Integers in PHP?</p>
| [
{
"answer_id": 43295,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 4,
"selected": true,
"text": "<p>No. PHP does what is called automatic type conversion.</p>\n\n<p>In your example</p>\n\n<pre><code>$int = (int)123;\n</code></pre>\n\n<p>the \"(int)\" just assures that at that exact moment 123 will be handled as an int.</p>\n\n<p>I think your best bet would be to use a class to provide some sort of type safety.</p>\n"
},
{
"answer_id": 43308,
"author": "ejack",
"author_id": 1377,
"author_profile": "https://Stackoverflow.com/users/1377",
"pm_score": 0,
"selected": false,
"text": "<p>No, the type LongBlob is specific to MySQL. In PHP it is seen as binary data (usually characters), if you tried to convert it to an int it would take the first 32 bits of data (platform dependent) and push that into the variable.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | I know that I can do something like
```
$int = (int)99; //(int) has a maximum or 99
```
To set the variable `$int` to an integer and give it a value of `99`.
Is there a way to set the type to something like `LongBlob` in MySQL for `LARGE` Integers in PHP? | No. PHP does what is called automatic type conversion.
In your example
```
$int = (int)123;
```
the "(int)" just assures that at that exact moment 123 will be handled as an int.
I think your best bet would be to use a class to provide some sort of type safety. |
43,320 | <p>One of the things that get me thoroughly confused is the use of <code>session.Flush</code>,in conjunction with <code>session.Commit</code>, and <code>session.Close</code>.</p>
<p>Sometimes <code>session.Close</code> works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs.</p>
<p>But sometimes I really get stymied by the logic behind <code>session.Flush</code>. I have seen examples where you have a <code>session.SaveOrUpdate()</code> followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error.</p>
<p>Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer.</p>
| [
{
"answer_id": 43567,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 9,
"selected": true,
"text": "<p>Briefly:</p>\n<ol>\n<li>Always use transactions</li>\n<li>Don't use <code>Close()</code>, instead wrap your calls on an <code>ISession</code> inside a <code>using</code> statement or <strong>manage the lifecycle of your ISession somewhere else</strong>.</li>\n</ol>\n<p>From <a href=\"http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-flushing\" rel=\"noreferrer\">the documentation</a>:</p>\n<blockquote>\n<p>From time to time the <code>ISession</code> will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points</p>\n<ul>\n<li>from some invocations of <code>Find()</code> or <code>Enumerable()</code></li>\n<li>from <code>NHibernate.ITransaction.Commit()</code></li>\n<li>from <code>ISession.Flush()</code></li>\n</ul>\n<p>The SQL statements are issued in the following order</p>\n<ol>\n<li>all entity insertions, in the same order the corresponding objects were saved using <code>ISession.Save()</code></li>\n<li>all entity updates</li>\n<li>all collection deletions</li>\n<li>all collection element deletions, updates and insertions</li>\n<li>all collection insertions</li>\n<li>all entity deletions, in the same order the corresponding objects were deleted using <code>ISession.Delete()</code></li>\n</ol>\n<p>(An exception is that objects using native ID generation are inserted when they are saved.)</p>\n<p><strong>Except when you explicity <code>Flush()</code>, there are absolutely no guarantees about when the Session executes the ADO.NET calls, only the order in which they are executed</strong>. However, NHibernate does guarantee that the <code>ISession.Find(..)</code> methods will never return stale data; nor will they return the wrong data.</p>\n<p>It is possible to change the default behavior so that flush occurs less frequently. The <code>FlushMode</code> class defines three different modes: only flush at commit time (and only when the NHibernate <code>ITransaction</code> API is used), flush automatically using the explained routine, or never flush unless <code>Flush()</code> is called explicitly. The last mode is useful for long running units of work, where an <code>ISession</code> is kept open and disconnected for a long time.</p>\n</blockquote>\n<p>...</p>\n<p>Also refer to <a href=\"http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-endingsession\" rel=\"noreferrer\">this section</a>:</p>\n<blockquote>\n<p>Ending a session involves four distinct phases:</p>\n<ul>\n<li>flush the session</li>\n<li>commit the transaction</li>\n<li>close the session</li>\n<li>handle exceptions</li>\n</ul>\n<h2>Flushing the Session</h2>\n<p>If you happen to be using the <code>ITransaction</code> API, you don't need to worry about this step. It will be performed implicitly when the transaction is committed. Otherwise you should call <code>ISession.Flush()</code> to ensure that all changes are synchronized with the database.</p>\n<h2>Committing the database transaction</h2>\n<p>If you are using the NHibernate ITransaction API, this looks like:</p>\n<pre><code>tx.Commit(); // flush the session and commit the transaction\n</code></pre>\n<p>If you are managing ADO.NET transactions yourself you should manually <code>Commit()</code> the ADO.NET transaction.</p>\n<pre><code>sess.Flush();\ncurrentTransaction.Commit();\n</code></pre>\n<p>If you decide not to commit your changes:</p>\n<pre><code>tx.Rollback(); // rollback the transaction\n</code></pre>\n<p>or:</p>\n<pre><code>currentTransaction.Rollback();\n</code></pre>\n<p>If you rollback the transaction you should immediately close and discard the current session to ensure that NHibernate's internal state is consistent.</p>\n<h2>Closing the ISession</h2>\n<p>A call to <code>ISession.Close()</code> marks the end of a session. The main implication of Close() is that the ADO.NET connection will be relinquished by the session.</p>\n<pre><code>tx.Commit();\nsess.Close();\n\nsess.Flush();\ncurrentTransaction.Commit();\nsess.Close();\n</code></pre>\n<p>If you provided your own connection, <code>Close()</code> returns a reference to it, so you can manually close it or return it to the pool. Otherwise <code>Close()</code> returns it to the pool.</p>\n</blockquote>\n"
},
{
"answer_id": 44212,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 4,
"selected": false,
"text": "<p>Starting in NHibernate 2.0, transactions are required for DB operations. Therefore, the <code>ITransaction.Commit()</code> call will handle any necessary flushing. If for some reason you aren't using NHibernate transactions, then there will be no auto-flushing of the session.</p>\n"
},
{
"answer_id": 13252242,
"author": "Paul T Davies",
"author_id": 803418,
"author_profile": "https://Stackoverflow.com/users/803418",
"pm_score": 0,
"selected": false,
"text": "<p>Here are two examples of my code where it would fail without session.Flush():</p>\n\n<p><a href=\"http://www.lucidcoding.blogspot.co.uk/2012/05/changing-type-of-entity-persistence.html\" rel=\"nofollow noreferrer\">http://www.lucidcoding.blogspot.co.uk/2012/05/changing-type-of-entity-persistence.html</a></p>\n\n<p>at the end of this, you can see a section of code where I set identity insert on, save the entity then flush, then set identity insert off. Without this flush it seemed to be setting identity insert on and off then saving the entity. </p>\n\n<p>The use of Flush() gave me more control over what was going on.</p>\n\n<p>Here is another example:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/12494943/sending-nservicebus-message-inside-transactionscope\">Sending NServiceBus message inside TransactionScope</a></p>\n\n<p>I don't fully understand why on this one, but Flush() prevented my error from happening.</p>\n"
},
{
"answer_id": 22193504,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>From time to time the ISession will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory.</p>\n\n<p>And always use </p>\n\n<pre><code> using (var transaction = session.BeginTransaction())\n {\n transaction.Commit();\n }\n</code></pre>\n\n<p>after the changes are committed than this changes to save into database we use transaction.Commit();</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372/"
] | One of the things that get me thoroughly confused is the use of `session.Flush`,in conjunction with `session.Commit`, and `session.Close`.
Sometimes `session.Close` works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs.
But sometimes I really get stymied by the logic behind `session.Flush`. I have seen examples where you have a `session.SaveOrUpdate()` followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error.
Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer. | Briefly:
1. Always use transactions
2. Don't use `Close()`, instead wrap your calls on an `ISession` inside a `using` statement or **manage the lifecycle of your ISession somewhere else**.
From [the documentation](http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-flushing):
>
> From time to time the `ISession` will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points
>
>
> * from some invocations of `Find()` or `Enumerable()`
> * from `NHibernate.ITransaction.Commit()`
> * from `ISession.Flush()`
>
>
> The SQL statements are issued in the following order
>
>
> 1. all entity insertions, in the same order the corresponding objects were saved using `ISession.Save()`
> 2. all entity updates
> 3. all collection deletions
> 4. all collection element deletions, updates and insertions
> 5. all collection insertions
> 6. all entity deletions, in the same order the corresponding objects were deleted using `ISession.Delete()`
>
>
> (An exception is that objects using native ID generation are inserted when they are saved.)
>
>
> **Except when you explicity `Flush()`, there are absolutely no guarantees about when the Session executes the ADO.NET calls, only the order in which they are executed**. However, NHibernate does guarantee that the `ISession.Find(..)` methods will never return stale data; nor will they return the wrong data.
>
>
> It is possible to change the default behavior so that flush occurs less frequently. The `FlushMode` class defines three different modes: only flush at commit time (and only when the NHibernate `ITransaction` API is used), flush automatically using the explained routine, or never flush unless `Flush()` is called explicitly. The last mode is useful for long running units of work, where an `ISession` is kept open and disconnected for a long time.
>
>
>
...
Also refer to [this section](http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-endingsession):
>
> Ending a session involves four distinct phases:
>
>
> * flush the session
> * commit the transaction
> * close the session
> * handle exceptions
>
>
> Flushing the Session
> --------------------
>
>
> If you happen to be using the `ITransaction` API, you don't need to worry about this step. It will be performed implicitly when the transaction is committed. Otherwise you should call `ISession.Flush()` to ensure that all changes are synchronized with the database.
>
>
> Committing the database transaction
> -----------------------------------
>
>
> If you are using the NHibernate ITransaction API, this looks like:
>
>
>
> ```
> tx.Commit(); // flush the session and commit the transaction
>
> ```
>
> If you are managing ADO.NET transactions yourself you should manually `Commit()` the ADO.NET transaction.
>
>
>
> ```
> sess.Flush();
> currentTransaction.Commit();
>
> ```
>
> If you decide not to commit your changes:
>
>
>
> ```
> tx.Rollback(); // rollback the transaction
>
> ```
>
> or:
>
>
>
> ```
> currentTransaction.Rollback();
>
> ```
>
> If you rollback the transaction you should immediately close and discard the current session to ensure that NHibernate's internal state is consistent.
>
>
> Closing the ISession
> --------------------
>
>
> A call to `ISession.Close()` marks the end of a session. The main implication of Close() is that the ADO.NET connection will be relinquished by the session.
>
>
>
> ```
> tx.Commit();
> sess.Close();
>
> sess.Flush();
> currentTransaction.Commit();
> sess.Close();
>
> ```
>
> If you provided your own connection, `Close()` returns a reference to it, so you can manually close it or return it to the pool. Otherwise `Close()` returns it to the pool.
>
>
> |
43,321 | <p>The default shell in Mac OS X is <code>bash</code>, which I'm generally happy to be using. I just take it for granted. It would be really nice if it auto-completed <em>more stuff</em>, though, and I've heard good things about <code>zsh</code> in this regard. But I don't really have the inclination to spend hours fiddling with settings to improve my command line usage by a tiny amount, since my life on the command line isn't that bad. </p>
<p>(As I understand it, <code>bash</code> can also be configured to auto-complete more cleverly. It's the configuring I'm not all that keen on.)</p>
<p>Will switching to <code>zsh</code>, even in a small number cases, make my life easier? Or is it only a better shell if you put in the time to learn <em>why</em> it's better? (Examples would be nice, too <code>:)</code> )</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43340">Rodney Amato</a>
&
@<a href="https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43338">Vulcan Eager</a>
give two good reasons to respectively stick to <code>bash</code> and switch to <code>zsh</code>. Looks like I'll have to investigate both! Oh well <code>:)</code></p>
<p>Is there anyone with an opinion from both sides of the argument?</p>
| [
{
"answer_id": 43323,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 3,
"selected": false,
"text": "<p>zsh has a console gui configuration thing. You can set it up pretty quickly and easily without having to fiddle with configuration files. I don't think you will need much time to set it up, probably 10 seconds with just using defaults, so go ahead and try it out.</p>\n"
},
{
"answer_id": 43338,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 2,
"selected": false,
"text": "<p>Staale is talking about a wizard like program (CUI) which autoruns the first time you run zsh. Just answer some questions, view/change the defaults and its configured for you.</p>\n\n<p>IBM developerWorks has great resources on zsh.</p>\n\n<p>I have not used very advanced features and so far I have not come across serious differences which should hamper someone coming from bash.</p>\n\n<p>Some examples:</p>\n\n<ul>\n<li><p>!?pattern<Tab> will autocomplete to\nthe last command in history matching\npattern. Very useful.</p></li>\n<li><p>You can configure a prompt on the\nRHS. One use is to keep a fixed\nwidth prompt on the left hand side\nso all commands line up nicely while\ndisplaying the pwd (or anything of\nvariable width) as the right hand\nside prompt.</p></li>\n<li><p>You can redirect input from multiple files (yet to try this): cat < file1 < file2 < file3 </p></li>\n</ul>\n"
},
{
"answer_id": 43340,
"author": "Rodney Amato",
"author_id": 4342,
"author_profile": "https://Stackoverflow.com/users/4342",
"pm_score": 7,
"selected": true,
"text": "<p>For casual use you are probably better off sticking with bash and just installing bash completion. </p>\n\n<p>Installing it is pretty easy, grab the bash-completion-20060301.tar.gz from <a href=\"http://www.caliban.org/bash/index.shtml#completion\" rel=\"noreferrer\">http://www.caliban.org/bash/index.shtml#completion</a> and extract it with </p>\n\n<pre><code>tar -xzvf bash-completion-20060301.tar.gz\n</code></pre>\n\n<p>then copy the bash_completion/bash_completion file to /etc with </p>\n\n<pre><code>sudo cp bash_completion/bash_completion /etc\n</code></pre>\n\n<p>which will prompt you for your password. You probably will want to make a /etc/bash_completion.d directory for any additional completion scripts (for instance I have the git completion script in there).</p>\n\n<p>Once this is done the last step is to make sure the .bash_profile file in your home directory has </p>\n\n<pre><code>if [ -f /etc/bash_completion ]; then\n . /etc/bash_completion \nfi\n</code></pre>\n\n<p>in it to load the completion file when you login. </p>\n\n<p>To test it just open a new terminal, and try completing on cvs and it should show you the cvs options in the list of completions.</p>\n"
},
{
"answer_id": 83754,
"author": "Matt",
"author_id": 15368,
"author_profile": "https://Stackoverflow.com/users/15368",
"pm_score": 6,
"selected": false,
"text": "<p>Personally, I love zsh. </p>\n\n<p>Generally, you probably won't notice the difference between it and bash, until you want to quickly do things like recursive globbing:</p>\n\n<ul>\n<li><code>**/*.c</code> for example.</li>\n</ul>\n\n<p>Or use suffix aliases to associate specific progs with different suffixes, so that you can \"execute\" them directly. The below alias lets you \"run\" a C source file at the prompt by simply typing <code>./my_program.c</code> – which will work exactly as if you typed <code>vim ./my_program.c</code>. (Sort of the equivalent to double clicking on the icon of a file.)</p>\n\n<ul>\n<li><code>alias -s c=vim</code></li>\n</ul>\n\n<p>Or print the names of files modified today:</p>\n\n<ul>\n<li><code>print *(e:age today now:)</code></li>\n</ul>\n\n<p>You can probably do all of these things in bash, but my experience with zsh is that if there's something I want to do, I can probably find it in <a href=\"http://grml.org/zsh/zsh-lovers.html\" rel=\"noreferrer\" title=\"ZSH-LOVERS(1)\">zsh-lovers</a>.\nI also find the book '<a href=\"https://rads.stackoverflow.com/amzn/click/com/1590593766\" rel=\"noreferrer\" rel=\"nofollow noreferrer\" title=\"Amazon.com: From Bash to Z Shell: Conquering the Command Line: Oliver Kiddle, Jerry Peek, Peter Stephenson: Books\">From Bash to Z-Shell</a>' really useful.</p>\n\n<p>Playing with the mind bogglingly large number of options is good fun too!</p>\n"
},
{
"answer_id": 106317,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 4,
"selected": false,
"text": "<p>If all you want to use ZSH for is better completion, the configuration is pretty easy. Place this in your ~/.zshrc:</p>\n\n<pre><code>autoload -U zutil # [1]\nautoload -U compinit # [2]\nautoload -U complist # [3]\ncompinit\n</code></pre>\n\n<p>However, it's worth checking out all the other great features of the ZSH. The above example will give you a pretty plain prompt with good completion. If you don't want to fiddle with configurations, but want to see what ZSH can do for you, Google for \"zshrc\" and you will get some ready to use configurations to get started.</p>\n\n<ul>\n<li>[1]: <a href=\"http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fzutil-Module\" rel=\"noreferrer\">http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fzutil-Module</a></li>\n<li>[2]: <a href=\"http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Initialization\" rel=\"noreferrer\">http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Initialization</a></li>\n<li>[3]: <a href=\"http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fcomplist-Module\" rel=\"noreferrer\">http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fcomplist-Module</a></li>\n</ul>\n"
},
{
"answer_id": 909650,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Switch to zsh. You will have access to:</p>\n\n<ol>\n<li><code>zmv</code>: You can do: <code>zmv '(*).mp3' '$1.wma'</code> for thousands of files.</li>\n<li><code>zcalc</code>: Extremely comfortable calculator, better than <code>bc</code>.</li>\n<li><code>zparseopts</code>: One-liner for parsing arbitrary complex options given to your script.</li>\n<li><code>autopushd</code>: You can always do <code>popd</code> after <code>cd</code> to change back to your previous directory.</li>\n<li>Floating point support. It is needed from time to time.</li>\n<li>Hashes support. Sometimes they are just a key feature.</li>\n</ol>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] | The default shell in Mac OS X is `bash`, which I'm generally happy to be using. I just take it for granted. It would be really nice if it auto-completed *more stuff*, though, and I've heard good things about `zsh` in this regard. But I don't really have the inclination to spend hours fiddling with settings to improve my command line usage by a tiny amount, since my life on the command line isn't that bad.
(As I understand it, `bash` can also be configured to auto-complete more cleverly. It's the configuring I'm not all that keen on.)
Will switching to `zsh`, even in a small number cases, make my life easier? Or is it only a better shell if you put in the time to learn *why* it's better? (Examples would be nice, too `:)` )
---
@[Rodney Amato](https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43340)
&
@[Vulcan Eager](https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43338)
give two good reasons to respectively stick to `bash` and switch to `zsh`. Looks like I'll have to investigate both! Oh well `:)`
Is there anyone with an opinion from both sides of the argument? | For casual use you are probably better off sticking with bash and just installing bash completion.
Installing it is pretty easy, grab the bash-completion-20060301.tar.gz from <http://www.caliban.org/bash/index.shtml#completion> and extract it with
```
tar -xzvf bash-completion-20060301.tar.gz
```
then copy the bash\_completion/bash\_completion file to /etc with
```
sudo cp bash_completion/bash_completion /etc
```
which will prompt you for your password. You probably will want to make a /etc/bash\_completion.d directory for any additional completion scripts (for instance I have the git completion script in there).
Once this is done the last step is to make sure the .bash\_profile file in your home directory has
```
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
```
in it to load the completion file when you login.
To test it just open a new terminal, and try completing on cvs and it should show you the cvs options in the list of completions. |
43,324 | <p>I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great, but it has the following documented limitation:</p>
<blockquote>
<p>Because of a known Flash bug, the Uploader running in Firefox in Windows does not send the correct cookies with the upload; instead of sending Firefox cookies, it sends Internet Explorer’s cookies for the respective domain. As a workaround, we suggest either using a cookieless upload method or appending document.cookie to the upload request.</p>
</blockquote>
<p>So, if a user is using Firefox, I can't rely on cookies to persist their session when they upload a file. I need their session because I need to know who they are! As a workaround, I'm using the Application object thusly:</p>
<pre><code>Guid UploadID = Guid.NewGuid();
Application.Add(Guid.ToString(), User);
</code></pre>
<p>So, I'm creating a unique ID and using it as a key to store the <code>Page.User</code> object in the Application scope. I include that ID as a variable in the POST when the file is uploaded. Then, in the handler that accepts the file upload, I grab the User object thusly:</p>
<pre><code>IPrincipal User = (IPrincipal)Application[Request.Form["uploadid"]];
</code></pre>
<p>This actually works, but it has two glaring drawbacks: </p>
<ul>
<li><p>If IIS, the app pool, or even just the application is restarted between the time the user visits the upload page, and actually uploads a file, their "uploadid" is deleted from application scope and the upload fails because I can't authenticate them.</p></li>
<li><p>If I ever scale to a web farm (possibly even a web garden) scenario, this will completely break. I might not be worried, except I do plan on scaling this app in the future.</p></li>
</ul>
<p>Does anyone have a better way? Is there a way for me to pass the actual ASP.Net session ID in a POST variable, then use that ID at the other end to retrieve the session?</p>
<p>I know I can get the session ID through <code>Session.SessionID</code>, and I know how to use YUI to post it to the next page. What I don't know is how to use that <code>SessionID</code> to grab the session from the state server.</p>
<p>Yes, I'm using a state server to store the sessions, so they persist application/IIS restarts, and will work in a web farm scenario.</p>
| [
{
"answer_id": 43353,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>The ASP.Net Session ID is stored in <code>Session.SessionID</code> so you could set that in a hidden field and then post it to the next page.</p>\n\n<p>I think, however, that if the application restarts, the sessionID will expire if you do not <a href=\"http://support.microsoft.com/kb/317604\" rel=\"nofollow noreferrer\">store your sessions in sql server</a>.</p>\n"
},
{
"answer_id": 43356,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 1,
"selected": false,
"text": "<p>You can get your current SessionID from the following code:</p>\n\n<pre><code>string sessionId = HttpContext.Current.Session.SessionID;\n</code></pre>\n\n<p>Then you can feed that into a hidden field maybe and then access that value through YUI.</p>\n\n<p>It's just a get, so you hopefully won't have any scaling problems. Security-problems though, that I don't know.</p>\n"
},
{
"answer_id": 237682,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://swfupload.org/forum/generaldiscussion/98\" rel=\"noreferrer\">Here</a> is a post from the maintainer of <a href=\"http://swfupload.org\" rel=\"noreferrer\">SWFUpload</a> which explains how to load the session from an ID stored in Request.Form. I imagine the same thing would work for the Yahoo component.</p>\n\n<p>Note the security disclaimers at the bottom of the post.</p>\n\n<hr>\n\n<blockquote>\n <p>By including a Global.asax file and the following code you can override the missing Session ID cookie:</p>\n</blockquote>\n\n<pre><code>using System;\nusing System.Web;\n\npublic class Global_asax : System.Web.HttpApplication\n{\n private void Application_BeginRequest(object sender, EventArgs e)\n {\n /* \n Fix for the Flash Player Cookie bug in Non-IE browsers.\n Since Flash Player always sends the IE cookies even in FireFox\n we have to bypass the cookies by sending the values as part of the POST or GET\n and overwrite the cookies with the passed in values.\n\n The theory is that at this point (BeginRequest) the cookies have not been ready by\n the Session and Authentication logic and if we update the cookies here we'll get our\n Session and Authentication restored correctly\n */\n\n HttpRequest request = HttpContext.Current.Request;\n\n try\n {\n string sessionParamName = \"ASPSESSID\";\n string sessionCookieName = \"ASP.NET_SESSIONID\";\n\n string sessionValue = request.Form[sessionParamName] ?? request.QueryString[sessionParamName];\n if (sessionValue != null)\n {\n UpdateCookie(sessionCookieName, sessionValue);\n }\n }\n catch (Exception ex)\n {\n // TODO: Add logging here.\n }\n\n try\n {\n string authParamName = \"AUTHID\";\n string authCookieName = FormsAuthentication.FormsCookieName;\n\n string authValue = request.Form[authParamName] ?? request.QueryString[authParamName];\n if (authValue != null)\n {\n UpdateCookie(authCookieName, authValue);\n }\n }\n catch (Exception ex)\n {\n // TODO: Add logging here.\n }\n }\n\n private void UpdateCookie(string cookieName, string cookieValue)\n {\n HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName);\n if (cookie == null)\n {\n HttpCookie newCookie = new HttpCookie(cookieName, cookieValue);\n Response.Cookies.Add(newCookie);\n }\n else\n {\n cookie.Value = cookieValue;\n HttpContext.Current.Request.Cookies.Set(cookie);\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <p><strong>Security Warning:</strong> Don't just copy and paste this code in to your ASP.Net application without knowing what you are doing. It introduces security issues and possibilities of Cross-site Scripting.</p>\n</blockquote>\n"
},
{
"answer_id": 25755712,
"author": "Pluto",
"author_id": 1507941,
"author_profile": "https://Stackoverflow.com/users/1507941",
"pm_score": 2,
"selected": false,
"text": "<p>Relying on <a href=\"http://konste.wordpress.com/2013/01/22/asp-net-accessing-any-session-data-by-session-id/\" rel=\"nofollow\">this blog post</a>, here's a function that should get you the session for any user based on the session ID, though it's not pretty:</p>\n\n<pre><code>public SessionStateStoreData GetSessionById(string sessionId)\n{\n HttpApplication httpApplication = HttpContext.ApplicationInstance;\n\n // Black magic #1: getting to SessionStateModule\n HttpModuleCollection httpModuleCollection = httpApplication.Modules;\n SessionStateModule sessionHttpModule = httpModuleCollection[\"Session\"] as SessionStateModule;\n if (sessionHttpModule == null)\n {\n // Couldn't find Session module\n return null;\n }\n\n // Black magic #2: getting to SessionStateStoreProviderBase through reflection\n FieldInfo fieldInfo = typeof(SessionStateModule).GetField(\"_store\", BindingFlags.NonPublic | BindingFlags.Instance);\n SessionStateStoreProviderBase sessionStateStoreProviderBase = fieldInfo.GetValue(sessionHttpModule) as SessionStateStoreProviderBase;\n if (sessionStateStoreProviderBase == null)\n {\n // Couldn't find sessionStateStoreProviderBase\n return null;\n }\n\n // Black magic #3: generating dummy HttpContext out of the thin air. sessionStateStoreProviderBase.GetItem in #4 needs it.\n SimpleWorkerRequest request = new SimpleWorkerRequest(\"dummy.html\", null, new StringWriter());\n HttpContext context = new HttpContext(request);\n\n // Black magic #4: using sessionStateStoreProviderBase.GetItem to fetch the data from session with given Id.\n bool locked;\n TimeSpan lockAge;\n object lockId;\n SessionStateActions actions;\n SessionStateStoreData sessionStateStoreData = sessionStateStoreProviderBase.GetItem(\n context, sessionId, out locked, out lockAge, out lockId, out actions);\n return sessionStateStoreData;\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] | I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great, but it has the following documented limitation:
>
> Because of a known Flash bug, the Uploader running in Firefox in Windows does not send the correct cookies with the upload; instead of sending Firefox cookies, it sends Internet Explorer’s cookies for the respective domain. As a workaround, we suggest either using a cookieless upload method or appending document.cookie to the upload request.
>
>
>
So, if a user is using Firefox, I can't rely on cookies to persist their session when they upload a file. I need their session because I need to know who they are! As a workaround, I'm using the Application object thusly:
```
Guid UploadID = Guid.NewGuid();
Application.Add(Guid.ToString(), User);
```
So, I'm creating a unique ID and using it as a key to store the `Page.User` object in the Application scope. I include that ID as a variable in the POST when the file is uploaded. Then, in the handler that accepts the file upload, I grab the User object thusly:
```
IPrincipal User = (IPrincipal)Application[Request.Form["uploadid"]];
```
This actually works, but it has two glaring drawbacks:
* If IIS, the app pool, or even just the application is restarted between the time the user visits the upload page, and actually uploads a file, their "uploadid" is deleted from application scope and the upload fails because I can't authenticate them.
* If I ever scale to a web farm (possibly even a web garden) scenario, this will completely break. I might not be worried, except I do plan on scaling this app in the future.
Does anyone have a better way? Is there a way for me to pass the actual ASP.Net session ID in a POST variable, then use that ID at the other end to retrieve the session?
I know I can get the session ID through `Session.SessionID`, and I know how to use YUI to post it to the next page. What I don't know is how to use that `SessionID` to grab the session from the state server.
Yes, I'm using a state server to store the sessions, so they persist application/IIS restarts, and will work in a web farm scenario. | [Here](http://swfupload.org/forum/generaldiscussion/98) is a post from the maintainer of [SWFUpload](http://swfupload.org) which explains how to load the session from an ID stored in Request.Form. I imagine the same thing would work for the Yahoo component.
Note the security disclaimers at the bottom of the post.
---
>
> By including a Global.asax file and the following code you can override the missing Session ID cookie:
>
>
>
```
using System;
using System.Web;
public class Global_asax : System.Web.HttpApplication
{
private void Application_BeginRequest(object sender, EventArgs e)
{
/*
Fix for the Flash Player Cookie bug in Non-IE browsers.
Since Flash Player always sends the IE cookies even in FireFox
we have to bypass the cookies by sending the values as part of the POST or GET
and overwrite the cookies with the passed in values.
The theory is that at this point (BeginRequest) the cookies have not been ready by
the Session and Authentication logic and if we update the cookies here we'll get our
Session and Authentication restored correctly
*/
HttpRequest request = HttpContext.Current.Request;
try
{
string sessionParamName = "ASPSESSID";
string sessionCookieName = "ASP.NET_SESSIONID";
string sessionValue = request.Form[sessionParamName] ?? request.QueryString[sessionParamName];
if (sessionValue != null)
{
UpdateCookie(sessionCookieName, sessionValue);
}
}
catch (Exception ex)
{
// TODO: Add logging here.
}
try
{
string authParamName = "AUTHID";
string authCookieName = FormsAuthentication.FormsCookieName;
string authValue = request.Form[authParamName] ?? request.QueryString[authParamName];
if (authValue != null)
{
UpdateCookie(authCookieName, authValue);
}
}
catch (Exception ex)
{
// TODO: Add logging here.
}
}
private void UpdateCookie(string cookieName, string cookieValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName);
if (cookie == null)
{
HttpCookie newCookie = new HttpCookie(cookieName, cookieValue);
Response.Cookies.Add(newCookie);
}
else
{
cookie.Value = cookieValue;
HttpContext.Current.Request.Cookies.Set(cookie);
}
}
}
```
>
> **Security Warning:** Don't just copy and paste this code in to your ASP.Net application without knowing what you are doing. It introduces security issues and possibilities of Cross-site Scripting.
>
>
> |
43,354 | <p>How do you reference a bitmap on the stage in flash using actionscript 3?</p>
<p>I have a bitmap on the stage in flash and at the end of the movie I would like to swap it out for the next in the sequence before the movie loops. in my library i have 3 images, exported for actionscript, with the class name img1/img2/img3. here is how my layers in flash are set out.</p>
<pre><code>layer 5 : mask2:MovieClip
layer 4 : img2:Bitmap
layer 3 : mask1:MovieClip
layer 2 : img1:Bitmap
layer 1 : background:Bitmap
</code></pre>
<p>at the end of the movie I would like to swap img1 with img2, so the movie loops seamlessly, then ideally swap img2 (on layer 4) with img3 and so on until I get to the end of my images.</p>
<p>but I can not find out how to reference the images that have already been put on the stage (in design time), any one have any idea of how to do this?</p>
<p>The end movie will hopefully load images dynamically from the web server (I have the code for this bit) and display them as well as img1/img2/img3.</p>
<p>Any help would be appreciated.</p>
<p><strong>EDIT:</strong></p>
<p>@<a href="https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#43735">81bronco</a> , I tried this but the instance name is greyed out for graphics, it will only allow me to do it with movieclips and buttons. I half got it to work by turning them into moveclips, and clearing the images in the moveclip out before adding a new one (using something simpler to what <a href="https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#44347">vanhornRF</a> suggested), but for some odd reason when the mask kicks in the images I cleared out come back for the mask animation.</p>
| [
{
"answer_id": 43477,
"author": "bitbonk",
"author_id": 4227,
"author_profile": "https://Stackoverflow.com/users/4227",
"pm_score": 1,
"selected": false,
"text": "<p>It should be something like this:</p>\n\n<pre><code>imageHolder.removeChild( imageIndex )\n</code></pre>\n\n<p>or</p>\n\n<pre><code>imageHolder.removeChildByName( imageName )\n</code></pre>\n\n<p>and after that</p>\n\n<pre><code>imageHolder.addChild( newImage )\n</code></pre>\n"
},
{
"answer_id": 43735,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 3,
"selected": true,
"text": "<p>To reference something on the stage, you need to give the stage instance a name - not give the symbol in the library a class name.</p>\n\n<p>Click on the item on the stage and look at the properties panel. There should be a text entry box just above the entry boxes for the item's dimensions. Enter a name there.</p>\n\n<p>Elsewhere in your code, you can then refer to that item on stage by it's instance name.</p>\n"
},
{
"answer_id": 44347,
"author": "vanhornRF",
"author_id": 1945,
"author_profile": "https://Stackoverflow.com/users/1945",
"pm_score": 0,
"selected": false,
"text": "<p>I would probably do something like this in your document class</p>\n\n<pre><code>for(var i:int=0; i<numChildren; i++){\n trace(getChildAt(i),\"This is the child at position \"+i);\n}\n</code></pre>\n\n<p>I do this because I still code in the flash IDE and its debugger is so very painful to get working most of the time it's easier to just trace variables out, so you can either use that for loop to print the object names of the items currently on your stage, or use a debugger program to find the objects as well.</p>\n\n<p>Now that you have the children and at what index they actually are at within the stage, you can reference them by calling getChildAt(int), you can removeChildAt(int), you can addChildAt(displayObject, int) and swapChildrenAt(int, int). The int in these arguments would represent the index position that was returned by your trace statement and the displayObject would obviously just represent anything you wanted to add to the stage or parent DisplayObject.</p>\n\n<p>Using those 4 commands you should be able to freely re-arrange any movieclips you have on stage so that they will appear to transition seamlessly.</p>\n\n<p>@81bronco One should definitely name your assets on stage if you want to uniquely reference them specifically to avoid any confusion if there ends up being a lot of items on stage</p>\n"
},
{
"answer_id": 44445,
"author": "vanhornRF",
"author_id": 1945,
"author_profile": "https://Stackoverflow.com/users/1945",
"pm_score": 0,
"selected": false,
"text": "<p>Hey Re0sless, when you remove those items from the stage do they have any event listeners attached to them, any timers or loaders? Any of those things can make an object stick around in flash's memory and not remove properly. Also on top of just removing the item, perhaps try nulling it as well? Sometimes that helps in clearing out its references so it can be properly destroyed.</p>\n\n<p>Of course it could also be something silly like removing the item at one instance doesn't remove the item from future frames as well, but I really don't think that's the case.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
] | How do you reference a bitmap on the stage in flash using actionscript 3?
I have a bitmap on the stage in flash and at the end of the movie I would like to swap it out for the next in the sequence before the movie loops. in my library i have 3 images, exported for actionscript, with the class name img1/img2/img3. here is how my layers in flash are set out.
```
layer 5 : mask2:MovieClip
layer 4 : img2:Bitmap
layer 3 : mask1:MovieClip
layer 2 : img1:Bitmap
layer 1 : background:Bitmap
```
at the end of the movie I would like to swap img1 with img2, so the movie loops seamlessly, then ideally swap img2 (on layer 4) with img3 and so on until I get to the end of my images.
but I can not find out how to reference the images that have already been put on the stage (in design time), any one have any idea of how to do this?
The end movie will hopefully load images dynamically from the web server (I have the code for this bit) and display them as well as img1/img2/img3.
Any help would be appreciated.
**EDIT:**
@[81bronco](https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#43735) , I tried this but the instance name is greyed out for graphics, it will only allow me to do it with movieclips and buttons. I half got it to work by turning them into moveclips, and clearing the images in the moveclip out before adding a new one (using something simpler to what [vanhornRF](https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#44347) suggested), but for some odd reason when the mask kicks in the images I cleared out come back for the mask animation. | To reference something on the stage, you need to give the stage instance a name - not give the symbol in the library a class name.
Click on the item on the stage and look at the properties panel. There should be a text entry box just above the entry boxes for the item's dimensions. Enter a name there.
Elsewhere in your code, you can then refer to that item on stage by it's instance name. |
43,368 | <p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p>
<p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p>
<p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p>
<p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p>
<p>E.g., it should ideally be able to:</p>
<ul>
<li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li>
<li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li>
<li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li>
<li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li>
<li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li>
<li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li>
<li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li>
<li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li>
</ul>
<p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p>
<p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
| [
{
"answer_id": 43386,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 2,
"selected": false,
"text": "<p>You should have a look at django and especially its <a href=\"http://www.djangoproject.com/documentation/forms/\" rel=\"nofollow noreferrer\">newforms</a> and <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin\" rel=\"nofollow noreferrer\">admin</a> modules. The newforms module provides a nice possibility to do server side validation with automated generation of error messages/pages for the user. Adding ajax validation is also <a href=\"http://lukeplant.me.uk/blog.php?id=1107301681\" rel=\"nofollow noreferrer\">possible</a> </p>\n"
},
{
"answer_id": 43414,
"author": "codeape",
"author_id": 3571,
"author_profile": "https://Stackoverflow.com/users/3571",
"pm_score": 1,
"selected": false,
"text": "<p>I believe that Django models does not support composite primary keys (see <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields\" rel=\"nofollow noreferrer\">documentation</a>). But perhaps you can use SQLAlchemy in Django? A <a href=\"http://www.google.com/search?q=sqlalchemy+django\" rel=\"nofollow noreferrer\">google search</a> indicates that you can. I have not used Django, so I don't know.</p>\n\n<p>I suggest you take a look at:</p>\n\n<ul>\n<li><a href=\"http://toscawidgets.org/\" rel=\"nofollow noreferrer\">ToscaWidgets</a></li>\n<li><a href=\"http://code.google.com/p/dbsprockets/\" rel=\"nofollow noreferrer\">DBSprockets</a>, including <a href=\"http://code.google.com/p/dbsprockets/wiki/DBMechanic\" rel=\"nofollow noreferrer\">DBMechanic</a></li>\n<li><a href=\"http://www.checkandshare.com/catwalk/\" rel=\"nofollow noreferrer\">Catwalk</a>. Catwalk is an application for TurboGears 1.0 that uses SQLObject, not SQLAlchemy. Also check out this <a href=\"http://www.checkandshare.com/blog/?p=41\" rel=\"nofollow noreferrer\">blog post</a> and <a href=\"http://www.checkandshare.com/CATWALK2/lview/index.html\" rel=\"nofollow noreferrer\">screencast</a>.</li>\n<li><a href=\"http://docs.turbogears.org/1.0/DataController\" rel=\"nofollow noreferrer\">FastData</a>. Also uses SQLObject.</li>\n<li><a href=\"http://code.google.com/p/formalchemy/\" rel=\"nofollow noreferrer\">formalchemy</a></li>\n<li><a href=\"http://rumdemo.toscawidgets.org/\" rel=\"nofollow noreferrer\">Rum</a></li>\n</ul>\n\n<p>I do not have any deep knowledge of any of the projects above. I am just in the process of trying to add something similar to one of my own applications as what the original question mentions. The above list is simply a list of interesting projects that I have stumbled across.</p>\n\n<p>As to web application frameworks for Python, I recommend TurboGears 2. Not that I have any experience with any of the other frameworks, I just like TurboGears...</p>\n\n<p>If the original question's author finds a solution that works well, please update or answer this thread.</p>\n"
},
{
"answer_id": 48284,
"author": "andy47",
"author_id": 2661,
"author_profile": "https://Stackoverflow.com/users/2661",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.turbogears.org/\" rel=\"nofollow noreferrer\">TurboGears</a> currently uses <a href=\"http://www.sqlobject.org/\" rel=\"nofollow noreferrer\">SQLObject</a> by default but you can use it with <a href=\"http://docs.turbogears.org/1.0/SQLAlchemy\" rel=\"nofollow noreferrer\">SQLAlchemy</a>. They are saying that the next major release of TurboGears (1.1) will use SQLAlchemy by default.</p>\n"
},
{
"answer_id": 48479,
"author": "Jason",
"author_id": 5036,
"author_profile": "https://Stackoverflow.com/users/5036",
"pm_score": 1,
"selected": false,
"text": "<p>I know that you specificity ask for a framework but I thought I would let you know about what I get up to here. I have just undergone converting my company's web application from a custom in-house ORM layer into sqlAlchemy so I am far from an expert but something that occurred to me was that sqlAlchemy has types for all of the attributes it maps from the database so why not use that to help output the right html onto the page. So we use sqlAlchemy for the back end and Cheetah templates for the front end but everything in between is basically our own still.</p>\n\n<p>We have never managed to find a framework that does exactly what we want without compromise and prefer to get all the bits that work right for us and write the glue our selves. </p>\n\n<p>Step 1. For each data type sqlAlchemy.types.INTEGER etc. Add an extra function toHtml (or many maybe toHTMLReadOnly, toHTMLAdminEdit whatever) and just have that return the template for the html, now you don't even have to care what data type your displaying if you just want to spit out a whole table you can just do (as a cheetah template or what ever your templating engine is).</p>\n\n<p>Step 2</p>\n\n<p><code><table></code></p>\n\n<p><code><tr></code></p>\n\n<p><code>#for $field in $dbObject.c:</code></p>\n\n<p><code><th>$field.name</th></code></p>\n\n<p><code>#end for</code></p>\n\n<p><code></tr></code></p>\n\n<p><code><tr></code></p>\n\n<p><code>#for $field in dbObject.c:</code></p>\n\n<p><code><td>$field.type.toHtml($field.name, $field.value)</td></code></p>\n\n<p><code>#end for</code></p>\n\n<p><code></tr></code></p>\n\n<p><code></table></code></p>\n\n<p>Using this basic method and stretching pythons introspection to its potential, in an afternoon I managed to make create read update and delete code for our whole admin section of out database, not yet with the polish of django but more then good enough for my needs.</p>\n\n<p>Step 3 Discovered the need for a third step just on Friday, wanted to upload files which as you know needs more then just the varchar data types default text box. No sweat, I just overrode the rows class in my table definition from VARCHAR to FilePath(VARCHAR) where the only difference was FilePath had a different toHtml method. Worked flawlessly.</p>\n\n<p>All that said, if there is a shrink wrapped one out there that does just what you want, use that.</p>\n\n<p>Disclaimer: This code was written from memory after midnight and probably wont produce a functioning web page.</p>\n"
},
{
"answer_id": 198348,
"author": "massimo",
"author_id": 24489,
"author_profile": "https://Stackoverflow.com/users/24489",
"pm_score": 3,
"selected": false,
"text": "<p>web2py does most of what you ask:</p>\n\n<p>Based on a field type and its validators it will render the field with the appropriate widget. You can override with</p>\n\n<pre><code>db.table.field.widget=...\n</code></pre>\n\n<p>and use a third party widget.</p>\n\n<p>web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double field. time, date and datetime fields have their own pickers. These js validation work with (not instead) of server side validation.</p>\n\n<p>There is <code>IS_EMPTY_OR(...)</code> validator.</p>\n\n<p>The DAL prevents SQL injections since everthing is escaped when goes in the DB.</p>\n\n<p>web2py prevents XSS because in {{=variable}}, 'variable' is escaped unless specified otherwise {{=XML(variable)}} or {{=XML(variable,sanitize=True)}}</p>\n\n<p>Error messages are arguments of validators for example</p>\n\n<pre><code>db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here'))\n</code></pre>\n\n<p>T is for internationalization.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4462/"
] | I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.
And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.
I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.
Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.
E.g., it should ideally be able to:
* **automatically select a suitable form widget** for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown
* **auto-generate javascript form validation code** which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc
* auto-generate a **calendar widget** for data which will end up in a DATE column
* **hint NOT NULL constraints** as javascript which complains about empty or whitespace-only data in a related input field
* generate javascript validation code which matches relevant (simple) **CHECK-constraints**
* make it easy to **avoid SQL injection**, by using prepared statements and/or validation of externally derived data
* make it easy to **avoid cross site scripting** by automatically escape outgoing strings when appropriate
* **make use of constraint names** to generate somewhat user friendly error messages in case a constrataint is violated
All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.
Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself? | web2py does most of what you ask:
Based on a field type and its validators it will render the field with the appropriate widget. You can override with
```
db.table.field.widget=...
```
and use a third party widget.
web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double field. time, date and datetime fields have their own pickers. These js validation work with (not instead) of server side validation.
There is `IS_EMPTY_OR(...)` validator.
The DAL prevents SQL injections since everthing is escaped when goes in the DB.
web2py prevents XSS because in {{=variable}}, 'variable' is escaped unless specified otherwise {{=XML(variable)}} or {{=XML(variable,sanitize=True)}}
Error messages are arguments of validators for example
```
db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here'))
```
T is for internationalization. |
43,374 | <p>What I have so far is </p>
<pre><code>#!/bin/sh
php_syntax_check()
{
retval=0
for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do
if [ -f $i ]; then
output=$(php -l $i)
retval=$?
if [ $retval -gt 0 ]; then
echo "=============================================================================="
echo "Unstaging $i for the commit due to the follow parse errors"
echo "$output"
git reset -q HEAD $i
fi
fi
done
if [ $retval -gt 0 ]; then
exit $retval
fi
}
php_syntax_check
</code></pre>
| [
{
"answer_id": 173878,
"author": "Anonymous",
"author_id": 15073,
"author_profile": "https://Stackoverflow.com/users/15073",
"pm_score": 2,
"selected": false,
"text": "<p>I'm sorry if it's offtopic, but aren't you supposed to run some kind of automated tests (which would imply that the code has no syntax errors) before doing a commit?</p>\n"
},
{
"answer_id": 547489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you've got the php5-cli installed you can write your pre-commit in PHP and use the syntax your more familiar with.</p>\n\n<p>Just do something more like.</p>\n\n<pre><code>#!/usr/bin/php\n<?php /* Your pre-commit check. */ ?>\n</code></pre>\n"
},
{
"answer_id": 3069175,
"author": "LarryH",
"author_id": 13923,
"author_profile": "https://Stackoverflow.com/users/13923",
"pm_score": 3,
"selected": true,
"text": "<p>If the commit is a partial commit (not all the changes in the working tree are committed), then this make give incorrect results since it tests the working copy and not the staged copy.</p>\n\n<p>One way to do this could be:</p>\n\n<pre><code>git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ --\nfind $TMPDIR -name '*.php' -print | xargs -n 1 php -l\n</code></pre>\n\n<p>Which would make a copy of the staged images into a scratch space and then run the test command on them there. If any of the files include other files in the build then you may have to recreate the whole staged image in the test tree and then test the changed files there (See: <a href=\"https://stackoverflow.com/questions/2412450/git-pre-commit-hook-changed-added-files/3068990#3068990\">Git pre-commit hook : changed/added files</a>).</p>\n"
},
{
"answer_id": 48700175,
"author": "Sudheesh.M.S",
"author_id": 1295321,
"author_profile": "https://Stackoverflow.com/users/1295321",
"pm_score": 0,
"selected": false,
"text": "<p>My PHP implementation of the pre-commit hook checks whether the modified files in git are 'error free' and are as per PSR2 standard using either 'php-code-sniffer' or 'php-cs-fixer' </p>\n\n<pre><code>#!/usr/local/bin/php\n<?php\n /**\n * Collect all files which have been added, copied or\n * modified and store them in an array - output\n */\n exec('git diff --cached --name-only --diff-filter=ACM', $output);\n\n $isViolated = 0;\n $violatedFiles = array();\n // $php_cs_path = \"/usr/local/bin/php-cs-fixer\";\n $php_cs_path = \"~/.composer/vendor/bin/phpcs\";\n\n foreach ($output as $fileName) {\n // Consider only PHP file for processing\n if (pathinfo($fileName, PATHINFO_EXTENSION) == \"php\") {\n $psr_output = array();\n\n // Put the changes to be made in $psr_output, if not as per PSR2 standard\n\n // php-cs-fixer\n // exec(\"{$php_cs_path} fix {$fileName} --rules=@PSR2 --dry-run --diff\", $psr_output, $return);\n\n // php-code-sniffer\n exec(\"{$php_cs_path} --standard=PSR2 --colors -n {$fileName}\", $psr_output, $return);\n\n if ($return != 0) {\n $isViolated = 1;\n $violatedFiles[] = $fileName;\n echo implode(\"\\n\", $psr_output), \"\\n\";\n }\n }\n }\n if ($isViolated == 1) {\n echo \"\\n---------------------------- IMPORTANT --------------------------------\\n\";\n echo \"\\nPlease use the suggestions above to fix the code in the following file: \\n\";\n echo \" => \" . implode(\"\\n => \", $violatedFiles);\n echo \"\\n-----------------------------------------------------------------------\\n\\n\\n\";\n exit(1);\n } else {\n echo \"\\n => Committed Successfully :-)\\n\\n\";\n exit(0);\n }\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4342/"
] | What I have so far is
```
#!/bin/sh
php_syntax_check()
{
retval=0
for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do
if [ -f $i ]; then
output=$(php -l $i)
retval=$?
if [ $retval -gt 0 ]; then
echo "=============================================================================="
echo "Unstaging $i for the commit due to the follow parse errors"
echo "$output"
git reset -q HEAD $i
fi
fi
done
if [ $retval -gt 0 ]; then
exit $retval
fi
}
php_syntax_check
``` | If the commit is a partial commit (not all the changes in the working tree are committed), then this make give incorrect results since it tests the working copy and not the staged copy.
One way to do this could be:
```
git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ --
find $TMPDIR -name '*.php' -print | xargs -n 1 php -l
```
Which would make a copy of the staged images into a scratch space and then run the test command on them there. If any of the files include other files in the build then you may have to recreate the whole staged image in the test tree and then test the changed files there (See: [Git pre-commit hook : changed/added files](https://stackoverflow.com/questions/2412450/git-pre-commit-hook-changed-added-files/3068990#3068990)). |
43,427 | <p>Say I have a site on <a href="http://example.com" rel="noreferrer">http://example.com</a>. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words</p>
<p><a href="http://example.com" rel="noreferrer">http://example.com</a> & <a href="http://example.com/" rel="noreferrer">http://example.com/</a> should be allowed, but
<a href="http://example.com/anything" rel="noreferrer">http://example.com/anything</a> and <a href="http://example.com/someendpoint.aspx" rel="noreferrer">http://example.com/someendpoint.aspx</a> should be blocked.</p>
<p>Further it would be great if I can allow certain query strings to passthrough to the home page:
<a href="http://example.com?okparam=true" rel="noreferrer">http://example.com?okparam=true</a> </p>
<p>but not
<a href="http://example.com?anythingbutokparam=true" rel="noreferrer">http://example.com?anythingbutokparam=true</a></p>
| [
{
"answer_id": 43436,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>Basic robots.txt:</p>\n\n<pre><code>Disallow: /subdir/\n</code></pre>\n\n<p>I don't think that you can create an expression saying 'everything but the root', you have to fill in all sub directories.</p>\n\n<p>The query string limitation is also not possible from robots.txt. You have to do it in the background code (the processing part), or maybe with server rewrite-rules.</p>\n"
},
{
"answer_id": 43454,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Disallow: *\nAllow: index.ext\n</code></pre>\n\n<p>If I remember correctly the second clause should override the first.</p>\n"
},
{
"answer_id": 43838,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://google.com/webmasters/tools\" rel=\"nofollow noreferrer\">Google's Webmaster Tools</a> report that disallow always takes precedence over allow, so there's no easy way of doing this in a <code>robots.txt</code> file.</p>\n\n<p>You could accomplish this by puting a <code>noindex,nofollow</code> <code>META</code> tag in the HTML every page but the home page.</p>\n"
},
{
"answer_id": 43848,
"author": "hakan",
"author_id": 3993,
"author_profile": "https://Stackoverflow.com/users/3993",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know, not all the crawlers support Allow tag. One possible solution might be putting everything except the home page into another folder and disallowing that folder.</p>\n"
},
{
"answer_id": 44711,
"author": "Boaz",
"author_id": 2892,
"author_profile": "https://Stackoverflow.com/users/2892",
"pm_score": 7,
"selected": true,
"text": "<p>So after some research, here is what I found - a solution acceptable by the major search providers: <a href=\"http://www.google.com/support/webmasters/bin/answer.py?answer=40367\" rel=\"noreferrer\">google</a> , <a href=\"http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-02.html\" rel=\"noreferrer\">yahoo</a> & msn (I could on find a validator here) :</p>\n\n<pre><code>User-Agent: *\nDisallow: /*\nAllow: /?okparam=\nAllow: /$\n</code></pre>\n\n<p>The trick is using the $ to mark the end of URL.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2892/"
] | Say I have a site on <http://example.com>. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words
<http://example.com> & <http://example.com/> should be allowed, but
<http://example.com/anything> and <http://example.com/someendpoint.aspx> should be blocked.
Further it would be great if I can allow certain query strings to passthrough to the home page:
<http://example.com?okparam=true>
but not
<http://example.com?anythingbutokparam=true> | So after some research, here is what I found - a solution acceptable by the major search providers: [google](http://www.google.com/support/webmasters/bin/answer.py?answer=40367) , [yahoo](http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-02.html) & msn (I could on find a validator here) :
```
User-Agent: *
Disallow: /*
Allow: /?okparam=
Allow: /$
```
The trick is using the $ to mark the end of URL. |
43,490 | <p>When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during <code>wm_close</code> - is <code>DestroyHandle</code> the .net equivalent?</p>
<hr>
<p>I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg:</p>
<pre><code>void Dispose(bool disposing) {
otherObject.Event -= myEventHandler;
}
</code></pre>
| [
{
"answer_id": 43499,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>Normally <code>DestroyHandle</code> is being called in <code>Dispose</code> method. So you need to make sure that all controls are disposed to avoid resource leaks.</p>\n"
},
{
"answer_id": 43560,
"author": "dan gibson",
"author_id": 4495,
"author_profile": "https://Stackoverflow.com/users/4495",
"pm_score": 2,
"selected": false,
"text": "<p><code>Dispose</code> does call <code>DestroyHandle</code>, but not always. If I close the parent window, then Windows will destroy all child windows. In this situation <code>Dispose</code> won't call <code>DestroyHandle</code> (since it is already destroyed). In other words, <code>DestroyHandle</code> is called to destroy the window, it is not called when the window is destroyed.</p>\n\n<p>The solution is to override either <code>OnHandleDestroyed</code>, or <code>Dispose</code>. I'm opting for <code>Dispose</code>.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4495/"
] | When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during `wm_close` - is `DestroyHandle` the .net equivalent?
---
I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg:
```
void Dispose(bool disposing) {
otherObject.Event -= myEventHandler;
}
``` | Normally `DestroyHandle` is being called in `Dispose` method. So you need to make sure that all controls are disposed to avoid resource leaks. |
43,503 | <p>Is there a way to detect if a flash movie contains any sound or is playing any music?<br>
It would be nice if this could be done inside a webbrowser (actionscript <strong>from another flash object</strong>, javascript,..) and could be done <em>before</em> the flash movie starts playing.</p>
<p>However, I have my doubts this will be possible altogether, so any other (programmable) solution is also appreciated</p>
| [
{
"answer_id": 43519,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, on the server side for sure. Client side? I don't know. (I'm a serverside kind of guy.) </p>\n\n<p>On the server side, one would have to parse the file, read the header and/or look for audio frames. (I've ported a haskel FLV parser to Java for indexing purposes myself, and there are other parsing utilities out there. It is possible.)</p>\n\n<p><a href=\"http://osflash.org/flv\" rel=\"nofollow noreferrer\">osflash.org's FLV page</a> has the gory details. Check out the FLV Format sections's FLV Header table. </p>\n\n<pre><code>FIELD DATA TYPE EXAMPLE DESCRIPTION\n Signature byte[3] “FLV” Always “FLV”\n Version uint8 “\\x01” (1) Currently 1 for known FLV files\n Flags uint8 bitmask “\\x05” (5, audio+video) Bitmask: 4 is audio, 1 is video\n Offset uint32-be “\\x00\\x00\\x00\\x09” (9) Total size of header (always 9 for known FLV files) \n</code></pre>\n\n<hr>\n\n<p>EDIT: My client side coding with Flash is non-existent, but I believe there is an onMetaDataLoad event that your code could catch. That might be happening a bit late for you, but maybe it is good enough?</p>\n"
},
{
"answer_id": 43911,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 1,
"selected": false,
"text": "<p>Are you asking about FLV video files or Flash \"movies\" as in SWF?</p>\n\n<p><em>Just to clarify, an FLV is the Flash Video Format (or whatever the acronym is), a regular Flash movie/application/banner would be an SWF. These are very different file formats.</em></p>\n"
},
{
"answer_id": 58240,
"author": "Antti",
"author_id": 6037,
"author_profile": "https://Stackoverflow.com/users/6037",
"pm_score": 0,
"selected": false,
"text": "<p>With the <a href=\"https://web.archive.org/web/20080917191415/http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/ByteArray.html\" rel=\"nofollow noreferrer\">ByteArray</a> you can do pretty much what you want. Before starting playback you can analyze the bytes of the FLV header (use byteArray.readByte() and refer to the specs) to determine to check if the audio flag is on. Since the FLV header is loaded almost instantly this shouldn't cause any inconvenient delay for the user.</p>\n\n<p>With SWF's it's a lot tricker -- i'm pretty sure there's no easy way to determine in advance if a swf plays audio somewhere. A way to do it could be to look at what assets the SWF has defined in the library but also then the swf could just load an external audio file (or even generate it with some hacks or the new apis in Flash player 10). If the swf's are user submitted (or something similar that's out of your immediate control) I think this is a risky road.. </p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46/"
] | Is there a way to detect if a flash movie contains any sound or is playing any music?
It would be nice if this could be done inside a webbrowser (actionscript **from another flash object**, javascript,..) and could be done *before* the flash movie starts playing.
However, I have my doubts this will be possible altogether, so any other (programmable) solution is also appreciated | Yes, on the server side for sure. Client side? I don't know. (I'm a serverside kind of guy.)
On the server side, one would have to parse the file, read the header and/or look for audio frames. (I've ported a haskel FLV parser to Java for indexing purposes myself, and there are other parsing utilities out there. It is possible.)
[osflash.org's FLV page](http://osflash.org/flv) has the gory details. Check out the FLV Format sections's FLV Header table.
```
FIELD DATA TYPE EXAMPLE DESCRIPTION
Signature byte[3] “FLV” Always “FLV”
Version uint8 “\x01” (1) Currently 1 for known FLV files
Flags uint8 bitmask “\x05” (5, audio+video) Bitmask: 4 is audio, 1 is video
Offset uint32-be “\x00\x00\x00\x09” (9) Total size of header (always 9 for known FLV files)
```
---
EDIT: My client side coding with Flash is non-existent, but I believe there is an onMetaDataLoad event that your code could catch. That might be happening a bit late for you, but maybe it is good enough? |
43,507 | <p>I have seen simple example Ajax source codes in many online tutorials. What I want to know is whether using the source code in the examples are perfectly alright or not?</p>
<p>Is there anything more to be added to the code that goes into a real world application?</p>
<p>What all steps are to be taken to make the application more robust and secure?</p>
<p>Here is a sample source code I got from the web:</p>
<pre><code>function getChats() {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
return;
}
var url="getchat.php?latest="+latest;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
} catch (e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</code></pre>
| [
{
"answer_id": 43510,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>I would use a framework like <a href=\"http://www.domassistant.com/\" rel=\"nofollow noreferrer\">DOMAssistant</a> which has already done the hard work for you and will be more robust as well as adding extra useful features.</p>\n\n<p>Apart from that, you code looks like it would do the job.</p>\n"
},
{
"answer_id": 43515,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 0,
"selected": false,
"text": "<p>I would honestly recommend using one of the many libraries available for Ajax. I use <a href=\"http://prototypejs.org/doc/latest/\" rel=\"nofollow noreferrer\">prototype</a> myself, while others prefer <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>. I like prototype because it's pretty minimal. The <a href=\"http://www.prototypejs.org/learn/introduction-to-ajax\" rel=\"nofollow noreferrer\">Prototype Ajax tutorial</a> explains it well. It also allows you to handle errors easily.</p>\n\n<pre><code>new Ajax.Request('/some_url',\n {\n method:'get',\n onSuccess: function(transport){\n var response = transport.responseText || \"no response text\";\n alert(\"Success! \\n\\n\" + response);\n },\n onFailure: function(){ alert('Something went wrong...') }\n });\n</code></pre>\n"
},
{
"answer_id": 43628,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 3,
"selected": true,
"text": "<p>The code you posted is missing one important ingredient: the function stateChanged.</p>\n\n<p>If you don't quite understand the code you posted yourself, then what happens is when the call to getchats.php is complete, a function \"stateChanged\" is called and that function will be responsible for handling the response. Since the script you're calling and the function itself is prefixed with \"gets\" then I'm pretty sure the response is something you're going to be interested in. </p>\n\n<p>That aside, there are a number of ways to improve on the code you posted. I'd guess it works by declaring a single \"xmlHttp\" object and then making that available to every function (because if it doesn't, the stateChanged function has no way of getting the response). This is fine until you run an AJAX request before the last one (or last few) haven't replied yet, which in that case the object reference is overwritten to the latest request each time.</p>\n\n<p>Also, any AJAX code worth its salt provides functionality for sucess and failure (server errors, page not found, etc.) cases so that the appriopiate message can be delivered to the user.</p>\n\n<p>If you just want to use AJAX functionality on your website then I'd point you in the direction of <a href=\"http://www.jquery.com\" rel=\"nofollow noreferrer\">jQuery</a> or a <a href=\"http://www.prototypejs.org\" rel=\"nofollow noreferrer\">similar</a> <a href=\"http://www.mootools.net\" rel=\"nofollow noreferrer\">framework</a>.</p>\n\n<p>BUT if you actually want to understand the technology and what is happening behind the scenes, I'd continue doing what you're doing and asking specific questions as you try to build a small lightweight AJAX class on your own. This is how I done it, and although I use the jQuery framework today.. I'm still glad I know how it works behind the scenes.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | I have seen simple example Ajax source codes in many online tutorials. What I want to know is whether using the source code in the examples are perfectly alright or not?
Is there anything more to be added to the code that goes into a real world application?
What all steps are to be taken to make the application more robust and secure?
Here is a sample source code I got from the web:
```
function getChats() {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
return;
}
var url="getchat.php?latest="+latest;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
} catch (e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
``` | The code you posted is missing one important ingredient: the function stateChanged.
If you don't quite understand the code you posted yourself, then what happens is when the call to getchats.php is complete, a function "stateChanged" is called and that function will be responsible for handling the response. Since the script you're calling and the function itself is prefixed with "gets" then I'm pretty sure the response is something you're going to be interested in.
That aside, there are a number of ways to improve on the code you posted. I'd guess it works by declaring a single "xmlHttp" object and then making that available to every function (because if it doesn't, the stateChanged function has no way of getting the response). This is fine until you run an AJAX request before the last one (or last few) haven't replied yet, which in that case the object reference is overwritten to the latest request each time.
Also, any AJAX code worth its salt provides functionality for sucess and failure (server errors, page not found, etc.) cases so that the appriopiate message can be delivered to the user.
If you just want to use AJAX functionality on your website then I'd point you in the direction of [jQuery](http://www.jquery.com) or a [similar](http://www.prototypejs.org) [framework](http://www.mootools.net).
BUT if you actually want to understand the technology and what is happening behind the scenes, I'd continue doing what you're doing and asking specific questions as you try to build a small lightweight AJAX class on your own. This is how I done it, and although I use the jQuery framework today.. I'm still glad I know how it works behind the scenes. |
43,511 | <p>I have some classes layed out like this</p>
<pre><code>class A
{
public virtual void Render()
{
}
}
class B : A
{
public override void Render()
{
// Prepare the object for rendering
SpecialRender();
// Do some cleanup
}
protected virtual void SpecialRender()
{
}
}
class C : B
{
protected override void SpecialRender()
{
// Do some cool stuff
}
}
</code></pre>
<p>Is it possible to prevent the C class from overriding the Render method, without breaking the following code?</p>
<pre><code>A obj = new C();
obj.Render(); // calls B.Render -> c.SpecialRender
</code></pre>
| [
{
"answer_id": 43516,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<p>You can seal individual methods to prevent them from being overridable:</p>\n\n<pre><code>public sealed override void Render()\n{\n // Prepare the object for rendering \n SpecialRender();\n // Do some cleanup \n}\n</code></pre>\n"
},
{
"answer_id": 43517,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 1,
"selected": false,
"text": "<p>In B, do </p>\n\n<pre><code>protected override sealed void Render() { ... }\n</code></pre>\n"
},
{
"answer_id": 43521,
"author": "Scott Wisniewski",
"author_id": 1737192,
"author_profile": "https://Stackoverflow.com/users/1737192",
"pm_score": -1,
"selected": false,
"text": "<p>yes. If you mark a method as Sealed then it can not be overriden in a derived class.</p>\n"
},
{
"answer_id": 43522,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, you can use the sealed keyword in the B class's implementation of Render:</p>\n\n<pre><code>class B : A\n{\n public sealed override void Render()\n {\n // Prepare the object for rendering\n SpecialRender();\n // Do some cleanup\n }\n\n protected virtual void SpecialRender()\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43531,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "<p>try <code>sealed</code></p>\n\n<pre><code>class B : A\n{\n protected sealed override void SpecialRender()\n {\n // do stuff\n }\n}\n\nclass C : B\n protected override void SpecialRender()\n {\n // not valid\n }\n}\n</code></pre>\n\n<p>Of course, I think C can get around it by being <code>new</code>.</p>\n"
},
{
"answer_id": 43547,
"author": "bitbonk",
"author_id": 4227,
"author_profile": "https://Stackoverflow.com/users/4227",
"pm_score": 0,
"selected": false,
"text": "<p>An other (better ?) way is probablby using the new keyword to prevent a particular virtual method from being overiden:</p>\n\n<pre><code>class A\n{\n public virtual void Render()\n {\n }\n}\nclass B : A\n{\n public override void Render()\n {\n // Prepare the object for rendering \n SpecialRender();\n // Do some cleanup \n }\n protected virtual void SpecialRender()\n {\n }\n}\nclass B2 : B\n{\n public new void Render()\n {\n }\n}\nclass C : B2\n{\n protected override void SpecialRender()\n {\n }\n //public override void Render() // compiler error \n //{\n //}\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3602/"
] | I have some classes layed out like this
```
class A
{
public virtual void Render()
{
}
}
class B : A
{
public override void Render()
{
// Prepare the object for rendering
SpecialRender();
// Do some cleanup
}
protected virtual void SpecialRender()
{
}
}
class C : B
{
protected override void SpecialRender()
{
// Do some cool stuff
}
}
```
Is it possible to prevent the C class from overriding the Render method, without breaking the following code?
```
A obj = new C();
obj.Render(); // calls B.Render -> c.SpecialRender
``` | You can seal individual methods to prevent them from being overridable:
```
public sealed override void Render()
{
// Prepare the object for rendering
SpecialRender();
// Do some cleanup
}
``` |
43,525 | <p>For some strange, bizarre reason, my images in my website just will not display on webkit based languages (such as safari and chrome).</p>
<p>This is the image tag</p>
<pre><code><img src="images/dukkah.jpg" class="imgleft"/>
</code></pre>
<p>Not only does it not display in the website, it wont display when accessed directly at <code>http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg</code></p>
<p>...Why?</p>
| [
{
"answer_id": 43537,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 2,
"selected": false,
"text": "<p>I have come across this problem a couple of times.</p>\n\n<p>I think it is because of some problem in the file format.</p>\n\n<p>Try importing the file in some image editor and saving it again. This should get rid of the problem.</p>\n"
},
{
"answer_id": 43539,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 0,
"selected": false,
"text": "<p>I tried the url you gave in FireFox 3 and IE 6, IE 6 won't show it either, firefox works. My guess is that there is something wrong with the jpg file.</p>\n"
},
{
"answer_id": 43540,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 3,
"selected": true,
"text": "<p>Imagemagick reports that this particular image is saved in CMYK colorspace instead of the more standard RGB. Try converting it, it should be more compatible with the webkit rendering engine.</p>\n\n<p>Imagemagick is available for download from <a href=\"http://www.imagemagick.org/script/index.php\" rel=\"nofollow noreferrer\"><a href=\"http://www.imagemagick.org/script/index.php\" rel=\"nofollow noreferrer\">http://www.imagemagick.org/script/index.php</a></a> - it's available for windows and *NIX systems.</p>\n"
},
{
"answer_id": 43543,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>Are you JPEG's compressed in Jpeg 2000 Format? If so, there is a known bug:</p>\n\n<ul>\n<li><a href=\"https://bugs.webkit.org/show_bug.cgi?id=8754\" rel=\"nofollow noreferrer\">https://bugs.webkit.org/show_bug.cgi?id=8754</a></li>\n</ul>\n"
},
{
"answer_id": 43545,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>\"The image “<a href=\"http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg\" rel=\"nofollow noreferrer\">http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg</a>” cannot be displayed, because it contains errors.\" and the image itself has some XML-fragment in it. So as others proposed: try to open with an editor and resave it.</p>\n"
},
{
"answer_id": 43552,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 0,
"selected": false,
"text": "<p>It's as stated elsewere a bug in the image. </p>\n\n<p><a href=\"http://www.irfanview.com/\" rel=\"nofollow noreferrer\">Irfanview</a> is a very good viewer that will display any image (and other formats as well), is small and free and will also let you adjust, crop or rescale images very easily without heavy programs like photoshop.</p>\n\n<p>I suggest <a href=\"http://www.irfanview.com/main_download_engl.htm\" rel=\"nofollow noreferrer\">download irfanview</a> and the image, open the image in irfanview and hit CTRL+S and save it over itself. Then upload the image again. Any problem should be solved.</p>\n"
},
{
"answer_id": 37536836,
"author": "Matt",
"author_id": 1318694,
"author_profile": "https://Stackoverflow.com/users/1318694",
"pm_score": 0,
"selected": false,
"text": "<p>Your image file does not contain image data, it contains html text:</p>\n\n<pre><code>$ curl -s http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg\n<html><head></head><body><!-- vbe --></body></html>\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] | For some strange, bizarre reason, my images in my website just will not display on webkit based languages (such as safari and chrome).
This is the image tag
```
<img src="images/dukkah.jpg" class="imgleft"/>
```
Not only does it not display in the website, it wont display when accessed directly at `http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg`
...Why? | Imagemagick reports that this particular image is saved in CMYK colorspace instead of the more standard RGB. Try converting it, it should be more compatible with the webkit rendering engine.
Imagemagick is available for download from [<http://www.imagemagick.org/script/index.php>](http://www.imagemagick.org/script/index.php) - it's available for windows and \*NIX systems. |
43,569 | <p>How to restrict the maximum number of characters that can be entered into an HTML <code><textarea></code>? I'm looking for a cross-browser solution.</p>
| [
{
"answer_id": 43571,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 5,
"selected": true,
"text": "<p>The <code>TEXTAREA</code> tag does not have a <code>MAXLENGTH</code> attribute the way that an\n<code>INPUT</code> tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be <em>typed</em> into a <code>TEXTAREA</code> tag is:</p>\n\n<pre><code><textarea onKeyPress=\"return ( this.value.length < 50 );\"></textarea>\n</code></pre>\n\n<p><strong>Note:</strong> <code>onKeyPress</code>, is going to prevent any button press, <strong>any button</strong> <em>including</em> the backspace key.</p>\n\n<p>This works because the Boolean expression compares the field's length\nbefore the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more, <code>false</code> if not. Returning false from most events cancels the default action.\nSo if the current length is already 50 (or more), the handler returns false,\nthe <code>KeyPress</code> action is cancelled, and the character is not added.</p>\n\n<p>One fly in the ointment is the possibility of pasting into a <code>TEXTAREA</code>,\nwhich does not cause the <code>KeyPress</code> event to fire, circumventing this check.\nInternet Explorer 5+ contains an <code>onPaste</code> event whose handler can contain the\ncheck. However, note that you must also take into account how many\ncharacters are waiting in the clipboard to know if the total is going to\ntake you over the limit or not. Fortunately, IE also contains a clipboard\nobject from the window object.<a href=\"http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html\" rel=\"nofollow noreferrer\">1</a> Thus:</p>\n\n<pre><code><textarea onKeyPress=\"return ( this.value.length < 50 );\"\nonPaste=\"return (( this.value.length +\nwindow.clipboardData.getData('Text').length) < 50 );\"></textarea>\n</code></pre>\n\n<p>Again, the <code>onPaste</code> event and <code>clipboardData</code> object are IE 5+ only. For a cross-browser solution, you will just have to use an <code>OnChange</code> or <code>OnBlur</code> handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly.</p>\n\n<p><a href=\"http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html\" rel=\"nofollow noreferrer\">Source</a></p>\n\n<p>Also, there is another way here, including a finished script you could include in your page:</p>\n\n<p><a href=\"http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html\" rel=\"nofollow noreferrer\">http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html</a></p>\n"
},
{
"answer_id": 11957631,
"author": "indusBull",
"author_id": 854656,
"author_profile": "https://Stackoverflow.com/users/854656",
"pm_score": 3,
"selected": false,
"text": "<p>HTML5 now allows <a href=\"https://developer.mozilla.org/en/docs/Web/HTML/Element/textarea#attr-maxlength\" rel=\"nofollow\"><code>maxlength</code> attribute on <code><textarea></code></a>. </p>\n\n<p>It is supported by all browsers except IE <= 9 and iOS Safari 8.4. See <a href=\"http://caniuse.com/#feat=maxlength\" rel=\"nofollow\">support table on caniuse.com</a>.</p>\n"
},
{
"answer_id": 23005615,
"author": "ngrashia",
"author_id": 3492139,
"author_profile": "https://Stackoverflow.com/users/3492139",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$(function(){ \n $(\"#id\").keypress(function() { \n var maxlen = 100;\nif ($(this).val().length > maxlen) { \n return false;\n} \n})\n}); \n</code></pre>\n\n<p>Reference <a href=\"https://stackoverflow.com/questions/4459610/set-maxlength-in-html-textarea\">Set maxlength in Html Textarea</a></p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512/"
] | How to restrict the maximum number of characters that can be entered into an HTML `<textarea>`? I'm looking for a cross-browser solution. | The `TEXTAREA` tag does not have a `MAXLENGTH` attribute the way that an
`INPUT` tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be *typed* into a `TEXTAREA` tag is:
```
<textarea onKeyPress="return ( this.value.length < 50 );"></textarea>
```
**Note:** `onKeyPress`, is going to prevent any button press, **any button** *including* the backspace key.
This works because the Boolean expression compares the field's length
before the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more, `false` if not. Returning false from most events cancels the default action.
So if the current length is already 50 (or more), the handler returns false,
the `KeyPress` action is cancelled, and the character is not added.
One fly in the ointment is the possibility of pasting into a `TEXTAREA`,
which does not cause the `KeyPress` event to fire, circumventing this check.
Internet Explorer 5+ contains an `onPaste` event whose handler can contain the
check. However, note that you must also take into account how many
characters are waiting in the clipboard to know if the total is going to
take you over the limit or not. Fortunately, IE also contains a clipboard
object from the window object.[1](http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html) Thus:
```
<textarea onKeyPress="return ( this.value.length < 50 );"
onPaste="return (( this.value.length +
window.clipboardData.getData('Text').length) < 50 );"></textarea>
```
Again, the `onPaste` event and `clipboardData` object are IE 5+ only. For a cross-browser solution, you will just have to use an `OnChange` or `OnBlur` handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly.
[Source](http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html)
Also, there is another way here, including a finished script you could include in your page:
<http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html> |
43,580 | <p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p>
<p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p>
<p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p>
<p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p>
<p>Does the browser add this information when posting the file to the web page?</p>
<p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
| [
{
"answer_id": 43588,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 7,
"selected": false,
"text": "<p>The <a href=\"https://docs.python.org/library/mimetypes.html\" rel=\"noreferrer\">mimetypes module</a> in the standard library will determine/guess the MIME type from a file extension.</p>\n\n<p>If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of the <a href=\"https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects\" rel=\"noreferrer\">UploadedFile</a> object.</p>\n"
},
{
"answer_id": 43616,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 3,
"selected": false,
"text": "<p>You didn't state what web server you were using, but Apache has a nice little module called <a href=\"http://httpd.apache.org/docs/1.3/mod/mod_mime_magic.html\" rel=\"nofollow noreferrer\">Mime Magic</a> which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as <a href=\"https://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python#43588\">Dave Webb Mentioned</a> the <a href=\"http://docs.python.org/lib/module-mimetypes.html\" rel=\"nofollow noreferrer\">MimeTypes Module</a> under python will work, provided an extension is handy.</p>\n\n<p>Alternatively, if you are sitting on a UNIX box you can use <code>sys.popen('file -i ' + fileName, mode='r')</code> to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is. </p>\n"
},
{
"answer_id": 1662074,
"author": "apito",
"author_id": 180008,
"author_profile": "https://Stackoverflow.com/users/180008",
"pm_score": 3,
"selected": false,
"text": "<p>in python 2.6:</p>\n<pre><code>import shlex\nimport subprocess\nmime = subprocess.Popen("/usr/bin/file --mime " + shlex.quote(PATH), shell=True, \\\n stdout=subprocess.PIPE).communicate()[0]\n</code></pre>\n"
},
{
"answer_id": 2133843,
"author": "toivotuo",
"author_id": 223251,
"author_profile": "https://Stackoverflow.com/users/223251",
"pm_score": 6,
"selected": false,
"text": "<p>More reliable way than to use the mimetypes library would be to use the python-magic package.</p>\n\n<pre><code>import magic\nm = magic.open(magic.MAGIC_MIME)\nm.load()\nm.file(\"/tmp/document.pdf\")\n</code></pre>\n\n<p>This would be equivalent to using file(1).</p>\n\n<p>On Django one could also make sure that the MIME type matches that of UploadedFile.content_type.</p>\n"
},
{
"answer_id": 2753385,
"author": "Simon Zimmermann",
"author_id": 230264,
"author_profile": "https://Stackoverflow.com/users/230264",
"pm_score": 9,
"selected": true,
"text": "<p>The python-magic method suggested by <a href=\"https://stackoverflow.com/a/2133843/5337834\">toivotuo</a> is outdated. <a href=\"http://github.com/ahupp/python-magic\" rel=\"noreferrer\">Python-magic's</a> current trunk is at Github and based on the readme there, finding the MIME-type, is done like this.</p>\n<pre><code># For MIME types\nimport magic\nmime = magic.Magic(mime=True)\nmime.from_file("testdata/test.pdf") # 'application/pdf'\n</code></pre>\n"
},
{
"answer_id": 11101343,
"author": "Helder",
"author_id": 998341,
"author_profile": "https://Stackoverflow.com/users/998341",
"pm_score": 2,
"selected": false,
"text": "<p>The mimetypes module just recognise an file type based on file extension. If you will try to recover a file type of a file without extension, the mimetypes will not works.</p>\n"
},
{
"answer_id": 12297929,
"author": "mammadori",
"author_id": 959278,
"author_profile": "https://Stackoverflow.com/users/959278",
"pm_score": 4,
"selected": false,
"text": "<p>There are 3 different libraries that wraps libmagic.</p>\n\n<p>2 of them are available on pypi (so pip install will work):</p>\n\n<ul>\n<li>filemagic</li>\n<li>python-magic</li>\n</ul>\n\n<p>And another, similar to python-magic is available directly in the latest libmagic sources, and it is the one you probably have in your linux distribution.</p>\n\n<p>In Debian the package python-magic is about this one and it is used as toivotuo said and it is not obsoleted as Simon Zimmermann said (IMHO).</p>\n\n<p>It seems to me another take (by the original author of libmagic).</p>\n\n<p>Too bad is not available directly on pypi.</p>\n"
},
{
"answer_id": 21755201,
"author": "Laxmikant Ratnaparkhi",
"author_id": 1182058,
"author_profile": "https://Stackoverflow.com/users/1182058",
"pm_score": 6,
"selected": false,
"text": "<p>This seems to be very easy</p>\n<pre><code>>>> from mimetypes import MimeTypes\n>>> import urllib \n>>> mime = MimeTypes()\n>>> url = urllib.pathname2url('Upload.xml')\n>>> mime_type = mime.guess_type(url)\n>>> print mime_type\n('application/xml', None)\n</code></pre>\n<p>Please refer <a href=\"https://stackoverflow.com/a/14412233/1182058\">Old Post</a></p>\n<p><strong>Update</strong> - In python 3+ version, it's more convenient now:</p>\n<pre><code>import mimetypes\nprint(mimetypes.guess_type("sample.html"))\n</code></pre>\n"
},
{
"answer_id": 28306825,
"author": "ewr2san",
"author_id": 2883775,
"author_profile": "https://Stackoverflow.com/users/2883775",
"pm_score": 3,
"selected": false,
"text": "<p>@toivotuo 's method worked best and most reliably for me under python3. My goal was to identify gzipped files which do not have a reliable .gz extension. I installed python3-magic.</p>\n\n<pre><code>import magic\n\nfilename = \"./datasets/test\"\n\ndef file_mime_type(filename):\n m = magic.open(magic.MAGIC_MIME)\n m.load()\n return(m.file(filename))\n\nprint(file_mime_type(filename))\n</code></pre>\n\n<p>for a gzipped file it returns:\napplication/gzip; charset=binary</p>\n\n<p>for an unzipped txt file (iostat data):\ntext/plain; charset=us-ascii</p>\n\n<p>for a tar file:\napplication/x-tar; charset=binary</p>\n\n<p>for a bz2 file: \napplication/x-bzip2; charset=binary</p>\n\n<p>and last but not least for me a .zip file: \napplication/zip; charset=binary</p>\n"
},
{
"answer_id": 39356849,
"author": "Claude COULOMBE",
"author_id": 1209842,
"author_profile": "https://Stackoverflow.com/users/1209842",
"pm_score": 3,
"selected": false,
"text": "<p>In Python 3.x and webapp with url to the file which couldn't have an extension or a fake extension. You should install python-magic, using </p>\n\n<pre><code>pip3 install python-magic\n</code></pre>\n\n<p>For Mac OS X, you should also install libmagic using</p>\n\n<pre><code>brew install libmagic\n</code></pre>\n\n<p>Code snippet</p>\n\n<pre><code>import urllib\nimport magic\nfrom urllib.request import urlopen\n\nurl = \"http://...url to the file ...\"\nrequest = urllib.request.Request(url)\nresponse = urlopen(request)\nmime_type = magic.from_buffer(response.readline())\nprint(mime_type)\n</code></pre>\n\n<p>alternatively you could put a size into the read</p>\n\n<pre><code>import urllib\nimport magic\nfrom urllib.request import urlopen\n\nurl = \"http://...url to the file ...\"\nrequest = urllib.request.Request(url)\nresponse = urlopen(request)\nmime_type = magic.from_buffer(response.read(128))\nprint(mime_type)\n</code></pre>\n"
},
{
"answer_id": 45770476,
"author": "Artem Bernatskyi",
"author_id": 5751147,
"author_profile": "https://Stackoverflow.com/users/5751147",
"pm_score": 0,
"selected": false,
"text": "<p>I 've tried a lot of examples but with Django <a href=\"http://mutagen.readthedocs.io\" rel=\"nofollow noreferrer\">mutagen</a> plays nicely. </p>\n\n<p>Example checking if files is <code>mp3</code> </p>\n\n<pre><code>from mutagen.mp3 import MP3, HeaderNotFoundError \n\ntry:\n audio = MP3(file)\nexcept HeaderNotFoundError:\n raise ValidationError('This file should be mp3')\n</code></pre>\n\n<p>The downside is that your ability to check file types is limited, but it's a great way if you want not only check for file type but also to access additional information.</p>\n"
},
{
"answer_id": 46758932,
"author": "Gringo Suave",
"author_id": 450917,
"author_profile": "https://Stackoverflow.com/users/450917",
"pm_score": 4,
"selected": false,
"text": "<p><strong>2017 Update</strong></p>\n\n<p>No need to go to github, it is on PyPi under a different name:</p>\n\n<pre><code>pip3 install --user python-magic\n# or:\nsudo apt install python3-magic # Ubuntu distro package\n</code></pre>\n\n<p>The code can be simplified as well:</p>\n\n<pre><code>>>> import magic\n\n>>> magic.from_file('/tmp/img_3304.jpg', mime=True)\n'image/jpeg'\n</code></pre>\n"
},
{
"answer_id": 50985903,
"author": "bodo",
"author_id": 1534459,
"author_profile": "https://Stackoverflow.com/users/1534459",
"pm_score": 4,
"selected": false,
"text": "<h1>Python bindings to libmagic</h1>\n\n<p>All the different answers on this topic are very confusing, so I’m hoping to give a bit more clarity with this overview of the different bindings of libmagic. Previously mammadori gave a <a href=\"https://stackoverflow.com/a/2753385/1534459\">short answer</a> listing the available option.</p>\n\n<h2>libmagic</h2>\n\n<ul>\n<li>module name: <code>magic</code></li>\n<li>pypi: <a href=\"https://pypi.org/project/file-magic/\" rel=\"noreferrer\">file-magic</a></li>\n<li>source: <a href=\"https://github.com/file/file/tree/master/python\" rel=\"noreferrer\">https://github.com/file/file/tree/master/python</a></li>\n</ul>\n\n<p>When determining a files mime-type, the tool of choice is simply called <code>file</code> and its back-end is called <code>libmagic</code>. (See the <a href=\"http://www.darwinsys.com/file/\" rel=\"noreferrer\">Project home page</a>.) The project is developed in a private cvs-repository, but there is a <a href=\"https://github.com/file/file\" rel=\"noreferrer\">read-only git mirror on github</a>.</p>\n\n<p>Now this tool, which you will need if you want to use any of the libmagic bindings with python, already comes with its own python bindings called <a href=\"https://pypi.org/project/file-magic/\" rel=\"noreferrer\"><code>file-magic</code></a>. There is not much dedicated documentation for them, but you can always have a look at the man page of the c-library: <a href=\"http://man7.org/linux/man-pages/man3/libmagic.3.html\" rel=\"noreferrer\"><code>man libmagic</code></a>. The basic usage is described in the <a href=\"https://github.com/file/file/tree/master/python\" rel=\"noreferrer\">readme file</a>:</p>\n\n<pre><code>import magic\n\ndetected = magic.detect_from_filename('magic.py')\nprint 'Detected MIME type: {}'.format(detected.mime_type)\nprint 'Detected encoding: {}'.format(detected.encoding)\nprint 'Detected file type name: {}'.format(detected.name)\n</code></pre>\n\n<p>Apart from this, you can also use the library by creating a <code>Magic</code> object using <code>magic.open(flags)</code> as shown in the <a href=\"https://github.com/file/file/tree/master/python/example.py\" rel=\"noreferrer\">example file</a>.</p>\n\n<p>Both <a href=\"https://stackoverflow.com/a/2133843/1534459\">toivotuo</a> and ewr2san use these <code>file-magic</code> bindings included in the <code>file</code> tool. They mistakenly assume, they are using the <code>python-magic</code> package. <em>This seems to indicate, that if both <code>file</code> and <code>python-magic</code> are installed, the python module <code>magic</code> refers to the former one.</em></p>\n\n<h2>python-magic</h2>\n\n<ul>\n<li>module name: <code>magic</code></li>\n<li>pypi: <a href=\"https://pypi.org/project/python-magic/\" rel=\"noreferrer\">python-magic</a></li>\n<li>source: <a href=\"https://github.com/ahupp/python-magic\" rel=\"noreferrer\">https://github.com/ahupp/python-magic</a></li>\n</ul>\n\n<p>This is the library that Simon Zimmermann talks about in <a href=\"https://stackoverflow.com/a/2753385/1534459\">his answer</a> and which is also employed by <a href=\"https://stackoverflow.com/a/2753385/1534459\">Claude COULOMBE</a> as well as <a href=\"https://stackoverflow.com/a/46758932/1534459\">Gringo Suave</a>.</p>\n\n<h2>filemagic</h2>\n\n<ul>\n<li>module name: <code>magic</code></li>\n<li>pypi: <a href=\"https://pypi.org/project/filemagic/\" rel=\"noreferrer\">filemagic</a></li>\n<li>source: <a href=\"https://github.com/aliles/filemagic\" rel=\"noreferrer\">https://github.com/aliles/filemagic</a></li>\n</ul>\n\n<p><strong>Note</strong>: This project was last updated in 2013!</p>\n\n<p>Due to being based on the same c-api, this library has some similarity with <code>file-magic</code> included in <code>libmagic</code>. It is only mentioned by <a href=\"https://stackoverflow.com/a/2753385/1534459\">mammadori</a> and no other answer employs it. </p>\n"
},
{
"answer_id": 51510950,
"author": "Ajay",
"author_id": 6164697,
"author_profile": "https://Stackoverflow.com/users/6164697",
"pm_score": 1,
"selected": false,
"text": "<p>For byte Array type data you can use \nmagic.from_buffer(_byte_array,mime=True)</p>\n"
},
{
"answer_id": 56248128,
"author": "Jak Liao",
"author_id": 6016411,
"author_profile": "https://Stackoverflow.com/users/6016411",
"pm_score": 2,
"selected": false,
"text": "<p>I try mimetypes library first. If it's not working, I use python-magic libary instead.</p>\n\n<pre><code>import mimetypes\ndef guess_type(filename, buffer=None):\nmimetype, encoding = mimetypes.guess_type(filename)\nif mimetype is None:\n try:\n import magic\n if buffer:\n mimetype = magic.from_buffer(buffer, mime=True)\n else:\n mimetype = magic.from_file(filename, mime=True)\n except ImportError:\n pass\nreturn mimetype\n</code></pre>\n"
},
{
"answer_id": 57941308,
"author": "oetzi",
"author_id": 9241362,
"author_profile": "https://Stackoverflow.com/users/9241362",
"pm_score": 3,
"selected": false,
"text": "<p>python 3 ref: <a href=\"https://docs.python.org/3.2/library/mimetypes.html\" rel=\"noreferrer\">https://docs.python.org/3.2/library/mimetypes.html</a></p>\n\n<blockquote>\n <p>mimetypes.guess_type(url, strict=True) Guess the type of a file based\n on its filename or URL, given by url. The return value is a tuple\n (type, encoding) where type is None if the type can’t be guessed\n (missing or unknown suffix) or a string of the form 'type/subtype',\n usable for a MIME content-type header.</p>\n \n <p>encoding is None for no encoding or the name of the program used to\n encode (e.g. compress or gzip). The encoding is suitable for use as a\n Content-Encoding header, not as a Content-Transfer-Encoding header.\n The mappings are table driven. Encoding suffixes are case sensitive;\n type suffixes are first tried case sensitively, then case\n insensitively.</p>\n \n <p>The optional strict argument is a flag specifying whether the list of\n known MIME types is limited to only the official types registered with\n IANA. When strict is True (the default), only the IANA types are\n supported; when strict is False, some additional non-standard but\n commonly used MIME types are also recognized.</p>\n</blockquote>\n\n<pre><code>import mimetypes\nprint(mimetypes.guess_type(\"sample.html\"))\n</code></pre>\n"
},
{
"answer_id": 62673207,
"author": "Eric McLachlan",
"author_id": 4093278,
"author_profile": "https://Stackoverflow.com/users/4093278",
"pm_score": 2,
"selected": false,
"text": "<p>I'm surprised that nobody has mentioned it but <a href=\"https://pypi.org/project/Pygments\" rel=\"nofollow noreferrer\">Pygments</a> is able to make an educated guess about the mime-type of, particularly, text documents.</p>\n<p>Pygments is actually a Python syntax highlighting library but is has a method that will make an educated guess about which of 500 supported document types your document is.\ni.e. c++ vs C# vs Python vs etc</p>\n<pre class=\"lang-py prettyprint-override\"><code>import inspect\n\ndef _test(text: str):\n from pygments.lexers import guess_lexer\n lexer = guess_lexer(text)\n mimetype = lexer.mimetypes[0] if lexer.mimetypes else None\n print(mimetype)\n\nif __name__ == "__main__":\n # Set the text to the actual defintion of _test(...) above\n text = inspect.getsource(_test)\n print('Text:')\n print(text)\n print()\n print('Result:')\n _test(text)\n</code></pre>\n<p>Output:</p>\n<pre><code>Text:\ndef _test(text: str):\n from pygments.lexers import guess_lexer\n lexer = guess_lexer(text)\n mimetype = lexer.mimetypes[0] if lexer.mimetypes else None\n print(mimetype)\n\n\nResult:\ntext/x-python\n</code></pre>\n<p>Now, it's not perfect, but if you need to be able to tell which of 500 document formats are being used, this is pretty darn useful.</p>\n"
},
{
"answer_id": 66012377,
"author": "Pedro Lobito",
"author_id": 797495,
"author_profile": "https://Stackoverflow.com/users/797495",
"pm_score": 5,
"selected": false,
"text": "<p>13 year later...<br />\nMost of the answers on this page for python 3 were either outdated or incomplete.<br />\nTo get the mime type of a file I use:</p>\n<pre><code>import mimetypes\n\nmt = mimetypes.guess_type("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")\nif mt:\n print("Mime Type:", mt[0])\nelse:\n print("Cannot determine Mime Type")\n\n# Mime Type: application/pdf\n</code></pre>\n<hr />\n<p><a href=\"https://trinket.io/python3/1485835cd1\" rel=\"noreferrer\">Live Demo</a></p>\n<hr />\n<p>From <a href=\"https://docs.python.org/3/library/mimetypes.html#mimetypes.guess_type\" rel=\"noreferrer\">Python docs</a>:</p>\n<p><code>mimetypes.guess_type</code>(<em>url</em>, <em>strict=True</em>)<a href=\"https://docs.python.org/3/library/mimetypes.html#mimetypes.guess_type\" rel=\"noreferrer\" title=\"Permalink to this definition\"></a></p>\n<p>Guess the type of a file based on its filename, path or URL, given by <em>url</em>. URL can be a string or a <a href=\"https://docs.python.org/3/glossary.html#term-path-like-object\" rel=\"noreferrer\">path-like object</a>.</p>\n<p>The return value is a tuple <code>(type, encoding)</code> where <em>type</em> is <code>None</code> if the type can’t be guessed (missing or unknown suffix) or a string of the form <code>'type/subtype'</code>, usable for a MIME <em>content-type</em> header.</p>\n<p><em>encoding</em> is <code>None</code> for no encoding or the name of the program used to encode (e.g. <strong>compress</strong> or <strong>gzip</strong>). The encoding is suitable for use as a <em>Content-Encoding</em> header, <strong>not</strong> as a <em>Content-Transfer-Encoding</em> header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively.</p>\n<p>The optional <em>strict</em> argument is a flag specifying whether the list of known MIME types is limited to only the official types <a href=\"https://www.iana.org/assignments/media-types/media-types.xhtml\" rel=\"noreferrer\">registered with IANA</a>. When <em>strict</em> is <code>True</code> (the default), only the IANA types are supported; when <em>strict</em> is <code>False</code>, some additional non-standard but commonly used MIME types are also recognized.</p>\n<p>Changed in version 3.8: Added support for url being a <a href=\"https://docs.python.org/3/glossary.html#term-path-like-object\" rel=\"noreferrer\">path-like object</a>.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.
Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.
Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.
How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows.
Does the browser add this information when posting the file to the web page?
Is there a neat python library for finding this information? A WebService or (even better) a downloadable database? | The python-magic method suggested by [toivotuo](https://stackoverflow.com/a/2133843/5337834) is outdated. [Python-magic's](http://github.com/ahupp/python-magic) current trunk is at Github and based on the readme there, finding the MIME-type, is done like this.
```
# For MIME types
import magic
mime = magic.Magic(mime=True)
mime.from_file("testdata/test.pdf") # 'application/pdf'
``` |
43,584 | <p>A very niche problem:</p>
<p>I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: <a href="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js" rel="nofollow noreferrer">http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js</a>).</p>
<p>Now on this page I have a Google Map and I use the Prototype Window library.</p>
<p>The problem occurs in IE7 and FF3.</p>
<p>This is the info FireBug gives:</p>
<pre><code>handler is undefined
? in prototype.js@3871()prototype.js (line 3877)
handler.call(element, event);
</code></pre>
<p>I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error...</p>
<p>I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :).</p>
| [
{
"answer_id": 43646,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I switched to a local version of prototypejs and added some debugging\n in the offending method (createWraper) but the debugging never appears\n before the error...</p>\n</blockquote>\n\n<p>Actually the offending function being called when the error occurs is \"wrapper\" which is created inside createWrapper (but not called there). Basically what is happening is that you've attached a function as the event handler for an element, and the function doesn't actually exist. </p>\n\n<p>If you're trying to put any debug information in to try and pinpoint which function \"doesn't exist\" then add your alert messages or firebug console output inside the wrapper function between lines 3871 and 3878.</p>\n"
},
{
"answer_id": 175102,
"author": "user25551",
"author_id": 25551,
"author_profile": "https://Stackoverflow.com/users/25551",
"pm_score": 4,
"selected": true,
"text": "<p>I just found out this error also occurs if you accidentally leave on the parenthesis on your observer call:</p>\n\n<pre><code>Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp());\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp);\n</code></pre>\n"
},
{
"answer_id": 4789535,
"author": "Slav",
"author_id": 432573,
"author_profile": "https://Stackoverflow.com/users/432573",
"pm_score": 2,
"selected": false,
"text": "<p>Really simple solution for <strong>“undefined handler” from prototype.js</strong> error in Prototype is just... fix prototype. I found advice here: <a href=\"https://prototype.lighthouseapp.com/projects/8886/tickets/407-ie7-i8-report-handler-is-null-or-not-an-object\" rel=\"nofollow\">https://prototype.lighthouseapp.com/projects/8886/tickets/407-ie7-i8-report-handler-is-null-or-not-an-object</a> and it's actually working.</p>\n\n<p>Just find line with: \n<code>handler.call(element, event);</code> \nand replace with \n<code>if (handler) handler.call(element, event)</code>\nproblem solved with prototype 1.6.0.3 and latest :)</p>\n"
},
{
"answer_id": 5219522,
"author": "TMN",
"author_id": 648107,
"author_profile": "https://Stackoverflow.com/users/648107",
"pm_score": 2,
"selected": false,
"text": "<p>This will probably cause an error:</p>\n\n<pre><code>Event.observe(myElement, 'click', myFunction(myParameters));\n</code></pre>\n\n<p>You should do it like this instead:</p>\n\n<pre><code>Event.observe(myElement, 'click', function() { myFunction(myParameters) });\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4512/"
] | A very niche problem:
I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: <http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js>).
Now on this page I have a Google Map and I use the Prototype Window library.
The problem occurs in IE7 and FF3.
This is the info FireBug gives:
```
handler is undefined
? in prototype.js@3871()prototype.js (line 3877)
handler.call(element, event);
```
I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error...
I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :). | I just found out this error also occurs if you accidentally leave on the parenthesis on your observer call:
```
Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp());
```
instead of
```
Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp);
``` |
43,589 | <p>I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?</p>
| [
{
"answer_id": 43607,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": false,
"text": "<p>First day is always YYYY-MM-01, isn't it? Example: <code>date(\"Y-M-d\", mktime(0, 0, 0, 8, 1, 2008))</code></p>\n\n<p>Last day is the previous day of the next month's first day:</p>\n\n<pre><code>$date = new DateTime(\"2008-09-01\");\n$date->modify(\"-1 day\");\necho $date->format(\"Y-m-d\");\n</code></pre>\n"
},
{
"answer_id": 43609,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 2,
"selected": false,
"text": "<p>The first day of the month is always 1.\nSo it will become</p>\n\n<pre><code>YYYY-MM-01\n</code></pre>\n\n<p>the last day can be calculated as:</p>\n\n<pre><code><?php\n $num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31\n echo \"There was $num days in August 2003\";\n?>\n</code></pre>\n"
},
{
"answer_id": 43610,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 7,
"selected": true,
"text": "<pre><code>$first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));\n$last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year));\n</code></pre>\n\n<p>See <a href=\"http://ie2.php.net/date\" rel=\"noreferrer\">date()</a> in PHP documentation.</p>\n"
},
{
"answer_id": 43618,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 2,
"selected": false,
"text": "<p>OK, first is dead easy. </p>\n\n<pre><code>date ('Y-m-d', mktime(0,0,0,MM,01,YYYY));\n</code></pre>\n\n<p>Last is a little trickier, but not much. </p>\n\n<pre><code>date ('Y-m-d', mktime(0,0,0,MM + 1,-1,YYYY));\n</code></pre>\n\n<p>If I remember my PHP date stuff correctly...</p>\n\n<p>**edit - Gah! Beaten to it about a million times...</p>\n\n<p>Edit by Pat:</p>\n\n<p>Last day should have been </p>\n\n<pre><code>date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1\n</code></pre>\n"
},
{
"answer_id": 43634,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "<p>By the way @ZombieSheep solution </p>\n\n<pre><code>date ('Y-m-d', mktime(0,0,0,$MM + 1,-1,$YYYY));\n</code></pre>\n\n<p>does not work it should be </p>\n\n<pre><code>date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1\n</code></pre>\n\n<p>Of course @Michał Słaby's accepted solution is the simplest.</p>\n"
},
{
"answer_id": 50065,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 0,
"selected": false,
"text": "<p>Just to verify that I didn't miss any loose ends:</p>\n\n<pre><code>$startDay = 1;\n\nif (date(\"m\") == 1) {\n $startMonth = 12;\n $startYear = date(\"Y\") - 1;\n\n $endMonth = 12;\n $endYear = date(\"Y\") - 1;\n}\nelse {\n $startMonth = date(\"m\") - 1;\n $startYear = date(\"Y\");\n\n $endMonth = date(\"m\") - 1;\n $endYear = date(\"Y\");\n}\n\n$endDay = date(\"d\") - 1;\n\n$startDate = date('Y-m-d', mktime(0, 0, 0, $startMonth , $startDay, $startYear));\n$endDate = date('Y-m-d', mktime(0, 0, 0, $endMonth, $endDay, $endYear));\n</code></pre>\n"
},
{
"answer_id": 9225401,
"author": "Eranda",
"author_id": 1181127,
"author_profile": "https://Stackoverflow.com/users/1181127",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\necho \"Month Start - \" . $monthStart = date(\"Y-m-1\") . \"<br/>\";\n$num = cal_days_in_month(CAL_GREGORIAN, date(\"m\"), date(\"Y\"));\necho \"Monthe End - \" . $monthEnd = date(\"Y-m-\".$num);\n?>\n</code></pre>\n"
},
{
"answer_id": 16603663,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way to do this with PHP is </p>\n\n<pre><code>$dateBegin = strtotime(\"first day of last month\"); \n$dateEnd = strtotime(\"last day of last month\");\n\necho date(\"MYDATEFORMAT\", $dateBegin); \necho \"<br>\"; \necho date(\"MYDATEFORMAT\", $dateEnd);\n</code></pre>\n\n<p>Or the last week</p>\n\n<pre><code>if (date('N', time()) == 7) {\n$dateBegin = strtotime(\"-2 weeks Monday\");\n$dateEnd = strtotime(\"last Sunday\");\n} else {\n$dateBegin = strtotime(\"Monday last week\"); \n$dateEnd = strtotime(\"Sunday last week\"); \n}\n</code></pre>\n\n<p>Or the last year</p>\n\n<pre><code>$dateBegin = strtotime(\"1/1 last year\");\n$dateEnd = strtotime(\"12/31 this year\");\n</code></pre>\n"
},
{
"answer_id": 17627103,
"author": "Nate",
"author_id": 1205600,
"author_profile": "https://Stackoverflow.com/users/1205600",
"pm_score": 0,
"selected": false,
"text": "<p>try this to get the number of days in the month:</p>\n\n<pre><code>$numdays = date('t', mktime(0, 0, 0, $m, 1, $Y));\n</code></pre>\n"
},
{
"answer_id": 27856580,
"author": "csonuryilmaz",
"author_id": 1750142,
"author_profile": "https://Stackoverflow.com/users/1750142",
"pm_score": 0,
"selected": false,
"text": "<p>Example; I want to get first day and last day of current month.</p>\n\n<pre><code>$month = (int) date('F');\n$year = (int) date('Y');\n\ndate('Y-m-d', mktime(0, 0, 0, $month + 1, 1, $year)); //first\ndate('Y-m-d', mktime(0, 0, 0, $month + 2, 0, $year)); //last\n</code></pre>\n\n<p>When you run this for instance at date 2015-01-09, the first and last values will be sequentially;</p>\n\n<pre><code>2015-01-01\n2015-01-31\n</code></pre>\n\n<p>Tested. </p>\n"
},
{
"answer_id": 48094516,
"author": "arturwwl",
"author_id": 8367985,
"author_profile": "https://Stackoverflow.com/users/8367985",
"pm_score": 0,
"selected": false,
"text": "<p>From <a href=\"https://stackoverflow.com/questions/39438496/last-day-of-next-month-date-timestamp-in-php\">here(get next month last day)</a> that is marked as duplicated, so i can't add comment there, but people can got bad answers from there. </p>\n\n<p>Correct one for last day of next month:</p>\n\n<pre><code>echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-t'));\n</code></pre>\n\n<p>Correct one for first day of next month:</p>\n\n<pre><code>echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-01'));\n</code></pre>\n\n<p>Code like this will be providing March from January, so that's not what could be expected.</p>\n\n<p><code>echo ((new DateTime())->modify('+1 month')->format('Y-m-t'));</code></p>\n"
},
{
"answer_id": 70531006,
"author": "palmer",
"author_id": 1390834,
"author_profile": "https://Stackoverflow.com/users/1390834",
"pm_score": 0,
"selected": false,
"text": "<p>proper way to build a relative date from now is:</p>\n<pre><code>//bad example - will be broken when generated at 30 of December (broken February)\n echo date("Y-m-d", strtotime("now"))."\\n";\n echo date("Y-m-d", strtotime("now + 1 month"))."\\n";\n echo date("Y-m-d", strtotime("now + 2 month"))."\\n";\n echo date("Y-m-d", strtotime("now + 3 month"))."\\n";\n \n//good example, you can change first day to last day or any day\n echo date("Y-m-d", strtotime("first day of this month"))."\\n";\n echo date("Y-m-d", strtotime("first day of next month"))."\\n";\n echo date("Y-m-d", strtotime("first day of +2 month"))."\\n";\n echo date("Y-m-d", strtotime("first day of +3 month"))."\\n";\n</code></pre>\n<p>and the result will be:</p>\n<pre><code>2021-12-30\n2022-01-30\n2022-03-02\n2022-03-30\n\n2021-12-01\n2022-01-01\n2022-02-01\n2022-03-01\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this? | ```
$first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));
$last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year));
```
See [date()](http://ie2.php.net/date) in PHP documentation. |
43,632 | <p>I've seen lots of examples of making an entire regular expression case-insensitive. What I'm wondering about is having just part of the expression be case-insensitive.</p>
<p>For example, let's say I have a string like this:</p>
<pre><code>fooFOOfOoFoOBARBARbarbarbAr
</code></pre>
<p>What if I want to match all occurrences of "foo" regardless of case but I only want to match the upper-case "BAR"s?</p>
<p>The ideal solution would be something that works across regex flavors but I'm interested in hearing language-specific ones as well (Thanks <a href="https://stackoverflow.com/questions/43632/can-you-make-just-part-of-a-regex-case-insensitive#43636">Espo</a>)</p>
<p><strong><em>Edit</em></strong></p>
<p>The link Espo provided was very helpful. There's a good example in there about turning modifiers on and off within the expression.</p>
<p>For my contrived example, I can do something like this:</p>
<pre><code>(?i)foo*(?-i)|BAR
</code></pre>
<p>which makes the match case-insensitive for just the foo portion of the match.</p>
<p>That seemed to work in most regex implementations except Javascript, Python, and a few others (as Espo mentioned). </p>
<p>The big ones that I was wondering about (Perl, PHP, .NET) all support inline mode changes.</p>
| [
{
"answer_id": 43636,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 8,
"selected": true,
"text": "<p>Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier.</p>\n\n<p>Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?ism) in the middle of the regex, the modifier only applies to the part of the regex to the right of the modifier. You can turn off modes by preceding them with a minus sign. All modes after the minus sign will be turned off. E.g. (?i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.</p>\n\n<p>Not all regex flavors support this. JavaScript and Python apply all mode modifiers to the entire regular expression. They don't support the (?-ismx) syntax, since turning off an option is pointless when mode modifiers apply to the whole regular expressions. All options are off by default.</p>\n\n<p>You can quickly test how the regex flavor you're using handles mode modifiers. The regex (?i)te(?-i)st should match test and TEst, but not teST or TEST.</p>\n\n<p><a href=\"http://www.regular-expressions.info/modifiers.html\" rel=\"noreferrer\">Source</a></p>\n"
},
{
"answer_id": 43641,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>You could use </p>\n\n<pre><code>(?:F|f)(?:O|o)(?:O|o)\n</code></pre>\n\n<p>The ?: in the brackets in .Net means it's non-capturing, and just used to group the terms of the | (or) statement.</p>\n"
},
{
"answer_id": 43654,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 3,
"selected": false,
"text": "<p>What language are you using? A standard way to do this would be something like /([Ff][Oo]{2}|BAR)/ with case sensitivity on, but in Java, for example, there is a case sensitivity modifier (?i) which makes all characters to the right of it case insensitive and (?-i) which forces sensitivity. An example of that Java regex modifier can be found <a href=\"http://exampledepot.com/egs/java.util.regex/Case.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 43655,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>Unfortunately syntax for case-insensitive matching is not common. \nIn .NET you can use RegexOptions.IgnoreCase flag or <strong>?i</strong> modifier</p>\n"
},
{
"answer_id": 58818125,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 4,
"selected": false,
"text": "<p>It is true one can rely on inline modifiers as described in <a href=\"https://www.regular-expressions.info/modifiers.html\" rel=\"noreferrer\"><em>Turning Modes On and Off for Only Part of The Regular Expression</em></a>:</p>\n<blockquote>\n<p>The regex <code>(?i)te(?-i)st</code> should match test and <code>TEst</code>, but not <code>teST</code> or <code>TEST</code>.</p>\n</blockquote>\n<p>However, a bit more supported feature is an <strong><code>(?i:...)</code> inline modifier group</strong> (see <a href=\"https://www.regular-expressions.info/modifiers.html\" rel=\"noreferrer\"><em>Modifier Spans</em></a>). The syntax is <code>(?i:</code>, then the pattern that you want to make cas-insensitive, and then a <code>)</code>.</p>\n<pre><code>(?i:foo)|BAR\n</code></pre>\n<p><strong>The reverse</strong>: If your pattern is compiled with a case insensitive option and you need to make a part of a regex case sensitive, you add <code>-</code> after <code>?</code>: <code>(?-i:...)</code>.</p>\n<p>Example uses in various languages (wrapping the matches with angle brackets):</p>\n<ul>\n<li><a href=\"/questions/tagged/php\" class=\"post-tag\" title=\"show questions tagged 'php'\" rel=\"tag\">php</a> - <code>preg_replace("~(?i:foo)|BAR~", '<$0>', "fooFOOfOoFoOBARBARbarbarbAr")</code> (<a href=\"https://3v4l.org/o25di\" rel=\"noreferrer\">demo</a>)</li>\n<li><a href=\"/questions/tagged/python\" class=\"post-tag\" title=\"show questions tagged 'python'\" rel=\"tag\">python</a> - <code>re.sub(r'(?i:foo)|BAR', r'<\\g<0>>', 'fooFOOfOoFoOBARBARbarbarbAr')</code> (<a href=\"https://ideone.com/53pLjc\" rel=\"noreferrer\">demo</a>) (note <a href=\"https://docs.python.org/3/library/re.html\" rel=\"noreferrer\">Python <code>re</code> supports</a> inline modifier groups since Python 3.6)</li>\n<li><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a> / <a href=\"/questions/tagged/vb.net\" class=\"post-tag\" title=\"show questions tagged 'vb.net'\" rel=\"tag\">vb.net</a> / <a href=\"/questions/tagged/.net\" class=\"post-tag\" title=\"show questions tagged '.net'\" rel=\"tag\">.net</a> - <code>Regex.Replace("fooFOOfOoFoOBARBARbarbarbAr", "(?i:foo)|BAR", "<$&>")</code> (<a href=\"https://ideone.com/WO1bVv\" rel=\"noreferrer\">demo</a>)</li>\n<li><a href=\"/questions/tagged/java\" class=\"post-tag\" title=\"show questions tagged 'java'\" rel=\"tag\">java</a> - <code>"fooFOOfOoFoOBARBARbarbarbAr".replaceAll("(?i:foo)|BAR", "<$0>")</code> (<a href=\"https://ideone.com/AHUrFx\" rel=\"noreferrer\">demo</a>)</li>\n<li><a href=\"/questions/tagged/perl\" class=\"post-tag\" title=\"show questions tagged 'perl'\" rel=\"tag\">perl</a> - <code>$s =~ s/(?i:foo)|BAR/<$&>/g</code> (<a href=\"https://ideone.com/4OewGe\" rel=\"noreferrer\">demo</a>)</li>\n<li><a href=\"/questions/tagged/ruby\" class=\"post-tag\" title=\"show questions tagged 'ruby'\" rel=\"tag\">ruby</a> - <code>"fooFOOfOoFoOBARBARbarbarbAr".gsub(/(?i:foo)|BAR/, '<\\0>')</code> (<a href=\"https://ideone.com/GZCbiI\" rel=\"noreferrer\">demo</a>)</li>\n<li><a href=\"/questions/tagged/r\" class=\"post-tag\" title=\"show questions tagged 'r'\" rel=\"tag\">r</a> - <code>gsub("((?i:foo)|BAR)", "<\\\\1>", "fooFOOfOoFoOBARBARbarbarbAr", perl=TRUE)</code> (<a href=\"https://ideone.com/ipk4K4\" rel=\"noreferrer\">demo</a>)</li>\n<li><a href=\"/questions/tagged/swift\" class=\"post-tag\" title=\"show questions tagged 'swift'\" rel=\"tag\">swift</a> - <code>"fooFOOfOoFoOBARBARbarbarbAr".replacingOccurrences(of: "(?i:foo)|BAR", with: "<$0>", options: [.regularExpression])</code></li>\n<li><a href=\"/questions/tagged/go\" class=\"post-tag\" title=\"show questions tagged 'go'\" rel=\"tag\">go</a> - (uses RE2) - <code>regexp.MustCompile(`(?i:foo)|BAR`).ReplaceAllString( "fooFOOfOoFoOBARBARbarbarbAr", `<${0}>`)</code> (<a href=\"https://play.golang.org/p/e5iH26spNGo\" rel=\"noreferrer\">demo</a>)</li>\n</ul>\n<p>Not supported in <a href=\"/questions/tagged/javascript\" class=\"post-tag\" title=\"show questions tagged 'javascript'\" rel=\"tag\">javascript</a>, <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged 'bash'\" rel=\"tag\">bash</a>, <a href=\"/questions/tagged/sed\" class=\"post-tag\" title=\"show questions tagged 'sed'\" rel=\"tag\">sed</a>, <a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged 'c++'\" rel=\"tag\">c++</a> <code>std::regex</code>, <a href=\"/questions/tagged/lua\" class=\"post-tag\" title=\"show questions tagged 'lua'\" rel=\"tag\">lua</a>, <a href=\"/questions/tagged/tcl\" class=\"post-tag\" title=\"show questions tagged 'tcl'\" rel=\"tag\">tcl</a>.</p>\n<p>In these case, you can put both letter variants into a character class (not a group, see <a href=\"https://stackoverflow.com/q/22132450/3832970\">Why is a character class faster than alternation?</a>). Examples:</p>\n<ul>\n<li><a href=\"/questions/tagged/sed\" class=\"post-tag\" title=\"show questions tagged 'sed'\" rel=\"tag\">sed</a> <a href=\"/questions/tagged/posix-ere\" class=\"post-tag\" title=\"show questions tagged 'posix-ere'\" rel=\"tag\">posix-ere</a> - <code>sed -E 's/[Ff][Oo][Oo]|BAR/<&>/g' file > outfile</code> (<a href=\"https://ideone.com/JrST8o\" rel=\"noreferrer\">demo</a>)</li>\n<li><a href=\"/questions/tagged/grep\" class=\"post-tag\" title=\"show questions tagged 'grep'\" rel=\"tag\">grep</a> <a href=\"/questions/tagged/posix-ere\" class=\"post-tag\" title=\"show questions tagged 'posix-ere'\" rel=\"tag\">posix-ere</a> - <code>grep -Eo '[Ff][Oo][Oo]|BAR' file</code> (or if you are using GNU grep, you can still use the PCRE regex, <code>grep -Po '(?i:foo)|BAR' file</code> (<a href=\"https://ideone.com/i6JRbL\" rel=\"noreferrer\">demo</a>))</li>\n</ul>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | I've seen lots of examples of making an entire regular expression case-insensitive. What I'm wondering about is having just part of the expression be case-insensitive.
For example, let's say I have a string like this:
```
fooFOOfOoFoOBARBARbarbarbAr
```
What if I want to match all occurrences of "foo" regardless of case but I only want to match the upper-case "BAR"s?
The ideal solution would be something that works across regex flavors but I'm interested in hearing language-specific ones as well (Thanks [Espo](https://stackoverflow.com/questions/43632/can-you-make-just-part-of-a-regex-case-insensitive#43636))
***Edit***
The link Espo provided was very helpful. There's a good example in there about turning modifiers on and off within the expression.
For my contrived example, I can do something like this:
```
(?i)foo*(?-i)|BAR
```
which makes the match case-insensitive for just the foo portion of the match.
That seemed to work in most regex implementations except Javascript, Python, and a few others (as Espo mentioned).
The big ones that I was wondering about (Perl, PHP, .NET) all support inline mode changes. | Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier.
Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?ism) in the middle of the regex, the modifier only applies to the part of the regex to the right of the modifier. You can turn off modes by preceding them with a minus sign. All modes after the minus sign will be turned off. E.g. (?i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.
Not all regex flavors support this. JavaScript and Python apply all mode modifiers to the entire regular expression. They don't support the (?-ismx) syntax, since turning off an option is pointless when mode modifiers apply to the whole regular expressions. All options are off by default.
You can quickly test how the regex flavor you're using handles mode modifiers. The regex (?i)te(?-i)st should match test and TEst, but not teST or TEST.
[Source](http://www.regular-expressions.info/modifiers.html) |
43,643 | <p>Given the code bellow, how do I style the radio buttons to be next to the labels and style the label of the selected radio button differently than the other labels?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="stylesheet">
<link href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="stylesheet">
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="color" value="" id="SubmitQuestion" />
<input type="radio" name="color" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<input type="radio" name="color" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<input type="radio" name="color" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div></code></pre>
</div>
</div>
</p>
<p>Also let me state that I use the yui css styles as base. If you are not familir with them, they can be found here:</p>
<ul>
<li><a href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="nofollow noreferrer">reset-fonts-grids.css</a></li>
<li><a href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="nofollow noreferrer">base-min.css</a></li>
</ul>
<p>Documentation for them both here : <a href="http://developer.yahoo.com/yui/reset/" rel="nofollow noreferrer">Yahoo! UI Library</a></p>
<p>@pkaeding: Thanks. I tried some floating both thing that just looked messed up. The styling active radio button seemed to be doable with some input[type=radio]:active nomination on a google search, but I didnt get it to work properly. So the question I guess is more: Is this possible on all of todays modern browsers, and if not, what is the minimal JS needed?</p>
| [
{
"answer_id": 43703,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 3,
"selected": false,
"text": "<p>This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: <a href=\"http://www.webmasterworld.com/forum83/6942.htm\" rel=\"nofollow noreferrer\">http://www.webmasterworld.com/forum83/6942.htm</a></p>\n\n<pre><code><style type=\"text/css\">\n.input input {\n float: left;\n}\n.input label {\n margin: 5px;\n}\n</style>\n<div class=\"input radio\">\n <fieldset>\n <legend>What color is the sky?</legend>\n <input type=\"hidden\" name=\"data[Submit][question]\" value=\"\" id=\"SubmitQuestion\" />\n\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion1\" value=\"1\" />\n <label for=\"SubmitQuestion1\">A strange radient green.</label>\n\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion2\" value=\"2\" />\n <label for=\"SubmitQuestion2\">A dark gloomy orange</label>\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion3\" value=\"3\" />\n <label for=\"SubmitQuestion3\">A perfect glittering blue</label>\n </fieldset>\n</div>\n</code></pre>\n"
},
{
"answer_id": 44043,
"author": "Chris Zwiryk",
"author_id": 734,
"author_profile": "https://Stackoverflow.com/users/734",
"pm_score": 6,
"selected": true,
"text": "<p>The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.</p>\n\n<h3>Getting the Label Near the Radio Button</h3>\n\n<p>I'm not sure what you mean by \"next to\": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into <code>float:</code> territory):</p>\n\n<ul>\n<li>Use <code><br />s </code> to split the options apart and some CSS to vertically align them:</li>\n</ul>\n\n\n\n<pre><code><style type='text/css'>\n .input input\n {\n width: 20px;\n }\n</style>\n<div class=\"input radio\">\n <fieldset>\n <legend>What color is the sky?</legend>\n <input type=\"hidden\" name=\"data[Submit][question]\" value=\"\" id=\"SubmitQuestion\" />\n\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion1\" value=\"1\" />\n <label for=\"SubmitQuestion1\">A strange radient green.</label>\n <br />\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion2\" value=\"2\" />\n <label for=\"SubmitQuestion2\">A dark gloomy orange</label>\n <br />\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion3\" value=\"3\" />\n <label for=\"SubmitQuestion3\">A perfect glittering blue</label>\n </fieldset>\n</div>\n</code></pre>\n\n<ul>\n<li>Follow <em>A List Apart</em>'s article: <a href=\"http://www.alistapart.com/articles/prettyaccessibleforms\" rel=\"noreferrer\">Prettier Accessible Forms</a></li>\n</ul>\n\n<h3>Applying a Style to the Currently Selected Label + Radio Button</h3>\n\n<p>Styling the <code><label></code> is why you'll need to resort to Javascript. A library like <a href=\"http://jquery.com\" rel=\"noreferrer\">jQuery</a>\nis perfect for this:</p>\n\n<pre><code><style type='text/css'>\n .input label.focused\n {\n background-color: #EEEEEE;\n font-style: italic;\n }\n</style>\n<script type='text/javascript' src='jquery.js'></script>\n<script type='text/javascript'>\n $(document).ready(function() {\n $('.input :radio').focus(updateSelectedStyle);\n $('.input :radio').blur(updateSelectedStyle);\n $('.input :radio').change(updateSelectedStyle);\n })\n\n function updateSelectedStyle() {\n $('.input :radio').removeClass('focused').next().removeClass('focused');\n $('.input :radio:checked').addClass('focused').next().addClass('focused');\n }\n</script>\n</code></pre>\n\n<p>The <code>focus</code> and <code>blur</code> hooks are needed to make this work in IE.</p>\n"
},
{
"answer_id": 44072,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 5,
"selected": false,
"text": "<p>For any CSS3-enabled browser you can use an <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors\" rel=\"nofollow noreferrer\">adjacent sibling selector</a> for styling your labels</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>input:checked + label {\n color: white;\n} \n</code></pre>\n\n<p>MDN's <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors#Browser_compatibility\" rel=\"nofollow noreferrer\">browser compatibility table</a> says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
] | Given the code bellow, how do I style the radio buttons to be next to the labels and style the label of the selected radio button differently than the other labels?
```html
<link href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="stylesheet">
<link href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="stylesheet">
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="color" value="" id="SubmitQuestion" />
<input type="radio" name="color" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<input type="radio" name="color" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<input type="radio" name="color" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
```
Also let me state that I use the yui css styles as base. If you are not familir with them, they can be found here:
* [reset-fonts-grids.css](http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css)
* [base-min.css](http://yui.yahooapis.com/2.5.2/build/base/base-min.css)
Documentation for them both here : [Yahoo! UI Library](http://developer.yahoo.com/yui/reset/)
@pkaeding: Thanks. I tried some floating both thing that just looked messed up. The styling active radio button seemed to be doable with some input[type=radio]:active nomination on a google search, but I didnt get it to work properly. So the question I guess is more: Is this possible on all of todays modern browsers, and if not, what is the minimal JS needed? | The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.
### Getting the Label Near the Radio Button
I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into `float:` territory):
* Use `<br />s` to split the options apart and some CSS to vertically align them:
```
<style type='text/css'>
.input input
{
width: 20px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
```
* Follow *A List Apart*'s article: [Prettier Accessible Forms](http://www.alistapart.com/articles/prettyaccessibleforms)
### Applying a Style to the Currently Selected Label + Radio Button
Styling the `<label>` is why you'll need to resort to Javascript. A library like [jQuery](http://jquery.com)
is perfect for this:
```
<style type='text/css'>
.input label.focused
{
background-color: #EEEEEE;
font-style: italic;
}
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('.input :radio').focus(updateSelectedStyle);
$('.input :radio').blur(updateSelectedStyle);
$('.input :radio').change(updateSelectedStyle);
})
function updateSelectedStyle() {
$('.input :radio').removeClass('focused').next().removeClass('focused');
$('.input :radio:checked').addClass('focused').next().addClass('focused');
}
</script>
```
The `focus` and `blur` hooks are needed to make this work in IE. |
43,711 | <p>I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value?</p>
| [
{
"answer_id": 43716,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 4,
"selected": false,
"text": "<p>I think creating a separate clock class for something simple like getting the current date is a bit overkill. </p>\n\n<p>You can pass today's date as a parameter so you can input a different date in the test. This has the added benefit of making your code more flexible.</p>\n"
},
{
"answer_id": 43718,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": -1,
"selected": false,
"text": "<p>Have you considered using conditional compilation to control what happens during debug/deployment?</p>\n<p>e.g.</p>\n<pre><code>DateTime date;\n#if DEBUG\n date = new DateTime(2008, 09, 04);\n#else\n date = DateTime.Now;\n#endif\n</code></pre>\n<p>Failing that, you want to expose the property so you can manipulate it, this is all part of the challenge of writing <em>testable</em> code, which is something I am currently wrestling myself :D</p>\n<h3>Edit</h3>\n<p>A big part of me would preference <a href=\"https://stackoverflow.com/questions/43711/whats-a-good-way-to-overwrite-datetimenow-during-testing#43720\">Blair's approach</a>. This allows you to "hot plug" parts of the code to aid in testing. It all follows the design principle <em>encapsulate what varies</em> test code is no different to production code, its just no one ever sees it externally.</p>\n<p>Creating and interface may seem like a lot of work for this example though (which is why I opted for conditional compilation).</p>\n"
},
{
"answer_id": 43720,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 8,
"selected": true,
"text": "<p>My preference is to have classes that use time actually rely on an interface, such as</p>\n\n<pre><code>interface IClock\n{\n DateTime Now { get; } \n}\n</code></pre>\n\n<p>With a concrete implementation</p>\n\n<pre><code>class SystemClock: IClock\n{\n DateTime Now { get { return DateTime.Now; } }\n}\n</code></pre>\n\n<p>Then if you want, you can provide any other kind of clock you want for testing, such as</p>\n\n<pre><code>class StaticClock: IClock\n{\n DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } }\n}\n</code></pre>\n\n<p>There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a <a href=\"http://codebetter.com/blogs/jean-paul_boodhoo/archive/2007/10/15/the-static-gateway-pattern.aspx\" rel=\"noreferrer\">Static Gateway Pattern</a>).</p>\n\n<p>Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that's just going to introduce pain on other levels.</p>\n\n<p>Also, using <code>DateTime.Now</code> and including it in your calculations doesn't just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won't allow you to test those scenarios. Or at least not whenever you want.</p>\n"
},
{
"answer_id": 43721,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "<p>You could inject the class (better: method/<strong>delegate</strong>) you use for <code>DateTime.Now</code> in the class being tested. Have <code>DateTime.Now</code> be a default value and only set it in testing to a dummy method that returns a constant value.</p>\n\n<p><strong>EDIT:</strong> What Blair Conrad said (he has some code to look at). Except, I tend to prefer delegates for this, as they don't clutter up your class hierarchy with stuff like <code>IClock</code>...</p>\n"
},
{
"answer_id": 43731,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 6,
"selected": false,
"text": "<p>Ayende Rahien <a href=\"http://www.ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx\" rel=\"noreferrer\">uses</a> a static method that is rather simple...</p>\n\n<pre><code>public static class SystemTime\n{\n public static Func<DateTime> Now = () => DateTime.Now;\n}\n</code></pre>\n"
},
{
"answer_id": 52077,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 4,
"selected": false,
"text": "<p>The key to successful unit testing is <strong>decoupling</strong>. You have to separate your interesting code from its external dependencies, so it can be tested in isolation. (Luckily, Test-Driven Development produces decoupled code.)</p>\n\n<p>In this case, your external is the current DateTime. </p>\n\n<p>My advice here is to extract the logic that deals with the DateTime to a new method or class or whatever makes sense in your case, and pass the DateTime in. Now, your unit test can pass an arbitrary DateTime in, to produce predictable results.</p>\n"
},
{
"answer_id": 2183744,
"author": "Pawel Lesnikowski",
"author_id": 80894,
"author_profile": "https://Stackoverflow.com/users/80894",
"pm_score": 3,
"selected": false,
"text": "<p>I'd suggest using IDisposable pattern:</p>\n\n<pre><code>[Test] \npublic void CreateName_AddsCurrentTimeAtEnd() \n{\n using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00)))\n {\n string name = new ReportNameService().CreateName(...);\n Assert.AreEqual(\"name 2010-12-31 23:59:00\", name);\n } \n}\n</code></pre>\n\n<p>In detail described here:\n<a href=\"http://www.lesnikowski.com/blog/index.php/testing-datetime-now/\" rel=\"noreferrer\">http://www.lesnikowski.com/blog/index.php/testing-datetime-now/</a></p>\n"
},
{
"answer_id": 2183833,
"author": "João Angelo",
"author_id": 204699,
"author_profile": "https://Stackoverflow.com/users/204699",
"pm_score": 4,
"selected": false,
"text": "<p>Another one using Microsoft Moles (<a href=\"http://research.microsoft.com/en-us/projects/moles/\" rel=\"noreferrer\">Isolation framework for .NET</a>).</p>\n\n<pre><code>MDateTime.NowGet = () => new DateTime(2000, 1, 1);\n</code></pre>\n\n<blockquote>\n <p>Moles allows to replace any .NET\n method with a delegate. Moles supports\n static or non-virtual methods. Moles\n relies on the profiler from Pex.</p>\n</blockquote>\n"
},
{
"answer_id": 20906399,
"author": "mmilleruva",
"author_id": 1301147,
"author_profile": "https://Stackoverflow.com/users/1301147",
"pm_score": 5,
"selected": false,
"text": "<p>Using Microsoft Fakes to create a shim is a really easy way to do this. Suppose I had the following class:</p>\n\n<pre><code>public class MyClass\n{\n public string WhatsTheTime()\n {\n return DateTime.Now.ToString();\n }\n\n}\n</code></pre>\n\n<p>In Visual Studio 2012 you can add a Fakes assembly to your test project by right clicking on the assembly you want to create Fakes/Shims for and selecting \"Add Fakes Assembly\"</p>\n\n<p><img src=\"https://i.stack.imgur.com/i7wVa.jpg\" alt=\"Adding Fakes Assembly\"></p>\n\n<p>Finally, Here is what the test class would look like: </p>\n\n<pre><code>using System;\nusing ConsoleApplication11;\nusing Microsoft.QualityTools.Testing.Fakes;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace DateTimeTest\n{\n[TestClass]\npublic class UnitTest1\n{\n [TestMethod]\n public void TestWhatsTheTime()\n {\n\n using(ShimsContext.Create()){\n\n //Arrange\n System.Fakes.ShimDateTime.NowGet =\n () =>\n { return new DateTime(2010, 1, 1); };\n\n var myClass = new MyClass();\n\n //Act\n var timeString = myClass.WhatsTheTime();\n\n //Assert\n Assert.AreEqual(\"1/1/2010 12:00:00 AM\",timeString);\n\n }\n }\n}\n}\n</code></pre>\n"
},
{
"answer_id": 26994291,
"author": "tugberk",
"author_id": 463785,
"author_profile": "https://Stackoverflow.com/users/463785",
"pm_score": 2,
"selected": false,
"text": "<p>Simple answer: ditch System.DateTime :) Instead, use <a href=\"https://www.nuget.org/packages/NodaTime\" rel=\"nofollow\">NodaTime</a> and it's testing library: <a href=\"https://www.nuget.org/packages/NodaTime.Testing\" rel=\"nofollow\">NodaTime.Testing</a>.</p>\n\n<p>Further reading: </p>\n\n<ul>\n<li><a href=\"http://nodatime.org/unstable/userguide/testing.html\" rel=\"nofollow\">Unit testing with Noda Time</a></li>\n<li><a href=\"http://www.tugberkugurlu.com/archive/dependency-injection-inject-your-dependencies-period\" rel=\"nofollow\">Dependency Injection: Inject Your Dependencies, Period!</a></li>\n</ul>\n"
},
{
"answer_id": 51064402,
"author": "Pawel Wujczyk",
"author_id": 9107834,
"author_profile": "https://Stackoverflow.com/users/9107834",
"pm_score": 1,
"selected": false,
"text": "<p>I faced this situation so often, that I created simple nuget which exposes <strong>Now</strong> property through interface.</p>\n\n<pre><code>public interface IDateTimeTools\n{\n DateTime Now { get; }\n}\n</code></pre>\n\n<p>Implementation is of course very straightforward </p>\n\n<pre><code>public class DateTimeTools : IDateTimeTools\n{\n public DateTime Now => DateTime.Now;\n}\n</code></pre>\n\n<p>So after adding nuget to my project I can use it in the unit tests</p>\n\n<p><a href=\"https://i.stack.imgur.com/g8GrG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/g8GrG.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can install module right from the GUI Nuget Package Manager or by using the command:</p>\n\n<pre><code>Install-Package -Id DateTimePT -ProjectName Project\n</code></pre>\n\n<p>And the code for the Nuget is <a href=\"https://github.com/pwujczyk/DateTimePT\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>The example of usage with the Autofac can be found <a href=\"https://github.com/pwujczyk/CalculateEmailsPT\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404/"
] | I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value? | My preference is to have classes that use time actually rely on an interface, such as
```
interface IClock
{
DateTime Now { get; }
}
```
With a concrete implementation
```
class SystemClock: IClock
{
DateTime Now { get { return DateTime.Now; } }
}
```
Then if you want, you can provide any other kind of clock you want for testing, such as
```
class StaticClock: IClock
{
DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } }
}
```
There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a [Static Gateway Pattern](http://codebetter.com/blogs/jean-paul_boodhoo/archive/2007/10/15/the-static-gateway-pattern.aspx)).
Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that's just going to introduce pain on other levels.
Also, using `DateTime.Now` and including it in your calculations doesn't just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won't allow you to test those scenarios. Or at least not whenever you want. |
43,738 | <p>I have a line color property in my custom grid control. I want it to default to <code>Drawing.SystemColors.InactiveBorder</code>. I tried:</p>
<pre><code>[DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")]
public Color LineColor { get; set; }
</code></pre>
<p>But it doesn't seem to work. How do I do that with the default value attribute?</p>
| [
{
"answer_id": 43751,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": false,
"text": "<p>You need to change first argument from <code>SystemColors</code> to <code>Color</code>.<br>\nIt seems that there is no type converter for the <code>SystemColors</code> type, only for the <code>Color</code> type.</p>\n\n<pre><code>[DefaultValue(typeof(Color),\"InactiveBorder\")]\n</code></pre>\n"
},
{
"answer_id": 44073,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 2,
"selected": false,
"text": "<p>According to the link Matt posted, the DefaultValue attribute doesn't set the default value of the property, it just lets the form designer know that the property <em>has</em> a default value. If you change a property from the default value it is shown as bold in the properties window.</p>\n\n<p>You can't set a default value using automatic properties - you'll have to do it the old-fashioned way:</p>\n\n<pre><code>class MyClass\n{\n Color lineColor = SystemColors.InactiveBorder;\n\n [DefaultValue(true)]\n public Color LineColor {\n get {\n return lineColor;\n }\n\n set {\n lineColor = value;\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976/"
] | I have a line color property in my custom grid control. I want it to default to `Drawing.SystemColors.InactiveBorder`. I tried:
```
[DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")]
public Color LineColor { get; set; }
```
But it doesn't seem to work. How do I do that with the default value attribute? | You need to change first argument from `SystemColors` to `Color`.
It seems that there is no type converter for the `SystemColors` type, only for the `Color` type.
```
[DefaultValue(typeof(Color),"InactiveBorder")]
``` |
43,765 | <p>For my day job, I live in Emacs. Utterly. I also have become pretty dependent on CScope to help me find things in the code.</p>
<p>Normally, I have 2 windows in a split (C-x 3):
<a href="http://bitthicket.com/files/emacs-2split.JPG">alt text http://bitthicket.com/files/emacs-2split.JPG</a></p>
<p>And I use the right window for code buffers and the left window for the CScope search buffer. When you do a CScope search and select a result, it automatically updates the right-side window to show the buffer referred to by the result. This is all well and good, except that it causes me to lose my place in some other buffer that I was studying. Sometimes this is no biggie, because [C-s u] gets me back to where I was.</p>
<p>What would be better, though, is to have 3 split windows like this ([C-x 2] in the left window):
<a href="http://bitthicket.com/files/emacs-3split.jpg">alt text http://bitthicket.com/files/emacs-3split.jpg</a></p>
<p>And have the bottom left window contain the CScope search buffer, and the top left window be the only buffer that CScope ever updates. That way, I can see my CScope searches and navigate around the code without losing the buffer I'm focused on.</p>
<p>Anyone know how I can do that?</p>
| [
{
"answer_id": 44562,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I decided to not be a reputation-whore and find the answer myself. I looked in cscope.el as shown on the Emacs wiki, as well as the xcscope.el that comes with the cscope RPM package on RHEL.</p>\n\n<p>Neither appear to give a way to do what I'm wanting. The way is probably to edit the ELisp by adding a package variable like <code>*browse-buffer*</code> or something and just initialize that variable if not already initialized the first time the user does <code>[C-c C-s g]</code> or whatever, and always have the resulting code shown in <code>*browse-buffer*</code>. Then the user can put the <code>*browse-buffer*</code> wherever he wants it.</p>\n"
},
{
"answer_id": 65992,
"author": "Frank Klotz",
"author_id": 9668,
"author_profile": "https://Stackoverflow.com/users/9668",
"pm_score": 6,
"selected": true,
"text": "<p>Put this in your .emacs file:</p>\n\n<pre><code>;; Toggle window dedication\n\n(defun toggle-window-dedicated ()\n\n\"Toggle whether the current active window is dedicated or not\"\n\n(interactive)\n\n(message \n\n (if (let (window (get-buffer-window (current-buffer)))\n\n (set-window-dedicated-p window \n\n (not (window-dedicated-p window))))\n\n \"Window '%s' is dedicated\"\n\n \"Window '%s' is normal\")\n\n (current-buffer)))\n</code></pre>\n\n<p>Then bind it to some key - I use the Pause key:</p>\n\n<pre><code>(global-set-key [pause] 'toggle-window-dedicated)\n</code></pre>\n\n<p>And then use it to \"dedicate\" the window you want locked. then cscope can only open files from its result window in some OTHER window. Works a charm. I specifically use it for exactly this purpose - keeping one source file always on screen, while using cscope in a second buffer/window, and looking at cscope results in a third.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
] | For my day job, I live in Emacs. Utterly. I also have become pretty dependent on CScope to help me find things in the code.
Normally, I have 2 windows in a split (C-x 3):
[alt text http://bitthicket.com/files/emacs-2split.JPG](http://bitthicket.com/files/emacs-2split.JPG)
And I use the right window for code buffers and the left window for the CScope search buffer. When you do a CScope search and select a result, it automatically updates the right-side window to show the buffer referred to by the result. This is all well and good, except that it causes me to lose my place in some other buffer that I was studying. Sometimes this is no biggie, because [C-s u] gets me back to where I was.
What would be better, though, is to have 3 split windows like this ([C-x 2] in the left window):
[alt text http://bitthicket.com/files/emacs-3split.jpg](http://bitthicket.com/files/emacs-3split.jpg)
And have the bottom left window contain the CScope search buffer, and the top left window be the only buffer that CScope ever updates. That way, I can see my CScope searches and navigate around the code without losing the buffer I'm focused on.
Anyone know how I can do that? | Put this in your .emacs file:
```
;; Toggle window dedication
(defun toggle-window-dedicated ()
"Toggle whether the current active window is dedicated or not"
(interactive)
(message
(if (let (window (get-buffer-window (current-buffer)))
(set-window-dedicated-p window
(not (window-dedicated-p window))))
"Window '%s' is dedicated"
"Window '%s' is normal")
(current-buffer)))
```
Then bind it to some key - I use the Pause key:
```
(global-set-key [pause] 'toggle-window-dedicated)
```
And then use it to "dedicate" the window you want locked. then cscope can only open files from its result window in some OTHER window. Works a charm. I specifically use it for exactly this purpose - keeping one source file always on screen, while using cscope in a second buffer/window, and looking at cscope results in a third. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.