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
|
---|---|---|---|---|---|---|
26,098 | <p>I'm writing a C/C++ DLL and want to export certain functions which I've done before using a .def file like this</p>
<pre><code>LIBRARY "MyLib"
EXPORTS
Foo
Bar
</code></pre>
<p>with the code defined as this, for example:</p>
<pre><code>int Foo(int a);
void Bar(int foo);
</code></pre>
<p>However, what if I want to declare an overloaded method of Foo() like:</p>
<pre><code>int Foo(int a, int b);
</code></pre>
<p>As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary() ?</p>
<p>Edit: To be clear, this is on Windows using Visual Studio 2005</p>
<p>Edit: Marked the non-def (__declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files.</p>
| [
{
"answer_id": 26121,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 4,
"selected": true,
"text": "<p>In the code itself, mark the functions you want to export using __declspec(dllexport). For example:</p>\n\n<pre><code>#define DllExport __declspec(dllexport)\n\nint DllExport Foo( int a ) {\n // implementation\n}\nint DllExport Foo( int a, int b ) {\n // implementation\n}\n</code></pre>\n\n<p>If you do this, you do not need to list the functions in the .def file.</p>\n\n<p>Alternatively, you may be able to use a default parameter value, like:</p>\n\n<pre><code>int Foo( int a, int b = -1 )\n</code></pre>\n\n<p>This assumes that there exists a value for b that you can use to indicate that it is unused. If -1 is a legal value for b, or if there isn't or shouldn't be a default, this won't work.</p>\n\n<p>Edit (Adam Haile): Corrected to use __declspec as __dllspec was not correct so I could mark this as the official answer...it was close enough. </p>\n\n<p>Edit (Graeme): Oops - thanks for correcting my typo!</p>\n"
},
{
"answer_id": 26142,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 4,
"selected": false,
"text": "<p>Function overloading is a C++ feature that relies on name mangling (the cryptic function names in the linker error messages).</p>\n\n<p>By writing the mangled names into the def file, I can get my test project to link and run:</p>\n\n<pre><code>LIBRARY \"TestDLL\"\nEXPORTS\n ?Foo@@YAXH@Z\n ?Foo@@YAXHH@Z\n</code></pre>\n\n<p>seems to work for</p>\n\n<pre><code>void Foo( int x );\nvoid Foo( int x, int y );\n</code></pre>\n\n<p>So copy the C++ function names from the error message and write them into your def file. However, the real question is: Why do you want to use a def file and not go with __declspec(dllexport) ?</p>\n\n<p>The mangled names are non-portable, I tested with VC++ 2008.</p>\n"
},
{
"answer_id": 26299,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "<p>There isn't a language or version agnostic way of exporting an overloaded function since the mangling convention can change with each release of the compiler.</p>\n\n<p>This is one reason why most WinXX functions have funny names like *Ex or *2.</p>\n"
},
{
"answer_id": 29909,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 2,
"selected": false,
"text": "<p>There is no official way of doing what you want, because the dll interface is a C api.</p>\n\n<p>The compiler itself uses mangled names as a workaround, so you should use name mangling when you don't want to change too much in your code.</p>\n"
},
{
"answer_id": 342055,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar issue so I wanted to post on this as well.</p>\n\n<ol>\n<li><p>Usually using </p>\n\n<pre><code>extern \"C\" __declspec(dllexport) void Foo();\n</code></pre>\n\n<p>to export a function name is fine. \nIt will <em>usually</em> export the name\nunmangled without the need for a\n.def file. There are, however, some\nexceptions like __stdcall functions\nand overloaded function names.</p></li>\n<li><p>If you declare a function to use the\n__stdcall convention (as is done for many API functions) then</p>\n\n<pre><code>extern \"C\" __declspec(dllexport) void __stdcall Foo();\n</code></pre>\n\n<p>will export a mangled name like\n_Foo@4. In this case you may need to explicitly map the exported name\nto an internal mangled name.</p></li>\n</ol>\n\n<p>A. How to export an unmangled name. In a .def file add</p>\n\n<pre><code>----\nEXPORTS\n ; Explicit exports can go here\n\n Foo\n-----\n</code></pre>\n\n<p>This will try to find a \"best match\" for an internal function Foo and export it. In the case above where there is only\none foo this will create the mapping </p>\n\n<p>Foo = _Foo@4</p>\n\n<p>as can be see via dumpbin /EXPORTS</p>\n\n<p>If you have overloaded a function name then you may need to explicitly say which function you want in the .def file\nby specifying a mangled name using the entryname[=internalname] syntax. e.g.</p>\n\n<pre><code>----\nEXPORTS\n ; Explicit exports can go here\n\n Foo=_Foo@4\n-----\n</code></pre>\n\n<p>B. An alternative to .def files is that you can export names \"in place\" using a #pragma.</p>\n\n<pre><code>#pragma comment(linker, \"/export:Foo=_Foo@4\")\n</code></pre>\n\n<p>C. A third alternative is to declare just one version of Foo as extern \"C\" to be exported unmangled. See <a href=\"http://blogs.msdn.com/shamit/archive/2005/02/11/371421.aspx\" rel=\"noreferrer\">here</a> for details.</p>\n"
},
{
"answer_id": 15540686,
"author": "null",
"author_id": 1999454,
"author_profile": "https://Stackoverflow.com/users/1999454",
"pm_score": 2,
"selected": false,
"text": "<p>Systax for EXPORTS definition is:</p>\n\n<pre><code>entryname[=internalname] [@ordinal [NONAME]] [PRIVATE] [DATA]\n</code></pre>\n\n<p><strong>entryname</strong> is the function or variable name that you want to export. This is required. If the name you export is different from the name in the DLL, specify the export's name in the DLL with internalname.</p>\n\n<p>For example, if your DLL exports a function, func1() and you want it to be used as func2(), you would specify:</p>\n\n<pre><code>EXPORTS\nfunc2=func1\n</code></pre>\n\n<p>Just see the mangled names (using Dependency walker) and specify your own functions name.</p>\n\n<p>Source: <a href=\"http://msdn.microsoft.com/en-us/library/hyx1zcd3(v=vs.71).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/hyx1zcd3(v=vs.71).aspx</a></p>\n\n<p>Edit: This works for dynamic DLLs, where we need to use GetProcAddress() to explicitly fetch a functions in Dll.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | I'm writing a C/C++ DLL and want to export certain functions which I've done before using a .def file like this
```
LIBRARY "MyLib"
EXPORTS
Foo
Bar
```
with the code defined as this, for example:
```
int Foo(int a);
void Bar(int foo);
```
However, what if I want to declare an overloaded method of Foo() like:
```
int Foo(int a, int b);
```
As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary() ?
Edit: To be clear, this is on Windows using Visual Studio 2005
Edit: Marked the non-def (\_\_declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files. | In the code itself, mark the functions you want to export using \_\_declspec(dllexport). For example:
```
#define DllExport __declspec(dllexport)
int DllExport Foo( int a ) {
// implementation
}
int DllExport Foo( int a, int b ) {
// implementation
}
```
If you do this, you do not need to list the functions in the .def file.
Alternatively, you may be able to use a default parameter value, like:
```
int Foo( int a, int b = -1 )
```
This assumes that there exists a value for b that you can use to indicate that it is unused. If -1 is a legal value for b, or if there isn't or shouldn't be a default, this won't work.
Edit (Adam Haile): Corrected to use \_\_declspec as \_\_dllspec was not correct so I could mark this as the official answer...it was close enough.
Edit (Graeme): Oops - thanks for correcting my typo! |
26,123 | <p>I want to use Powershell to write some utilities, leveraging our own .NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this?</p>
| [
{
"answer_id": 26135,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 5,
"selected": true,
"text": "<p>If you want to load an assembly into your PowerShell session, you can use reflection and load the assembly.</p>\n\n<pre><code>[void][System.Reflection.Assembly]::LoadFrom(PathToYourAssembly)\n</code></pre>\n\n<p>After you load your assembly, you can call static methods and create new instances of a class. </p>\n\n<p>A good tutorial can be found <a href=\"http://stevenmurawski.com/powershell/2009/03/exploring-the-net-framework-with-powershell-constructors-part-3/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Both books mentioned by EBGreen are excellent. The PowerShell Cookbook is very task oriented and PowerShell in Action is a great description of the language, its focus and useability. PowerShell in Action is one of my favorite books. :)</p>\n"
},
{
"answer_id": 26157,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 2,
"selected": false,
"text": "<p>The link that Steven posted is a good example. I don't know of any extensive tutorial. Both the <a href=\"http://oreilly.com/catalog/9780596528492/\" rel=\"nofollow noreferrer\" title=\"Windows Powershell Cookbook\">Windows Powershell Cookbook</a> and <a href=\"http://www.manning.com/payette/\" rel=\"nofollow noreferrer\" title=\"Windows Powershell In Action\">Windows Powershell In Action</a> have good chapters on the subject. Also, look at the ::LoadFromFile method of the System.Reflection.Assembly class in case your in-house assemblies are not loaded in the GAC.</p>\n"
},
{
"answer_id": 40611548,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>you can use <code>[]</code> or use <code>add-type -AssemblyName \"System.example\"</code> to use assembly for example use :</p>\n\n<pre><code>[system.drawing]::class ...\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1535/"
] | I want to use Powershell to write some utilities, leveraging our own .NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this? | If you want to load an assembly into your PowerShell session, you can use reflection and load the assembly.
```
[void][System.Reflection.Assembly]::LoadFrom(PathToYourAssembly)
```
After you load your assembly, you can call static methods and create new instances of a class.
A good tutorial can be found [here](http://stevenmurawski.com/powershell/2009/03/exploring-the-net-framework-with-powershell-constructors-part-3/).
Both books mentioned by EBGreen are excellent. The PowerShell Cookbook is very task oriented and PowerShell in Action is a great description of the language, its focus and useability. PowerShell in Action is one of my favorite books. :) |
26,137 | <p>I have a couple of questions regarding VBScript and ASP Classic:</p>
<ol>
<li><p>What is the preferred way to access an MS SQL Server database in VBScript/ASP?</p></li>
<li><p>What are best practices in regards to separating model from view from controller?</p></li>
<li><p>Any other things I should know about either VBScript or ASP?</p></li>
</ol>
<p>If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.</p>
| [
{
"answer_id": 26181,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 5,
"selected": true,
"text": "<p>ADO is an excellent way to access a database in VBScript/Classic ASP.</p>\n\n<pre><code>Dim db: Set db = Server.CreateObject(\"ADODB.Connection\")\ndb.Open \"yourconnectionstring -> see connectionstrings.com\"\nDim rs: Set rs = db.Execute(\"SELECT firstName from Employees\")\nWhile Not rs.EOF\n Response.Write rs(\"firstName\")\n rs.MoveNext\nWend\nrs.Close\n</code></pre>\n\n<p>More info here: <a href=\"http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/\" rel=\"noreferrer\">http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/</a></p>\n\n<p>One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems.\n(Reference: <a href=\"http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html\" rel=\"noreferrer\">http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html</a> )</p>\n"
},
{
"answer_id": 26315,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 2,
"selected": false,
"text": "<p>On number 2, I think you have a few options...</p>\n\n<p>1) You can use COM components developed in VB6 or the like to separate some of your business logic from your UI.</p>\n\n<p>2) You can create classes in VBScript. There is no concept of inheritance and other more advanced features are missing from the implementation, but you can encapsulate logic in classes that helps reduce the spagehtti-ness of your app. Check out this: <a href=\"https://web.archive.org/web/20210505200200/http://www.4guysfromrolla.com/webtech/092399-1.shtml\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20210505200200/http://www.4guysfromrolla.com/webtech/092399-1.shtml</a></p>\n"
},
{
"answer_id": 26336,
"author": "Ryan Rinaldi",
"author_id": 2278,
"author_profile": "https://Stackoverflow.com/users/2278",
"pm_score": 2,
"selected": false,
"text": "<p>Echoing some ideas and adding a few of my own: </p>\n\n<p>1) Best way to access the database would to abstract that away into a COM component of some sort that you access from VBScript.</p>\n\n<p>2) If you really wanted to you could write the controller in VBScript and then access that in the page. It would resemble a Page Controller pattern and not a Front Controller that you would see in ASP.NET MVC or MonoRail</p>\n\n<p>3) Why are you doing this to yourself? Most of the tooling required to do this kind of work isn't even available anymore.</p>\n"
},
{
"answer_id": 26699,
"author": "George Godik",
"author_id": 2759,
"author_profile": "https://Stackoverflow.com/users/2759",
"pm_score": 1,
"selected": false,
"text": "<p>way way back in the day when VBScript/ASP were still ok\nI worked in a utility company with a very mixed DB envrionment, I used to swear by this website: <a href=\"http://www.connectionstrings.com/\" rel=\"nofollow noreferrer\">http://www.connectionstrings.com/</a></p>\n\n<p>@michealpryor got it right</p>\n"
},
{
"answer_id": 60335,
"author": "Scott",
"author_id": 6126,
"author_profile": "https://Stackoverflow.com/users/6126",
"pm_score": 1,
"selected": false,
"text": "<p>I've been stuck building on ASP, and I feel your pain.</p>\n\n<p>1) The best way to query against SQL Server is with parameterized queries; this will help prevent against SQL injection attacks.</p>\n\n<p>Tutorial (not my blog):<br>\n<a href=\"http://www.nomadpete.com/2007/03/23/classic-asp-which-is-still-alive-and-parametised-queries/\" rel=\"nofollow noreferrer\"><a href=\"http://www.nomadpete.com/2007/03/23/classic-asp-which-is-still-alive-and-parametised-queries/\" rel=\"nofollow noreferrer\">http://www.nomadpete.com/2007/03/23/classic-asp-which-is-still-alive-and-parametised-queries/</a></a></p>\n\n<p>2) I haven't seen anything regarding MVC specifically geared towards ASP, but I'm definitely interested because it's something I'm having a tough time wrapping my head around. I generally try to at least contain things which are view-like and things which are controller-like in separate functions. I suppose you could possibly write code in separate files and then use server side includes to join them all back together.</p>\n\n<p>3) You're probably coming from a language which has more functionality built in. At first, some things may appear to be missing, but it's often just a matter of writing a lot more lines of code than you're used to.</p>\n"
},
{
"answer_id": 91504,
"author": "jammus",
"author_id": 984,
"author_profile": "https://Stackoverflow.com/users/984",
"pm_score": 3,
"selected": false,
"text": "<p>Remember to <em>program into</em> the language rather than program in it. Just because you're using a limited tool set doesn't mean you have to program like it's 1999.</p>\n\n<p>I agree with JasonS about classes. It's true you can't do things like inheritance but you can easily fake it</p>\n\n<pre><code>Class Dog\n Private Parent\n\n Private Sub Class_Initialize()\n Set Parent = New Animal\n End Sub\n\n Public Function Walk()\n Walk = Parent.Walk\n End Function\n\n Public Function Bark()\n Response.Write(\"Woof! Woof!\")\n End Function\nEnd Class\n</code></pre>\n\n<p>In my projects an ASP page will have the following:\nINC-APP-CommonIncludes.asp - This includes stuff like my general libraries (Database Access, file functions, etc) and sets up security and includes any configuration files (like connection strings, directory locations, etc) and common classes (User, Permission, etc) and is included in every page.</p>\n\n<p>Modules/ModuleName/page.vb.asp - Kind of like a code behind page. Includes page specific BO, BLL and DAL classes and sets up the data required for the page/receives submitted form data, etc</p>\n\n<p>Modules/ModuleName/Display/INC-DIS-Page.asp - Displays the data set up in page.vb.asp.</p>\n"
},
{
"answer_id": 91513,
"author": "jammus",
"author_id": 984,
"author_profile": "https://Stackoverflow.com/users/984",
"pm_score": 1,
"selected": false,
"text": "<p>Also for database access I have a set of functions - GetSingleRecord, GetRecordset and UpdateDatabase which has similar function to what Michael mentions above</p>\n"
},
{
"answer_id": 92146,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 4,
"selected": false,
"text": "<p>I had to walk away from my PC when I saw the first answer, and am still distressed that it has been approved by so many people. It's an appalling example of the very worst kind of ASP code, the kind that would ensure your site is SQL-injectable and, if you continue using this code across the site, hackable within an inch of its life.</p>\n\n<p>This is NOT the kind of code you should be giving to someone new to ASP coding as they will think it is the professional way of coding in the language!</p>\n\n<ol>\n<li><p>NEVER reveal a connection string in your code as it contains the username and password to your database. Use a UDL file instead, or at the very least a constant that can be declared elsewhere and used across the site.</p></li>\n<li><p>There is no longer any good excuse for using inline SQL for any operation in a web environment. Use a stored procedure -- the security benefits cannot be stressed enough. If you really can't do that then look at inline parameters as a second-best option... Inline SQL will leave your site wide open to SQL injection, malware injection and the rest. </p></li>\n<li><p>Late declaration of variables can lead to sloppy coding. Use \"option explicit\" and declare variables at the top of the function. This is best practice rather than a real WTF, but it's best to start as you mean to go on.</p></li>\n<li><p>No hints to the database as to what type of connection this is -- is it for reading only, or will the user be updating records? The connection can be optimised and the database can handle locking very efficiently if effectively told what to expect.</p></li>\n<li><p>The database connection is not closed after use, and the recordset object isn't fully destroyed.</p></li>\n</ol>\n\n<p>ASP is still a strong language, despite many folks suggesting moving to .NET -- with good coding practices an ASP site can be written that is easy to maintain, scaleable and fast, but you HAVE to make sure you use every method available to make your code efficient, you HAVE to maintain good coding practices and a little forethought. A good editor will help too, my preference being for PrimalScript which I find more helpful to an ASP coder than any of the latest MS products which seem to be very .NET-centric.</p>\n\n<p>Also, where is a \"MEMO\" field from? Is this Access nomenclature, or maybe MySQL? I ask as such fields have been called TEXT or NTEXT fields in MS-SQL for a decade.</p>\n"
},
{
"answer_id": 185205,
"author": "jwalkerjr",
"author_id": 689,
"author_profile": "https://Stackoverflow.com/users/689",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with @Cirieno, that the selected answer would not be wise to use in production code, for all of the reasons he mentions. That said, if you have just a little experience, this answer is a good starting point as to the basics.</p>\n\n<p>In my ASP experience, I preferred to write my database access layer using VB, compiling down to a DLL and referencing the DLL via VBScript. Tough to debug directly through ASP, but it was a nice way to encapsulate all data access code away from the ASP code.</p>\n"
},
{
"answer_id": 1103513,
"author": "My Alter Ego",
"author_id": 93868,
"author_profile": "https://Stackoverflow.com/users/93868",
"pm_score": 2,
"selected": false,
"text": "<p>AXE - Asp Xtreme Evolution is a MVC framework for ASP classic</p>\n\n<p>There are some attempts at making test frameworks for asp:\naspUnit is good, but no longer maintained.</p>\n\n<p>I saw a sample on how to make your own one a few months back.\nThe example used nUnit to call functions against the website for automatic testing.\nI think i got it off <a href=\"http://www.beingnew.net/2008/11/automating-classic-asp-unit-tests-with.html\" rel=\"nofollow noreferrer\">here</a> (my line is borked so I can't check)</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | I have a couple of questions regarding VBScript and ASP Classic:
1. What is the preferred way to access an MS SQL Server database in VBScript/ASP?
2. What are best practices in regards to separating model from view from controller?
3. Any other things I should know about either VBScript or ASP?
If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here. | ADO is an excellent way to access a database in VBScript/Classic ASP.
```
Dim db: Set db = Server.CreateObject("ADODB.Connection")
db.Open "yourconnectionstring -> see connectionstrings.com"
Dim rs: Set rs = db.Execute("SELECT firstName from Employees")
While Not rs.EOF
Response.Write rs("firstName")
rs.MoveNext
Wend
rs.Close
```
More info here: <http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/>
One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems.
(Reference: <http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html> ) |
26,145 | <p>I'm making a simple extra java app launcher for Eclipse 3.2 (JBuilder 2007-8) for internal use.</p>
<p>So I looked up all the documentations related, including this one <a href="http://www.eclipse.org/articles/Article-Launch-Framework/launch.html" rel="nofollow noreferrer" title="The Launching Framework">The Launching Framework from eclipse.org</a> and have managed to make everything else working with the exception of the launch shortcut. </p>
<p><img src="https://i.stack.imgur.com/8I8zw.jpg" alt="alt text"></p>
<p>This is the part of my plugin.xml. </p>
<pre><code> <extension
point="org.eclipse.debug.ui.launchShortcuts">
<shortcut
category="mycompany.javalaunchext.launchConfig"
class="mycompany.javalaunchext.LaunchShortcut"
description="launchshortcutsdescription"
icon="icons/k2mountain.png"
id="mycompany.javalaunchext.launchShortcut"
label="Java Application Ext."
modes="run, debug">
<perspective
id="org.eclipse.jdt.ui.JavaPerspective">
</perspective>
<perspective
id="org.eclipse.jdt.ui.JavaHierarchyPerspective">
</perspective>
<perspective
id="org.eclipse.jdt.ui.JavaBrowsingPerspective">
</perspective>
<perspective
id="org.eclipse.debug.ui.DebugPerspective">
</perspective>
</shortcut>
</code></pre>
<p></p>
<p>The configuration name in the category section is correct and the class in the class section, i believe, is correctly implemented. (basically copied from org.eclipse.jdt.debug.ui.launchConfigurations.JavaApplicationLaunchShortcut)</p>
<hr>
<p>I'm really not sure if I'm supposed to write a follow-up here but let me clarify my question more.
I've extended org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut.
Plus, I've added my own logger to constructors and methods, but the class seems like it's never even instantiating.</p>
| [
{
"answer_id": 26341,
"author": "zvikico",
"author_id": 2823,
"author_profile": "https://Stackoverflow.com/users/2823",
"pm_score": 0,
"selected": false,
"text": "<p>You class should implement ILaunchShortcut.\nCheck out the <a href=\"http://help.eclipse.org/help32/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/debug/ui/ILaunchShortcut.html\" rel=\"nofollow noreferrer\">Javadoc</a>. </p>\n\n<p>What exception are you getting? Check the error log.</p>\n"
},
{
"answer_id": 40209,
"author": "wbkang",
"author_id": 2710,
"author_profile": "https://Stackoverflow.com/users/2710",
"pm_score": 3,
"selected": true,
"text": "<p>I had to add <code>contextualLaunch</code> under <code>org.eclipse.debug.ui.launchShortcuts</code>.</p>\n\n<p>The old way seems like it's deprecated a long ago.</p>\n\n<p>For other people who are working on the same subject,\nyou might want to extend <code>org.eclipse.ui.commands</code> and bindings, too.</p>\n\n<p>I cannot choose this answer but this is the answer that I (the questioner) was looking for.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2710/"
] | I'm making a simple extra java app launcher for Eclipse 3.2 (JBuilder 2007-8) for internal use.
So I looked up all the documentations related, including this one [The Launching Framework from eclipse.org](http://www.eclipse.org/articles/Article-Launch-Framework/launch.html "The Launching Framework") and have managed to make everything else working with the exception of the launch shortcut.

This is the part of my plugin.xml.
```
<extension
point="org.eclipse.debug.ui.launchShortcuts">
<shortcut
category="mycompany.javalaunchext.launchConfig"
class="mycompany.javalaunchext.LaunchShortcut"
description="launchshortcutsdescription"
icon="icons/k2mountain.png"
id="mycompany.javalaunchext.launchShortcut"
label="Java Application Ext."
modes="run, debug">
<perspective
id="org.eclipse.jdt.ui.JavaPerspective">
</perspective>
<perspective
id="org.eclipse.jdt.ui.JavaHierarchyPerspective">
</perspective>
<perspective
id="org.eclipse.jdt.ui.JavaBrowsingPerspective">
</perspective>
<perspective
id="org.eclipse.debug.ui.DebugPerspective">
</perspective>
</shortcut>
```
The configuration name in the category section is correct and the class in the class section, i believe, is correctly implemented. (basically copied from org.eclipse.jdt.debug.ui.launchConfigurations.JavaApplicationLaunchShortcut)
---
I'm really not sure if I'm supposed to write a follow-up here but let me clarify my question more.
I've extended org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut.
Plus, I've added my own logger to constructors and methods, but the class seems like it's never even instantiating. | I had to add `contextualLaunch` under `org.eclipse.debug.ui.launchShortcuts`.
The old way seems like it's deprecated a long ago.
For other people who are working on the same subject,
you might want to extend `org.eclipse.ui.commands` and bindings, too.
I cannot choose this answer but this is the answer that I (the questioner) was looking for. |
26,151 | <p>C++ 0x has template aliases (sometimes referred to as template typedefs). See <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates" rel="noreferrer">here</a>. Current spec of C++ does not. </p>
<p>What do you like to use as work around ? Container objects or Macros ?
Do you feel its worth it ?</p>
| [
{
"answer_id": 26162,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": true,
"text": "<blockquote>\n <p>What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?</p>\n</blockquote>\n\n<p>The canonical way is to use a metafunction like thus:</p>\n\n<pre><code>template <typename T>\nstruct my_string_map {\n typedef std::map<std::string, T> type;\n};\n\n// Invoke:\n\nmy_string_map<int>::type my_str_int_map;\n</code></pre>\n\n<p>This is also used in the STL (<code>allocator::rebind<U></code>) and in many libraries including Boost. We use it extensively in a <a href=\"http://www.seqan.de/dddoc/html/index.html\" rel=\"noreferrer\">bioinformatical library</a>.</p>\n\n<p>It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.</p>\n\n<p>(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)</p>\n"
},
{
"answer_id": 2089853,
"author": "xghost",
"author_id": 253585,
"author_profile": "https://Stackoverflow.com/users/253585",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n<pre><code>template <typename T>\nstruct my_string_map : public std::map<std::string,T> \n{\n};\n</code></pre>\n</blockquote>\n\n<p>You shouldn't inherit from classes that do not have a virtual destructor. It's related to destructors in derived classes not being called when they should be and you could end up with unallocated memory.</p>\n\n<p>That being said you could *****probably***** get away with it in the instance above because you're not adding any more data to your derived type. Note that this is not an endorsement. I still advice you <strong>don't</strong> do it. The fact that you <em>can</em> do it doesn't mean you <em>should</em>.</p>\n\n<p>EDIT: Yes, this is a reply to ShaChris23's post. I probably missed something because it showed up above his/her message instead of below.</p>\n"
},
{
"answer_id": 15489480,
"author": "Andrei Pokrovsky",
"author_id": 231742,
"author_profile": "https://Stackoverflow.com/users/231742",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes you can just explicitly write out the untemplated typedefs for all the necessary types. If the base class is templated on multiple template args with only one type desired to be typedefed you can inherit a specialized class with typedef effectively included in the inherited class name. This approach is less abstruse than the metafunction approach.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759/"
] | C++ 0x has template aliases (sometimes referred to as template typedefs). See [here](http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates). Current spec of C++ does not.
What do you like to use as work around ? Container objects or Macros ?
Do you feel its worth it ? | >
> What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?
>
>
>
The canonical way is to use a metafunction like thus:
```
template <typename T>
struct my_string_map {
typedef std::map<std::string, T> type;
};
// Invoke:
my_string_map<int>::type my_str_int_map;
```
This is also used in the STL (`allocator::rebind<U>`) and in many libraries including Boost. We use it extensively in a [bioinformatical library](http://www.seqan.de/dddoc/html/index.html).
It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.
(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.) |
26,196 | <p>I am looking for a very fast way to filter down a collection in C#. I am currently using generic <code>List<object></code> collections, but am open to using other structures if they perform better.</p>
<p>Currently, I am just creating a new <code>List<object></code> and looping thru the original list. If the filtering criteria matches, I put a copy into the new list.</p>
<p>Is there a better way to do this? Is there a way to filter in place so there is no temporary list required?</p>
| [
{
"answer_id": 26203,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 9,
"selected": true,
"text": "<p>If you're using C# 3.0 you can use linq, which is way better and way more elegant:</p>\n<pre class=\"lang-c# prettyprint-override\"><code>List<int> myList = GetListOfIntsFromSomewhere();\n\n// This will filter ints that are not > 7 out of the list; Where returns an\n// IEnumerable<T>, so call ToList to convert back to a List<T>.\nList<int> filteredList = myList.Where(x => x > 7).ToList();\n</code></pre>\n<p>If you can't find the <code>.Where</code>, that means you need to import <code>using System.Linq;</code> at the top of your file.</p>\n"
},
{
"answer_id": 26206,
"author": "Mykroft",
"author_id": 2191,
"author_profile": "https://Stackoverflow.com/users/2191",
"pm_score": 4,
"selected": false,
"text": "<p><code>List<T></code> has a <code>FindAll</code> method that will do the filtering for you and return a subset of the list. </p>\n\n<p>MSDN has a great code example here: <a href=\"http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx</a></p>\n\n<p>EDIT: I wrote this before I had a good understanding of LINQ and the <code>Where()</code> method. If I were to write this today i would probably use the method Jorge mentions above. The <code>FindAll</code> method still works if you're stuck in a .NET 2.0 environment though.</p>\n"
},
{
"answer_id": 26209,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>To do it in place, you can use the RemoveAll method of the \"List<>\" class along with a custom \"Predicate\" class...but all that does is clean up the code... under the hood it's doing the same thing you are...but yes, it does it in place, so you do same the temp list.</p>\n"
},
{
"answer_id": 26210,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 3,
"selected": false,
"text": "<p>You can use IEnumerable to eliminate the need of a temp list.</p>\n\n<pre><code>public IEnumerable<T> GetFilteredItems(IEnumerable<T> collection)\n{\n foreach (T item in collection)\n if (Matches<T>(item))\n {\n yield return item;\n }\n}\n</code></pre>\n\n<p>where Matches is the name of your filter method. And you can use this like:</p>\n\n<pre><code>IEnumerable<MyType> filteredItems = GetFilteredItems(myList);\nforeach (MyType item in filteredItems)\n{\n // do sth with your filtered items\n}\n</code></pre>\n\n<p>This will call GetFilteredItems function when needed and in some cases that you do not use all items in the filtered collection, it may provide some good performance gain.</p>\n"
},
{
"answer_id": 26211,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/fh1w7y8z.aspx\" rel=\"nofollow noreferrer\">FindAll</a> method of the List, providing a delegate to filter on. Though, I agree with @<a href=\"https://stackoverflow.com/questions/26196/filtering-collections-in-c#26201\">IainMH</a> that it's not worth worrying yourself too much unless it's a huge list.</p>\n"
},
{
"answer_id": 26232,
"author": "Tom Lokhorst",
"author_id": 2597,
"author_profile": "https://Stackoverflow.com/users/2597",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p>If you're using C# 3.0 you can use linq</p>\n </blockquote>\n</blockquote>\n\n<p>Or, if you prefer, use the special query syntax provided by the C# 3 compiler:</p>\n\n<pre><code>var filteredList = from x in myList\n where x > 7\n select x;\n</code></pre>\n"
},
{
"answer_id": 26273,
"author": "Jon Erickson",
"author_id": 1950,
"author_profile": "https://Stackoverflow.com/users/1950",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a code block / example of some list filtering using three different methods that I put together to show Lambdas and LINQ based list filtering.</p>\n\n<pre><code>#region List Filtering\n\nstatic void Main(string[] args)\n{\n ListFiltering();\n Console.ReadLine();\n}\n\nprivate static void ListFiltering()\n{\n var PersonList = new List<Person>();\n\n PersonList.Add(new Person() { Age = 23, Name = \"Jon\", Gender = \"M\" }); //Non-Constructor Object Property Initialization\n PersonList.Add(new Person() { Age = 24, Name = \"Jack\", Gender = \"M\" });\n PersonList.Add(new Person() { Age = 29, Name = \"Billy\", Gender = \"M\" });\n\n PersonList.Add(new Person() { Age = 33, Name = \"Bob\", Gender = \"M\" });\n PersonList.Add(new Person() { Age = 45, Name = \"Frank\", Gender = \"M\" });\n\n PersonList.Add(new Person() { Age = 24, Name = \"Anna\", Gender = \"F\" });\n PersonList.Add(new Person() { Age = 29, Name = \"Sue\", Gender = \"F\" });\n PersonList.Add(new Person() { Age = 35, Name = \"Sally\", Gender = \"F\" });\n PersonList.Add(new Person() { Age = 36, Name = \"Jane\", Gender = \"F\" });\n PersonList.Add(new Person() { Age = 42, Name = \"Jill\", Gender = \"F\" });\n\n //Logic: Show me all males that are less than 30 years old.\n\n Console.WriteLine(\"\");\n //Iterative Method\n Console.WriteLine(\"List Filter Normal Way:\");\n foreach (var p in PersonList)\n if (p.Gender == \"M\" && p.Age < 30)\n Console.WriteLine(p.Name + \" is \" + p.Age);\n\n Console.WriteLine(\"\");\n //Lambda Filter Method\n Console.WriteLine(\"List Filter Lambda Way\");\n foreach (var p in PersonList.Where(p => (p.Gender == \"M\" && p.Age < 30))) //.Where is an extension method\n Console.WriteLine(p.Name + \" is \" + p.Age);\n\n Console.WriteLine(\"\");\n //LINQ Query Method\n Console.WriteLine(\"List Filter LINQ Way:\");\n foreach (var v in from p in PersonList\n where p.Gender == \"M\" && p.Age < 30\n select new { p.Name, p.Age })\n Console.WriteLine(v.Name + \" is \" + v.Age);\n}\n\nprivate class Person\n{\n public Person() { }\n public int Age { get; set; }\n public string Name { get; set; }\n public string Gender { get; set; }\n}\n\n#endregion\n</code></pre>\n"
},
{
"answer_id": 3916043,
"author": "gouldos",
"author_id": 449696,
"author_profile": "https://Stackoverflow.com/users/449696",
"pm_score": 2,
"selected": false,
"text": "<p>Using LINQ is relatively much slower than using a predicate supplied to the Lists <code>FindAll</code> method. Also be careful with LINQ as the enumeration of the <code>list</code> is not actually executed until you access the result. This can mean that, when you think you have created a filtered list, the content may differ to what you expected when you actually read it.</p>\n"
},
{
"answer_id": 38121663,
"author": "Daniel Roberts",
"author_id": 3466633,
"author_profile": "https://Stackoverflow.com/users/3466633",
"pm_score": 1,
"selected": false,
"text": "<p>If your list is very big and you are filtering repeatedly - you can sort the original list on the filter attribute, binary search to find the start and end points.</p>\n\n<p>Initial time O(n*log(n)) then O(log(n)).</p>\n\n<p>Standard filtering will take O(n) each time.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] | I am looking for a very fast way to filter down a collection in C#. I am currently using generic `List<object>` collections, but am open to using other structures if they perform better.
Currently, I am just creating a new `List<object>` and looping thru the original list. If the filtering criteria matches, I put a copy into the new list.
Is there a better way to do this? Is there a way to filter in place so there is no temporary list required? | If you're using C# 3.0 you can use linq, which is way better and way more elegant:
```c#
List<int> myList = GetListOfIntsFromSomewhere();
// This will filter ints that are not > 7 out of the list; Where returns an
// IEnumerable<T>, so call ToList to convert back to a List<T>.
List<int> filteredList = myList.Where(x => x > 7).ToList();
```
If you can't find the `.Where`, that means you need to import `using System.Linq;` at the top of your file. |
26,233 | <p>Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.</p>
| [
{
"answer_id": 26237,
"author": "Chris",
"author_id": 2134,
"author_profile": "https://Stackoverflow.com/users/2134",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient%28VS.80%29.aspx\" rel=\"noreferrer\">System.Net.WebClient</a></p>\n\n<p>From MSDN:</p>\n\n<pre><code>using System;\nusing System.Net;\nusing System.IO;\n\npublic class Test\n{\n public static void Main (string[] args)\n {\n if (args == null || args.Length == 0)\n {\n throw new ApplicationException (\"Specify the URI of the resource to retrieve.\");\n }\n WebClient client = new WebClient ();\n\n // Add a user agent header in case the \n // requested URI contains a query.\n\n client.Headers.Add (\"user-agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)\");\n\n Stream data = client.OpenRead (args[0]);\n StreamReader reader = new StreamReader (data);\n string s = reader.ReadToEnd ();\n Console.WriteLine (s);\n data.Close ();\n reader.Close ();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 26238,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 7,
"selected": true,
"text": "<pre><code>public static void DownloadFile(string remoteFilename, string localFilename)\n{\n WebClient client = new WebClient();\n client.DownloadFile(remoteFilename, localFilename);\n}\n</code></pre>\n"
},
{
"answer_id": 26242,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 5,
"selected": false,
"text": "<p>Use the WebClient class from System.Net; on .NET 2.0 and higher.</p>\n\n<pre><code>WebClient Client = new WebClient ();\nClient.DownloadFile(\"http://mysite.com/myfile.txt\", \" C:\\myfile.txt\");\n</code></pre>\n"
},
{
"answer_id": 25605187,
"author": "EKanadily",
"author_id": 365867,
"author_profile": "https://Stackoverflow.com/users/365867",
"pm_score": 3,
"selected": false,
"text": "<p>here is my answer ,a method that takes a URL and return a string</p>\n\n<pre><code>public static string downloadWebPage(string theURL)\n {\n //### download a web page to a string\n WebClient client = new WebClient();\n\n client.Headers.Add(\"user-agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)\");\n\n Stream data = client.OpenRead(theURL);\n StreamReader reader = new StreamReader(data);\n string s = reader.ReadToEnd();\n return s;\n }\n</code></pre>\n"
},
{
"answer_id": 27552526,
"author": "liang",
"author_id": 802589,
"author_profile": "https://Stackoverflow.com/users/802589",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/fhd1f0sw%28v=vs.110%29.aspx\" rel=\"noreferrer\">WebClient.DownloadString</a></p>\n\n<pre><code>public static void DownloadString (string address)\n{\n WebClient client = new WebClient ();\n string reply = client.DownloadString (address);\n\n Console.WriteLine (reply);\n}\n</code></pre>\n"
},
{
"answer_id": 54502464,
"author": "Amir Astaneh",
"author_id": 577543,
"author_profile": "https://Stackoverflow.com/users/577543",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is the fastest (download speed time with low latency) solution for download.</p>\n\n<pre><code>// WebClient vs HttpClient vs HttpWebRequest vs RestSharp\n// در نهایت به نظرم روش زیر سریعترین روشه\nHttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);\nRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;\nRequest.Proxy = null;\nRequest.Method = \"GET\";\nusing (WebResponse Response = Request.GetResponse())\n{\n using (StreamReader Reader = new StreamReader(Response.GetResponseStream()))\n {\n return Reader.ReadToEnd();\n }\n}\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
] | Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS. | ```
public static void DownloadFile(string remoteFilename, string localFilename)
{
WebClient client = new WebClient();
client.DownloadFile(remoteFilename, localFilename);
}
``` |
26,305 | <p>I want to be able to play sound files in my program. Where should I look?</p>
| [
{
"answer_id": 26311,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 4,
"selected": false,
"text": "<p>A bad example:</p>\n\n<pre><code>import sun.audio.*; //import the sun.audio package\nimport java.io.*;\n\n//** add this into your application code as appropriate\n// Open an input stream to the audio file.\nInputStream in = new FileInputStream(Filename);\n\n// Create an AudioStream object from the input stream.\nAudioStream as = new AudioStream(in); \n\n// Use the static class member \"player\" from class AudioPlayer to play\n// clip.\nAudioPlayer.player.start(as); \n\n// Similarly, to stop the audio.\nAudioPlayer.player.stop(as); \n</code></pre>\n"
},
{
"answer_id": 26318,
"author": "pek",
"author_id": 2644,
"author_profile": "https://Stackoverflow.com/users/2644",
"pm_score": 8,
"selected": true,
"text": "<p>I wrote the following code that works fine. But I think it only works with <code>.wav</code> format.</p>\n\n<pre><code>public static synchronized void playSound(final String url) {\n new Thread(new Runnable() {\n // The wrapper thread is unnecessary, unless it blocks on the\n // Clip finishing; see comments.\n public void run() {\n try {\n Clip clip = AudioSystem.getClip();\n AudioInputStream inputStream = AudioSystem.getAudioInputStream(\n Main.class.getResourceAsStream(\"/path/to/sounds/\" + url));\n clip.open(inputStream);\n clip.start(); \n } catch (Exception e) {\n System.err.println(e.getMessage());\n }\n }\n }).start();\n}\n</code></pre>\n"
},
{
"answer_id": 2084262,
"author": "Stephen Ware",
"author_id": 252964,
"author_profile": "https://Stackoverflow.com/users/252964",
"pm_score": 2,
"selected": false,
"text": "<p>There is an alternative to importing the sound files which works in both applets and applications: convert the audio files into .java files and simply use them in your code.</p>\n\n<p>I have developed a tool which makes this process a lot easier. It simplifies the Java Sound API quite a bit.</p>\n\n<p><a href=\"http://stephengware.com/projects/soundtoclass/\" rel=\"nofollow noreferrer\">http://stephengware.com/projects/soundtoclass/</a></p>\n"
},
{
"answer_id": 15694770,
"author": "hamilton.lima",
"author_id": 1953431,
"author_profile": "https://Stackoverflow.com/users/1953431",
"pm_score": 2,
"selected": false,
"text": "<p>I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.</p>\n\n<p><a href=\"https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java\" rel=\"nofollow\">https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java</a></p>\n\n<p>Here is the code for reference.</p>\n\n<pre><code>package com.athanazio.jaga.desktop.sound;\n\nimport java.io.BufferedInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.AudioInputStream;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.DataLine;\nimport javax.sound.sampled.LineUnavailableException;\nimport javax.sound.sampled.SourceDataLine;\nimport javax.sound.sampled.UnsupportedAudioFileException;\n\npublic class Sound {\n\n AudioInputStream in;\n\n AudioFormat decodedFormat;\n\n AudioInputStream din;\n\n AudioFormat baseFormat;\n\n SourceDataLine line;\n\n private boolean loop;\n\n private BufferedInputStream stream;\n\n // private ByteArrayInputStream stream;\n\n /**\n * recreate the stream\n * \n */\n public void reset() {\n try {\n stream.reset();\n in = AudioSystem.getAudioInputStream(stream);\n din = AudioSystem.getAudioInputStream(decodedFormat, in);\n line = getLine(decodedFormat);\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void close() {\n try {\n line.close();\n din.close();\n in.close();\n } catch (IOException e) {\n }\n }\n\n Sound(String filename, boolean loop) {\n this(filename);\n this.loop = loop;\n }\n\n Sound(String filename) {\n this.loop = false;\n try {\n InputStream raw = Object.class.getResourceAsStream(filename);\n stream = new BufferedInputStream(raw);\n\n // ByteArrayOutputStream out = new ByteArrayOutputStream();\n // byte[] buffer = new byte[1024];\n // int read = raw.read(buffer);\n // while( read > 0 ) {\n // out.write(buffer, 0, read);\n // read = raw.read(buffer);\n // }\n // stream = new ByteArrayInputStream(out.toByteArray());\n\n in = AudioSystem.getAudioInputStream(stream);\n din = null;\n\n if (in != null) {\n baseFormat = in.getFormat();\n\n decodedFormat = new AudioFormat(\n AudioFormat.Encoding.PCM_SIGNED, baseFormat\n .getSampleRate(), 16, baseFormat.getChannels(),\n baseFormat.getChannels() * 2, baseFormat\n .getSampleRate(), false);\n\n din = AudioSystem.getAudioInputStream(decodedFormat, in);\n line = getLine(decodedFormat);\n }\n } catch (UnsupportedAudioFileException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (LineUnavailableException e) {\n e.printStackTrace();\n }\n }\n\n private SourceDataLine getLine(AudioFormat audioFormat)\n throws LineUnavailableException {\n SourceDataLine res = null;\n DataLine.Info info = new DataLine.Info(SourceDataLine.class,\n audioFormat);\n res = (SourceDataLine) AudioSystem.getLine(info);\n res.open(audioFormat);\n return res;\n }\n\n public void play() {\n\n try {\n boolean firstTime = true;\n while (firstTime || loop) {\n\n firstTime = false;\n byte[] data = new byte[4096];\n\n if (line != null) {\n\n line.start();\n int nBytesRead = 0;\n\n while (nBytesRead != -1) {\n nBytesRead = din.read(data, 0, data.length);\n if (nBytesRead != -1)\n line.write(data, 0, nBytesRead);\n }\n\n line.drain();\n line.stop();\n line.close();\n\n reset();\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 20514020,
"author": "Ishwor",
"author_id": 2118080,
"author_profile": "https://Stackoverflow.com/users/2118080",
"pm_score": 3,
"selected": false,
"text": "<p>For playing sound in java, you can refer to the following code.</p>\n\n<pre><code>import java.io.*;\nimport java.net.URL;\nimport javax.sound.sampled.*;\nimport javax.swing.*;\n\n// To play sound using Clip, the process need to be alive.\n// Hence, we use a Swing application.\npublic class SoundClipTest extends JFrame {\n\n public SoundClipTest() {\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n this.setTitle(\"Test Sound Clip\");\n this.setSize(300, 200);\n this.setVisible(true);\n\n try {\n // Open an audio input stream.\n URL url = this.getClass().getClassLoader().getResource(\"gameover.wav\");\n AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);\n // Get a sound clip resource.\n Clip clip = AudioSystem.getClip();\n // Open audio clip and load samples from the audio input stream.\n clip.open(audioIn);\n clip.start();\n } catch (UnsupportedAudioFileException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (LineUnavailableException e) {\n e.printStackTrace();\n }\n }\n\n public static void main(String[] args) {\n new SoundClipTest();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 35162134,
"author": "Cyril Duchon-Doris",
"author_id": 2832282,
"author_profile": "https://Stackoverflow.com/users/2832282",
"pm_score": 4,
"selected": false,
"text": "<p>I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).</p>\n\n<pre><code>private static void playSound(String sound){\n // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();\n URL file = cl.getResource(sound);\n final Media media = new Media(file.toString());\n final MediaPlayer mediaPlayer = new MediaPlayer(media);\n mediaPlayer.play();\n}\n</code></pre>\n\n<p>Notice : You need to <a href=\"https://stackoverflow.com/questions/14025718/javafx-toolkit-not-initialized-when-trying-to-play-an-mp3-file-through-mediap\">initialize JavaFX</a>. A quick way to do that, is to call the constructor of JFXPanel() once in your app :</p>\n\n<pre><code>static{\n JFXPanel fxPanel = new JFXPanel();\n}\n</code></pre>\n"
},
{
"answer_id": 37693420,
"author": "Andrew Jenkins",
"author_id": 2657020,
"author_profile": "https://Stackoverflow.com/users/2657020",
"pm_score": 3,
"selected": false,
"text": "<p>For whatever reason, the top answer by wchargin was giving me a null pointer error when I was calling this.getClass().getResourceAsStream().</p>\n\n<p>What worked for me was the following:</p>\n\n\n\n<pre class=\"lang-java prettyprint-override\"><code>void playSound(String soundFile) {\n File f = new File(\"./\" + soundFile);\n AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL()); \n Clip clip = AudioSystem.getClip();\n clip.open(audioIn);\n clip.start();\n}\n</code></pre>\n\n<p>And I would play the sound with:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> playSound(\"sounds/effects/sheep1.wav\");\n</code></pre>\n\n<p>sounds/effects/sheep1.wav was located in the base directory of my project in Eclipse (so not inside the src folder).</p>\n"
},
{
"answer_id": 39965540,
"author": "Galen Nare",
"author_id": 2737479,
"author_profile": "https://Stackoverflow.com/users/2737479",
"pm_score": 0,
"selected": false,
"text": "<p>This thread is rather old but I have determined an option that could prove useful.</p>\n\n<p>Instead of using the Java <code>AudioStream</code> library you could use an external program like Windows Media Player or VLC and run it with a console command through Java.</p>\n\n<pre><code>String command = \"\\\"C:/Program Files (x86)/Windows Media Player/wmplayer.exe\\\" \\\"C:/song.mp3\\\"\";\ntry {\n Process p = Runtime.getRuntime().exec(command);\ncatch (IOException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>This will also create a separate process that can be controlled it the program. </p>\n\n<pre><code>p.destroy();\n</code></pre>\n\n<p>Of course this will take longer to execute than using an internal library but there may be programs that can start up faster and possibly without a GUI given certain console commands. </p>\n\n<p>If time is not of the essence then this is useful.</p>\n"
},
{
"answer_id": 54341775,
"author": "Nav",
"author_id": 453673,
"author_profile": "https://Stackoverflow.com/users/453673",
"pm_score": 2,
"selected": false,
"text": "<p>I'm surprised nobody suggested using Applet. <a href=\"https://stackoverflow.com/a/3780445/453673\">Use</a> <code>Applet</code>. You'll have to supply the beep audio file as a <code>wav</code> file, but it works. I tried this on Ubuntu: </p>\n\n<pre><code>package javaapplication2;\n\nimport java.applet.Applet;\nimport java.applet.AudioClip;\nimport java.io.File;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic class JavaApplication2 {\n\n public static void main(String[] args) throws MalformedURLException {\n File file = new File(\"/path/to/your/sounds/beep3.wav\");\n URL url = null;\n if (file.canRead()) {url = file.toURI().toURL();}\n System.out.println(url);\n AudioClip clip = Applet.newAudioClip(url);\n clip.play();\n System.out.println(\"should've played by now\");\n }\n}\n//beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav\n</code></pre>\n"
},
{
"answer_id": 63436083,
"author": "Arsen Tagaev",
"author_id": 12102080,
"author_profile": "https://Stackoverflow.com/users/12102080",
"pm_score": 2,
"selected": false,
"text": "<p>It works for me. Simple variant</p>\n<pre><code>public void makeSound(){\n File lol = new File("somesound.wav");\n \n\n try{\n Clip clip = AudioSystem.getClip();\n clip.open(AudioSystem.getAudioInputStream(lol));\n clip.start();\n } catch (Exception e){\n e.printStackTrace();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67658292,
"author": "Adir D",
"author_id": 6130501,
"author_profile": "https://Stackoverflow.com/users/6130501",
"pm_score": 0,
"selected": false,
"text": "<p>I faced many issues to play mp3 file format\nso converted it to .wav using some <a href=\"https://online-audio-converter.com/\" rel=\"nofollow noreferrer\">online converter</a></p>\n<p>and then used below code (it was easier instead of mp3 supporting)</p>\n<pre><code>try\n{\n Clip clip = AudioSystem.getClip();\n clip.open(AudioSystem.getAudioInputStream(GuiUtils.class.getResource("/sounds/success.wav")));\n clip.start();\n}\ncatch (Exception e)\n{\n LogUtils.logError(e);\n}\n</code></pre>\n"
},
{
"answer_id": 68312041,
"author": "devp",
"author_id": 8234870,
"author_profile": "https://Stackoverflow.com/users/8234870",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import java.net.URL;\nimport java.net.MalformedURLException;\nimport javax.sound.sampled.AudioInputStream;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.Clip;\nimport javax.sound.sampled.LineUnavailableException;\nimport javax.sound.sampled.UnsupportedAudioFileException;\nimport java.io.IOException;\nimport java.io.File;\npublic class SoundClipTest{\n //plays the sound\n public static void playSound(final String path){\n try{\n final File audioFile=new File(path);\n AudioInputStream audioIn=AudioSystem.getAudioInputStream(audioFile);\n Clip clip=AudioSystem.getClip();\n clip.open(audioIn);\n clip.start();\n long duration=getDurationInSec(audioIn);\n //System.out.println(duration);\n //We need to delay it otherwise function will return\n //duration is in seconds we are converting it to milliseconds\n Thread.sleep(duration*1000);\n }catch(LineUnavailableException | UnsupportedAudioFileException | MalformedURLException | InterruptedException exception){\n exception.printStackTrace();\n }\n catch(IOException ioException){\n ioException.printStackTrace();\n }\n }\n //Gives duration in seconds for audio files\n public static long getDurationInSec(final AudioInputStream audioIn){\n final AudioFormat format=audioIn.getFormat();\n double frameRate=format.getFrameRate();\n return (long)(audioIn.getFrameLength()/frameRate);\n }\n ////////main//////\n public static void main(String $[]){\n //SoundClipTest test=new SoundClipTest();\n SoundClipTest.playSound("/home/dev/Downloads/mixkit-sad-game-over-trombone-471.wav");\n }\n}\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | I want to be able to play sound files in my program. Where should I look? | I wrote the following code that works fine. But I think it only works with `.wav` format.
```
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
``` |
26,323 | <p>C#: What is a good Regex to parse hyperlinks and their description?</p>
<p>Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag.</p>
<p>Please also consider obtaining hyperlinks which have other tags within the <code><a></code> tags such as <code><b></code> and <code><i></code>.
</p>
| [
{
"answer_id": 26328,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://regexlib.com/RETester.aspx?regexp_id=968\" rel=\"nofollow noreferrer\">I found this</a> but apparently <a href=\"http://forums.asp.net/p/1029814/1434514.aspx\" rel=\"nofollow noreferrer\">these guys</a> had some problems with it.</p>\n\n<p>Edit: <em>(It works!)</em><br />\nI have now done my own testing and found that it works, I don't know C# so I can't give you a C# answer but I do know PHP and here's the matches array I got back from running it on this:</p>\n\n<pre><code><a href=\"pages/index.php\" title=\"the title\">Text</a>\n\narray(3) { [0]=> string(52) \"Text\" [1]=> string(15) \"pages/index.php\" [2]=> string(4) \"Text\" } \n</code></pre>\n"
},
{
"answer_id": 26339,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "<p>As long as there are no nested tags (and no line breaks), the following variant works well:</p>\n\n<pre><code><a\\s+href=(?:\"([^\"]+)\"|'([^']+)').*?>(.*?)</a>\n</code></pre>\n\n<p>As soon as nested tags come into play, regular expressions are unfit for parsing. However, you can still use them by applying more advanced features of modern interpreters (depending on your regex machine). E.g. .NET regular expressions use a stack; I found this:</p>\n\n<pre><code>(?:<a.*?href=[\"\"'](?<url>.*?)[\"\"'].*?>)(?<name>(?><a[^<]*>(?<DEPTH>)|</a>(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:</a>) \n</code></pre>\n\n<p>Source: <a href=\"http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx</a></p>\n"
},
{
"answer_id": 26345,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 1,
"selected": false,
"text": "<p>I <a href=\"http://haacked.com/archive/2005/04/22/Matching_HTML_With_Regex.aspx\" rel=\"nofollow noreferrer\">have a regex</a> that handles most cases, though I believe it does match HTML within a multiline comment.</p>\n\n<p>It's written using the .NET syntax, but should be easily translatable.</p>\n"
},
{
"answer_id": 100657,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 2,
"selected": false,
"text": "<p>See this example from <a href=\"https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage#13446\">StackOverflow: Regular expression for parsing links from a webpage?</a></p>\n\n<p>Using <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\">The HTML Agility Pack</a> you can parse the html, and extract details using the semantics of the HTML, instead of a broken regex.</p>\n"
},
{
"answer_id": 1720232,
"author": "James Shaw",
"author_id": 189626,
"author_profile": "https://Stackoverflow.com/users/189626",
"pm_score": 0,
"selected": false,
"text": "<p>Just going to throw this snippet out there now that I have it working..this is a less greedy version of one suggested earlier. The original wouldnt work if the input had multiple hyperlinks. This code below will allow you to loop through all the hyperlinks:</p>\n\n<pre><code>static Regex rHref = new Regex(@\"<a.*?href=[\"\"'](?<url>[^\"\"^']+[.]*?)[\"\"'].*?>(?<keywords>[^<]+[.]*?)</a>\", RegexOptions.IgnoreCase | RegexOptions.Compiled);\npublic void ParseHyperlinks(string html)\n{\n MatchCollection mcHref = rHref.Matches(html);\n\n foreach (Match m in mcHref)\n AddKeywordLink(m.Groups[\"keywords\"].Value, m.Groups[\"url\"].Value);\n}\n</code></pre>\n"
},
{
"answer_id": 1815829,
"author": "Svarga",
"author_id": 220875,
"author_profile": "https://Stackoverflow.com/users/220875",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a regular expression that will match the balanced tags.</p>\n\n<p>(?:\"\"'[\"\"'].*?>)(?(?>(?)|(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:) </p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
] | C#: What is a good Regex to parse hyperlinks and their description?
Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag.
Please also consider obtaining hyperlinks which have other tags within the `<a>` tags such as `<b>` and `<i>`.
| As long as there are no nested tags (and no line breaks), the following variant works well:
```
<a\s+href=(?:"([^"]+)"|'([^']+)').*?>(.*?)</a>
```
As soon as nested tags come into play, regular expressions are unfit for parsing. However, you can still use them by applying more advanced features of modern interpreters (depending on your regex machine). E.g. .NET regular expressions use a stack; I found this:
```
(?:<a.*?href=[""'](?<url>.*?)[""'].*?>)(?<name>(?><a[^<]*>(?<DEPTH>)|</a>(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:</a>)
```
Source: <http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx> |
26,354 | <p>Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode.
</p>
| [
{
"answer_id": 26356,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 0,
"selected": false,
"text": "<p>Last time I had to print Barcode (despite the printer or framework) I resorted to use a True Type font with the Barcode I needed. (In my case was EAN-13 something), an european barcode.</p>\n\n<p>There are fonts where you simply write numbers (and/or letters when supported) and you get a perfect barcode any scanner can read :)</p>\n\n<p>Google is your friend. I don't know if there are free ones.</p>\n"
},
{
"answer_id": 26373,
"author": "Steve",
"author_id": 620435,
"author_profile": "https://Stackoverflow.com/users/620435",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you for your answer. There are free fonts available -- However, the PB20 is a handheld printer with a few built-in fonts. It has the capability to print barcodes and can be manipulated directly via the serial port. Intermec provides a .Net CF API to make printing \"easy\", and it is using this API that we have been unable to figure out how to tell the printer to print a barcode.</p>\n"
},
{
"answer_id": 27081,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 0,
"selected": false,
"text": "<p>Ditch all API's and use a serial port API directly.</p>\n\n<p>Talk the printers language and you can get decent results.\nEvery other approach leads to frustration.\nNot so pretty, but that is the way my old factory worked.\n4k print jobs per day, and none ever missed.</p>\n"
},
{
"answer_id": 27087,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.squaregear.net/fonts/free3of9.shtml\" rel=\"nofollow noreferrer\">Free 3 of 9</a></p>\n\n<blockquote>\n <p>This is 3 of 9 (sometimes called \"code\n 39\"), a widely used barcode standard\n that includes capital letters,\n numbers, and several symbols. This is\n not the barcode for UPC's (universal\n price codes) found on products at the\n store. However, most kinds of barcode\n scanners will recognize 3 of 9 just\n fine.</p>\n</blockquote>\n"
},
{
"answer_id": 28168,
"author": "Steve",
"author_id": 620435,
"author_profile": "https://Stackoverflow.com/users/620435",
"pm_score": 2,
"selected": true,
"text": "<p>Thank you all for your thoughts. Printing directly to the serial port is likely the most flexible method. In this case we didn't want to replicate all of the work that was already built into the Intermec dll for handling the port, printer errors, etc. We were able to get this working by sending the printer the appropriate codes to switch it into a different mode and then pass direct printer commands that way.</p>\n\n<p>Here was our solution in case anyone else happens to encounter a similar issue working with Intermec Printers. The following code is a test case that doesn't catch printer errors and retry, etc. (See Intermec code examples.)</p>\n\n<pre><code>Intermec.Print.LinePrinter lp;\n\nint escapeCharacter = int.Parse(\"1b\", NumberStyles.HexNumber);\nchar[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' };\n\nlp = new Intermec.Print.LinePrinter(\"Printer_Config.XML\", \"PrinterPB20_40COL\");\nlp.Open();\n\nlp.Write(charArray2); //switch to ez print mode\n\nstring testBarcode = \"{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}\";\nlp.Write(testBarcode);\n\nlp.Write(\"{LP}\"); //switch from ez print mode back to line printer mode\n\nlp.NewLine();\nlp.Write(\"Test\"); //verify line printer mode is working\n</code></pre>\n\n<p>There is a technical document on Intermec's support site called the \"Technical Manual\" that describes the code for directly controlling the printer. The section about Easy Print describes how to print a variety of barcodes.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/620435/"
] | Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode.
| Thank you all for your thoughts. Printing directly to the serial port is likely the most flexible method. In this case we didn't want to replicate all of the work that was already built into the Intermec dll for handling the port, printer errors, etc. We were able to get this working by sending the printer the appropriate codes to switch it into a different mode and then pass direct printer commands that way.
Here was our solution in case anyone else happens to encounter a similar issue working with Intermec Printers. The following code is a test case that doesn't catch printer errors and retry, etc. (See Intermec code examples.)
```
Intermec.Print.LinePrinter lp;
int escapeCharacter = int.Parse("1b", NumberStyles.HexNumber);
char[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' };
lp = new Intermec.Print.LinePrinter("Printer_Config.XML", "PrinterPB20_40COL");
lp.Open();
lp.Write(charArray2); //switch to ez print mode
string testBarcode = "{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}";
lp.Write(testBarcode);
lp.Write("{LP}"); //switch from ez print mode back to line printer mode
lp.NewLine();
lp.Write("Test"); //verify line printer mode is working
```
There is a technical document on Intermec's support site called the "Technical Manual" that describes the code for directly controlling the printer. The section about Easy Print describes how to print a variety of barcodes. |
26,362 | <p>Has anyone managed to use <code>ItemizedOverlays</code> in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available. </p>
<p>I've been trying to use the <code>ItemizedOverlay</code> and <code>OverlayItem</code> classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map.</p>
<p>I can add my own custom overlays using a similar technique, it's just the <code>ItemizedOverlays</code> that don't work.</p>
<p>Once I've implemented my own <code>ItemizedOverlay</code> (and overridden <code>createItem</code>), creating a new instance of my class seems to work (I can extract <code>OverlayItems</code> from it) but adding it to a map's <code>Overlay</code> list doesn't make it appear as it should.</p>
<p>This is the code I use to add the <code>ItemizedOverlay</code> class as an <code>Overlay</code> on to my <code>MapView</code>.</p>
<pre><code>// Add the ItemizedOverlay to the Map
private void addItemizedOverlay() {
Resources r = getResources();
MapView mapView = (MapView)findViewById(R.id.mymapview);
List<Overlay> overlays = mapView.getOverlays();
MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon));
overlays.add(markers);
OverlayItem oi = markers.getItem(0);
markers.setFocus(oi);
mapView.postInvalidate();
}
</code></pre>
<p>Where <code>MyItemizedOverlay</code> is defined as:</p>
<pre><code>public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public MyItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
populate();
}
@Override
protected OverlayItem createItem(int index) {
Double lat = (index+37.422006)*1E6;
Double lng = -122.084095*1E6;
GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue());
OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text");
return oi;
}
@Override
public int size() {
return 5;
}
}
</code></pre>
| [
{
"answer_id": 46766,
"author": "eon",
"author_id": 2000,
"author_profile": "https://Stackoverflow.com/users/2000",
"pm_score": 7,
"selected": true,
"text": "<p>For the sake of completeness I'll repeat the discussion on Reto's post over at the <a href=\"http://groups.google.com/group/android-developers/browse_thread/thread/36fe0648dabfe745#\" rel=\"noreferrer\">Android Groups here</a>.</p>\n\n<p>It seems that if you set the bounds on your drawable it does the trick:</p>\n\n<pre><code>Drawable defaultMarker = r.getDrawable(R.drawable.icon);\n\n// You HAVE to specify the bounds! It seems like the markers are drawn\n// through Drawable.draw(Canvas) and therefore must have its bounds set\n// before drawing.\ndefaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),\n defaultMarker.getIntrinsicHeight());\n\nMyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);\noverlays.add(markers);\n</code></pre>\n\n<p>By the way, the above is shamelessly ripped from <a href=\"http://www.marcelp.info/2008/09/01/android-itemizedoverlay-demo/\" rel=\"noreferrer\">the demo at MarcelP.info</a>. Also, here is a <a href=\"http://androidguys.com/?p=1413\" rel=\"noreferrer\">good howto</a>.</p>\n"
},
{
"answer_id": 58889919,
"author": "zahra salmaninejad",
"author_id": 11372789,
"author_profile": "https://Stackoverflow.com/users/11372789",
"pm_score": 1,
"selected": false,
"text": "<p>try :</p>\n\n<pre><code>Drawable defaultMarker = r.getDrawable(R.drawable.icon);\n\ndefaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),\n defaultMarker.getIntrinsicHeight());\n\nMyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);\noverlays.add(markers);\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/822/"
] | Has anyone managed to use `ItemizedOverlays` in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available.
I've been trying to use the `ItemizedOverlay` and `OverlayItem` classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map.
I can add my own custom overlays using a similar technique, it's just the `ItemizedOverlays` that don't work.
Once I've implemented my own `ItemizedOverlay` (and overridden `createItem`), creating a new instance of my class seems to work (I can extract `OverlayItems` from it) but adding it to a map's `Overlay` list doesn't make it appear as it should.
This is the code I use to add the `ItemizedOverlay` class as an `Overlay` on to my `MapView`.
```
// Add the ItemizedOverlay to the Map
private void addItemizedOverlay() {
Resources r = getResources();
MapView mapView = (MapView)findViewById(R.id.mymapview);
List<Overlay> overlays = mapView.getOverlays();
MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon));
overlays.add(markers);
OverlayItem oi = markers.getItem(0);
markers.setFocus(oi);
mapView.postInvalidate();
}
```
Where `MyItemizedOverlay` is defined as:
```
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public MyItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
populate();
}
@Override
protected OverlayItem createItem(int index) {
Double lat = (index+37.422006)*1E6;
Double lng = -122.084095*1E6;
GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue());
OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text");
return oi;
}
@Override
public int size() {
return 5;
}
}
``` | For the sake of completeness I'll repeat the discussion on Reto's post over at the [Android Groups here](http://groups.google.com/group/android-developers/browse_thread/thread/36fe0648dabfe745#).
It seems that if you set the bounds on your drawable it does the trick:
```
Drawable defaultMarker = r.getDrawable(R.drawable.icon);
// You HAVE to specify the bounds! It seems like the markers are drawn
// through Drawable.draw(Canvas) and therefore must have its bounds set
// before drawing.
defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),
defaultMarker.getIntrinsicHeight());
MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);
overlays.add(markers);
```
By the way, the above is shamelessly ripped from [the demo at MarcelP.info](http://www.marcelp.info/2008/09/01/android-itemizedoverlay-demo/). Also, here is a [good howto](http://androidguys.com/?p=1413). |
26,366 | <p>For the past 10 years or so there have been a smattering of articles and papers referencing Christopher Alexander's newer work "The Nature of Order" and how it can be applied to software.</p>
<p>Unfortunately, the only works I can find are from James Coplien and Richard Gabriel; there is nothing beyond that, at least from my attempts to find such things through google.</p>
<p>Is this kind of discussion happening anywhere?</p>
<p>MSN</p>
<hr>
<p>@Georgia</p>
<p>My question isn't about design patterns or pattern languages; it's about trying to see if more of Christopher Alexander's work can be applied to software (which it probably can, since it has even less physical constraints than architecture and building).</p>
<p>Design patterns and pattern languages seem to have embraced the structure of Alexander's design patterns, but not many capture the essence. The essence being something beyond solving a problem in a particular context.</p>
<p>It's difficult to explain without using some of Alexander's later works as a reference point.</p>
<p>Edit: No, I take that back.</p>
<p>For example, there's an architectural design pattern that is called Alcoves. The pattern has a context that isn't just rooted in the circumstances of the situation but also rooted in fundamentals about the purpose of buildings: that they are structures to be lived in and must promote living in them. In the case of the Alcove pattern, the context is that you want an area that allows for multiple people to be in the same area doing different things, because it is important for family members to be physically together as well as to be able to do things that tend to distract other family members.</p>
<p>Most software design patterns describe a problem in a context, but they make no deeper statement about why the problem is important, or why the problem is something that is fundamental to software. It makes it very easy to apply design patterns inappropriately or blithely, which is the exact opposite of the intent of design patterns to began with.</p>
<p>MSN
</p>
| [
{
"answer_id": 46766,
"author": "eon",
"author_id": 2000,
"author_profile": "https://Stackoverflow.com/users/2000",
"pm_score": 7,
"selected": true,
"text": "<p>For the sake of completeness I'll repeat the discussion on Reto's post over at the <a href=\"http://groups.google.com/group/android-developers/browse_thread/thread/36fe0648dabfe745#\" rel=\"noreferrer\">Android Groups here</a>.</p>\n\n<p>It seems that if you set the bounds on your drawable it does the trick:</p>\n\n<pre><code>Drawable defaultMarker = r.getDrawable(R.drawable.icon);\n\n// You HAVE to specify the bounds! It seems like the markers are drawn\n// through Drawable.draw(Canvas) and therefore must have its bounds set\n// before drawing.\ndefaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),\n defaultMarker.getIntrinsicHeight());\n\nMyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);\noverlays.add(markers);\n</code></pre>\n\n<p>By the way, the above is shamelessly ripped from <a href=\"http://www.marcelp.info/2008/09/01/android-itemizedoverlay-demo/\" rel=\"noreferrer\">the demo at MarcelP.info</a>. Also, here is a <a href=\"http://androidguys.com/?p=1413\" rel=\"noreferrer\">good howto</a>.</p>\n"
},
{
"answer_id": 58889919,
"author": "zahra salmaninejad",
"author_id": 11372789,
"author_profile": "https://Stackoverflow.com/users/11372789",
"pm_score": 1,
"selected": false,
"text": "<p>try :</p>\n\n<pre><code>Drawable defaultMarker = r.getDrawable(R.drawable.icon);\n\ndefaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),\n defaultMarker.getIntrinsicHeight());\n\nMyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);\noverlays.add(markers);\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1799/"
] | For the past 10 years or so there have been a smattering of articles and papers referencing Christopher Alexander's newer work "The Nature of Order" and how it can be applied to software.
Unfortunately, the only works I can find are from James Coplien and Richard Gabriel; there is nothing beyond that, at least from my attempts to find such things through google.
Is this kind of discussion happening anywhere?
MSN
---
@Georgia
My question isn't about design patterns or pattern languages; it's about trying to see if more of Christopher Alexander's work can be applied to software (which it probably can, since it has even less physical constraints than architecture and building).
Design patterns and pattern languages seem to have embraced the structure of Alexander's design patterns, but not many capture the essence. The essence being something beyond solving a problem in a particular context.
It's difficult to explain without using some of Alexander's later works as a reference point.
Edit: No, I take that back.
For example, there's an architectural design pattern that is called Alcoves. The pattern has a context that isn't just rooted in the circumstances of the situation but also rooted in fundamentals about the purpose of buildings: that they are structures to be lived in and must promote living in them. In the case of the Alcove pattern, the context is that you want an area that allows for multiple people to be in the same area doing different things, because it is important for family members to be physically together as well as to be able to do things that tend to distract other family members.
Most software design patterns describe a problem in a context, but they make no deeper statement about why the problem is important, or why the problem is something that is fundamental to software. It makes it very easy to apply design patterns inappropriately or blithely, which is the exact opposite of the intent of design patterns to began with.
MSN
| For the sake of completeness I'll repeat the discussion on Reto's post over at the [Android Groups here](http://groups.google.com/group/android-developers/browse_thread/thread/36fe0648dabfe745#).
It seems that if you set the bounds on your drawable it does the trick:
```
Drawable defaultMarker = r.getDrawable(R.drawable.icon);
// You HAVE to specify the bounds! It seems like the markers are drawn
// through Drawable.draw(Canvas) and therefore must have its bounds set
// before drawing.
defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),
defaultMarker.getIntrinsicHeight());
MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);
overlays.add(markers);
```
By the way, the above is shamelessly ripped from [the demo at MarcelP.info](http://www.marcelp.info/2008/09/01/android-itemizedoverlay-demo/). Also, here is a [good howto](http://androidguys.com/?p=1413). |
26,369 | <p>I have a .NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)?</p>
<p>Some people pointed to <code>Application.LocalUserAppDataPath</code>. However, that creates a folder structure like:</p>
<blockquote>
<p>C:\Documents and Settings\user_name\Local Settings\Application
Data\company_name\product_name\product_version\</p>
</blockquote>
<p>If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version.
</p>
| [
{
"answer_id": 26377,
"author": "LeoD",
"author_id": 2868,
"author_profile": "https://Stackoverflow.com/users/2868",
"pm_score": 0,
"selected": false,
"text": "<p>Settings are standard key-value pairs (string-string). I could wrap them in an XML file, if that helps.</p>\n\n<p>I'd rather use the file system instead of the registry. It seems to be easier to maintain. In support scenarios, if the user needs to manually open/change the settings, that would be easier if it's in the file system. </p>\n"
},
{
"answer_id": 26379,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>I'd go down the folder list you posted except for the product version. You don't want the settings reset after an update is released.</p>\n\n<p>I'm actually moving away from the registry for user settings because of the debug/footprint factor. I'm currently only storing a few basic settings (window size, position, version of a data file) in the registry, and I've run into more problems if an update goes bad or a user loses a second monitor and that is where the application was opening to. A few of them are savvy enough to understand regedit, but for the rest they have to do a reinstall, which is quick, but I think they grumble a bit. With the file based version, all I'd have to do is have them open up an XML file in Notepad and make a quick tweak.</p>\n\n<p>In addition, I'm looking to make my application runnable off a USB flash drive, and having the settings tied into the file seems much friendlier to that process. I'm sure I can do some code to check/clean the registry, but I think most of us are already tired of the registry clutter that seems to eat up our machines nowadays.</p>\n\n<p>I know there are some security tradeoffs to this, but none of the data I'm sorting is that critical to that cause, and I'm not suffering any performance hits due to the size of the application.</p>\n"
},
{
"answer_id": 26394,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 7,
"selected": true,
"text": "<p>I love using the built-in <a href=\"http://msdn.microsoft.com/en-us/library/a65txexh.aspx\" rel=\"noreferrer\">Application Settings</a>. Then you have built in support for using the settings designer if you want at design-time, or at runtime to use: </p>\n\n<pre><code>// read setting\nstring setting1 = (string)Settings.Default[\"MySetting1\"];\n// save setting\nSettings.Default[\"MySetting2\"] = \"My Setting Value\";\n\n// you can force a save with\nProperties.Settings.Default.Save();\n</code></pre>\n\n<p>It does store the settings in a similar folder structure as you describe (with the version in the path). However, with a simple call to: </p>\n\n<pre><code>Properties.Settings.Default.Upgrade(); \n</code></pre>\n\n<p>The app will pull all previous versions settings in to save in. </p>\n"
},
{
"answer_id": 26414,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 2,
"selected": false,
"text": "<p>One approach that has worked for me in the past has been to create a settings class and use XML serialization to write it to the file system. You could extend this concept by creating a collection of settings objects and serializing it. You would have all of your settings for all users in one place without having to worry about managing the file system.</p>\n\n<p>Before anyone gives me any flak for partially re-inventing the wheel, let me say a few things. For one, it is only a few lines of code to serialize and write the file. Secondly, if you have an object that contains your settings, you don't have to make multiple calls to the appSettings object when you load your app. And lastly, it is very easy to add items that represent your applications state, thereby allowing you to resume a long-running task when the application loads next.</p>\n"
},
{
"answer_id": 26424,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 3,
"selected": false,
"text": "<p>Or write your settings in a xml file and save it using <a href=\"http://msdn.microsoft.com/en-us/library/3ak841sy.aspx\" rel=\"noreferrer\">Isolated Storage</a>. Depending on the store you use it saves it in the Application Data folder. You can also choose a roaming enabled store which means when the user logs on a different computer the settings move with them.</p>\n"
},
{
"answer_id": 26982,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Isolated storage is primarily used for applications distributed using <a href=\"http://en.wikipedia.org/wiki/ClickOnce\" rel=\"nofollow noreferrer\">ClickOnce</a> and are run in a secure sandbox. The base path is decided for you and you won't be able infer it in your code. The path will be something like \"\\LocalSettings\\ApplicationData\\IsolatedStorage\\ejwnwe.302\\kfiwemqi.owx\\url.asdaiojwejoieajae....\", not all that friendly. Your storage space is also limited.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/26369/what-is-the-best-way-to-store-user-settings-for-a-net-application/26400#26400\">Ryan Farley has it right</a>.</p>\n"
},
{
"answer_id": 5379459,
"author": "Jonathan Wood",
"author_id": 522663,
"author_profile": "https://Stackoverflow.com/users/522663",
"pm_score": 3,
"selected": false,
"text": "<p>.NET applications have a built-in settings mechanism that is easy to use. The problem with it, in my opinion, is that it stores those settings off into a rather obscure directory and end users will not be able to find it. Moreover, just switching from debug to release build changes the location of this directory, meaning that any settings saved in one configuration are lost in the other.</p>\n\n<p>For these and other reasons, I came up with <a href=\"http://www.blackbeltcoder.com/Articles/winforms/a-custom-settings-class-for-winforms\" rel=\"noreferrer\">my own settings code for Windows Forms</a>. It's not quite as slick as the one that comes with .NET, but it's more flexible, and I use it all the time.</p>\n"
},
{
"answer_id": 31044553,
"author": "vitalinvent",
"author_id": 2409677,
"author_profile": "https://Stackoverflow.com/users/2409677",
"pm_score": 1,
"selected": false,
"text": "<p>I try some methods to store my settings to simply text file and i found best way:</p>\n\n<p>file stored in application folder, to usage , <strong>settings.txt</strong>:\n(inside settings file approved comments, try //comment)</p>\n\n<p>//to get settings value</p>\n\n<pre><code>Settings.Get(\"name\", \"Ivan\");\n</code></pre>\n\n<p>//to set settings value</p>\n\n<pre><code>Settings.Set(\"name\", \"John\");\n</code></pre>\n\n<p>using:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Windows.Forms;\n</code></pre>\n\n<p>//you can store also with section name, to use just add name section Set(section_name,name,value) and Get(section_name,name,value)</p>\n\n<pre><code>public static class Settings\n{\n private static string SECTION = typeof(Settings).Namespace;//\"SETTINGS\";\n private static string settingsPath = Application.StartupPath.ToString() + \"\\\\settings.txt\";\n [DllImport(\"kernel32\")]\n private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);\n [DllImport(\"kernel32\")]\n private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);\n public static String GetString(String name)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(SECTION,name,\"\",temp,255,settingsPath);\n return temp.ToString();\n }\n public static String Get(String name, String defVal)\n {\n return Get(SECTION,name,defVal);\n }\n public static String Get(string _SECTION, String name, String defVal)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(_SECTION, name, \"\", temp, 255, settingsPath);\n return temp.ToString();\n }\n public static Boolean Get(String name, Boolean defVal)\n {\n return Get(SECTION, name, defVal);\n }\n public static Boolean Get(string _SECTION, String name, Boolean defVal)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(_SECTION,name,\"\",temp,255,settingsPath);\n bool retval=false;\n if (bool.TryParse(temp.ToString(),out retval))\n {\n return retval;\n } else\n {\n return retval;\n }\n }\n public static int Get(String name, int defVal)\n {\n return Get(SECTION, name, defVal);\n }\n public static int Get(string _SECTION, String name, int defVal)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(SECTION,name,\"\",temp,255,settingsPath);\n int retval=0;\n if (int.TryParse(temp.ToString(),out retval))\n {\n return retval;\n } else\n {\n return retval;\n }\n }\n public static void Set(String name, String val)\n {\n Set(SECTION, name,val);\n }\n public static void Set(string _SECTION, String name, String val)\n {\n WritePrivateProfileString(_SECTION, name, val, settingsPath);\n }\n public static void Set(String name, Boolean val)\n {\n Set(SECTION, name, val);\n }\n public static void Set(string _SECTION, String name, Boolean val)\n {\n WritePrivateProfileString(_SECTION, name, val.ToString(), settingsPath);\n }\n public static void Set(String name, int val)\n {\n Set(SECTION, name, val);\n }\n public static void Set(string _SECTION,String name, int val)\n {\n WritePrivateProfileString(SECTION, name, val.ToString(), settingsPath);\n }\n}\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868/"
] | I have a .NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)?
Some people pointed to `Application.LocalUserAppDataPath`. However, that creates a folder structure like:
>
> C:\Documents and Settings\user\_name\Local Settings\Application
> Data\company\_name\product\_name\product\_version\
>
>
>
If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version.
| I love using the built-in [Application Settings](http://msdn.microsoft.com/en-us/library/a65txexh.aspx). Then you have built in support for using the settings designer if you want at design-time, or at runtime to use:
```
// read setting
string setting1 = (string)Settings.Default["MySetting1"];
// save setting
Settings.Default["MySetting2"] = "My Setting Value";
// you can force a save with
Properties.Settings.Default.Save();
```
It does store the settings in a similar folder structure as you describe (with the version in the path). However, with a simple call to:
```
Properties.Settings.Default.Upgrade();
```
The app will pull all previous versions settings in to save in. |
26,383 | <p>I know two approaches to Exception handling, lets have a look at them.</p>
<ol>
<li><p>Contract approach.</p>
<p>When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception.</p>
</li>
<li><p>Exceptional approach.</p>
<p>Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach.</p>
</li>
</ol>
<p>Lets use both approaches in different cases:</p>
<p>We have a Customer class that has a method called OrderProduct.</p>
<p>contract approach:</p>
<pre><code>class Customer
{
public void OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
throw new NoCreditException("Not enough credit!");
// do stuff
}
}
</code></pre>
<p>exceptional approach:</p>
<pre><code>class Customer
{
public bool OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
return false;
// do stuff
return true;
}
}
if !(customer.OrderProduct(product))
Console.WriteLine("Not enough credit!");
else
// go on with your life
</code></pre>
<p>Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery.</p>
<p>But here is a situation I err on the contract style.</p>
<p>Exceptional:</p>
<pre><code>class CarController
{
// returns null if car creation failed.
public Car CreateCar(string model)
{
// something went wrong, wrong model
return null;
}
}
</code></pre>
<p>When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one:</p>
<pre><code>class CarController
{
public Car CreateCar(string model)
{
// something went wrong, wrong model
throw new CarModelNotKnownException("Model unkown");
return new Car();
}
}
</code></pre>
<p>Which do style do you use? What do you think is best general approach to Exceptions?</p>
| [
{
"answer_id": 26395,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that if you are building a class which will be used by an external program (or will be reused by other programs) then you should use the contract approach. A good example of this is an API of any kind.</p>\n"
},
{
"answer_id": 26401,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 1,
"selected": false,
"text": "<p>My usual approach is to use contract to handle any kind of error due to \"client\" invocation, that is, due to an external error (i.e ArgumentNullException).</p>\n\n<p>Every error on the arguments is not handled. An exception is raised and the \"client\" is in charge of handling it. On the other hand, for internal errors always try to correct them (as if you can't get a database connection for some reason) and only if you can't handle it reraise the exception.</p>\n\n<p>It's important to keep in mind that most unhandled exception at such level will not be able to be handled by the client anyway so they will just probably go up to the most general exception handler, so if such an exception occurs you are probably FUBAR anyway.</p>\n"
},
{
"answer_id": 26403,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 4,
"selected": true,
"text": "<p>I favor what you call the \"contract\" approach. Returning nulls or other special values to indicate errors isn't necessary in a language that supports exceptions. I find it much easier to understand code when it doesn't have a bunch of \"if (result == NULL)\" or \"if (result == -1)\" clauses mixed in with what could be very simple, straightforward logic.</p>\n"
},
{
"answer_id": 26548,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p>If you are actually interested in exceptions and want to think about how to use them to construct robust systems, consider reading <a href=\"http://www.erlang.org/download/armstrong_thesis_2003.pdf\" rel=\"nofollow noreferrer\">Making reliable distributed systems in the presence of software errors</a>.</p>\n"
},
{
"answer_id": 7517569,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "<p>Both approaches are right. What that means is that a contract should be written in such a way as to specify for all cases that are not truly exceptional a behavior that does not require throwing an exception.</p>\n\n<p>Note that some situations may or may not be exceptional based upon what the caller of the code is expecting. If the caller is expecting that a dictionary will contain a certain item, and absence of that item would indicate a severe problem, then failure to find the item is an exceptional condition and should cause an exception to be thrown. If, however, the caller doesn't really know if an item exists, and is equally prepared to handle its presence or its absence, then absence of the item would be an expected condition and should not cause an exception. The best way to handle such variations in caller expectation is to have a contract specify two methods: a DoSomething method and a TryDoSomething method, e.g.</p>\n\n<pre>\nTValue GetValue(TKey Key);\nbool TryGetValue(TKey Key, ref TValue value);\n</pre>\n\n<p>Note that, while the standard 'try' pattern is as illustrated above, some alternatives may also be helpful if one is designing an interface which produces items:</p>\n\n<pre>\n // In case of failure, set ok false and return default<TValue>.\nTValue TryGetResult(ref bool ok, TParam param);\n// In case of failure, indicate particular problem in GetKeyErrorInfo\n// and return default<TValue>.\nTValue TryGetResult(ref GetKeyErrorInfo errorInfo, ref TParam param);\n</pre>\n\n<p>Note that using something like the normal TryGetResult pattern within an interface will make the interface invariant with respect to the result type; using one of the patterns above will allow the interface to be covariant with respect to the result type. Also, it will allow the result to be used in a 'var' declaration:</p>\n\n<pre>\n var myThingResult = myThing.TryGetSomeValue(ref ok, whatever);\n if (ok) { do_whatever }\n</pre>\n\n<p>Not quite the standard approach, but in some cases the advantages may justify it.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I know two approaches to Exception handling, lets have a look at them.
1. Contract approach.
When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception.
2. Exceptional approach.
Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach.
Lets use both approaches in different cases:
We have a Customer class that has a method called OrderProduct.
contract approach:
```
class Customer
{
public void OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
throw new NoCreditException("Not enough credit!");
// do stuff
}
}
```
exceptional approach:
```
class Customer
{
public bool OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
return false;
// do stuff
return true;
}
}
if !(customer.OrderProduct(product))
Console.WriteLine("Not enough credit!");
else
// go on with your life
```
Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery.
But here is a situation I err on the contract style.
Exceptional:
```
class CarController
{
// returns null if car creation failed.
public Car CreateCar(string model)
{
// something went wrong, wrong model
return null;
}
}
```
When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one:
```
class CarController
{
public Car CreateCar(string model)
{
// something went wrong, wrong model
throw new CarModelNotKnownException("Model unkown");
return new Car();
}
}
```
Which do style do you use? What do you think is best general approach to Exceptions? | I favor what you call the "contract" approach. Returning nulls or other special values to indicate errors isn't necessary in a language that supports exceptions. I find it much easier to understand code when it doesn't have a bunch of "if (result == NULL)" or "if (result == -1)" clauses mixed in with what could be very simple, straightforward logic. |
26,393 | <p>I've seen news of <a href="http://github.com/jeresig/sizzle/tree/master" rel="noreferrer">John Resig's fast new selector engine named Sizzle</a> pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine?</p>
<p>Thanks!</p>
| [
{
"answer_id": 26411,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 7,
"selected": true,
"text": "<p>A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or similar). </p>\n\n<p>For example, this jQuery:</p>\n\n<pre><code>$('div')\n</code></pre>\n\n<p>Would search for and return all of the <div> elements on the page. It uses jQuery's selector engine to do that.</p>\n\n<p>Optimizing the selector engine is a big deal because almost every operation you perform with these frameworks is based on some sort of DOM query.</p>\n"
},
{
"answer_id": 26417,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 3,
"selected": false,
"text": "<p>Also, Sizzle is the engine John Resig is working on currently to replace jQuery's already fantastic selector engine.</p>\n"
},
{
"answer_id": 26418,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 4,
"selected": false,
"text": "<p>A selector engine is a JavaScript library that lets you select elements in the DOM tree using some kind of string for identifying them (think regular expressions for DOM elements). Most selector engines use some variation of the CSS3 selectors syntax so, for example, you can write something like:</p>\n\n<pre><code>var paragraphs = selectorengine.select('p.firstParagraph')\n</code></pre>\n\n<p>to select all P elements in the document with class firstParagraph.</p>\n\n<p>Some selector engines also support a partial implementation of XPath, and even some custom syntaxes. For example, jQuery lets you write:</p>\n\n<pre><code>var checkedBoxes = jQuery('form#login input:checked')\n</code></pre>\n\n<p>To select all checked check boxes in the login form in the document.</p>\n"
},
{
"answer_id": 26419,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>A selector engine is a way to traverse the DOM looking for a specific element.</p>\n\n<p>An example of a built in selector engine:</p>\n\n<pre><code>var foo = document.getElementById('foo');\n</code></pre>\n"
},
{
"answer_id": 537060,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A selector engine is used to find elements in a document, in the same way as CSS stylesheets does. Currently only Safari has the built-in querySelectorAll function which does just that. With other browser you have to use external JavaScript implementations as <a href=\"http://llamalab.com/js/selector/\" rel=\"nofollow noreferrer\">LlamaLab Selector</a> or Sizzle instead. </p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266/"
] | I've seen news of [John Resig's fast new selector engine named Sizzle](http://github.com/jeresig/sizzle/tree/master) pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine?
Thanks! | A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or similar).
For example, this jQuery:
```
$('div')
```
Would search for and return all of the <div> elements on the page. It uses jQuery's selector engine to do that.
Optimizing the selector engine is a big deal because almost every operation you perform with these frameworks is based on some sort of DOM query. |
26,433 | <p>Say I have three files (template_*.txt):</p>
<ul>
<li>template_x.txt</li>
<li>template_y.txt</li>
<li>template_z.txt</li>
</ul>
<p>I want to copy them to three new files (foo_*.txt). </p>
<ul>
<li>foo_x.txt </li>
<li>foo_y.txt </li>
<li>foo_z.txt</li>
</ul>
<p>Is there some simple way to do that with one command, e.g. </p>
<p><code>cp --enableAwesomeness template_*.txt foo_*.txt</code></p>
| [
{
"answer_id": 26439,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know of anything in bash or on cp, but there are simple ways to do this sort of thing using (for example) a perl script:</p>\n\n<pre><code>($op = shift) || die \"Usage: rename perlexpr [filenames]\\n\";\n\nfor (@ARGV) {\n $was = $_;\n eval $op;\n die $@ if $@;\n rename($was,$_) unless $was eq $_;\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>rename s/template/foo/ *.txt\n</code></pre>\n"
},
{
"answer_id": 26441,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 1,
"selected": false,
"text": "<pre><code>for i in template_*.txt; do cp -v \"$i\" \"`echo $i | sed 's%^template_%foo_%'`\"; done\n</code></pre>\n\n<p>Probably breaks if your filenames have funky characters in them. Remove the '-v' when (if) you get confidence that it works reliably.</p>\n"
},
{
"answer_id": 26447,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 2,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>for file in template_*.txt ; do cp $file `echo $file | sed 's/template_\\(.*\\)/foo_\\1/'` ; done\n</code></pre>\n"
},
{
"answer_id": 26451,
"author": "Matt McMinn",
"author_id": 1322,
"author_profile": "https://Stackoverflow.com/users/1322",
"pm_score": 2,
"selected": false,
"text": "<pre><code>[01:22 PM] matt@Lunchbox:~/tmp/ba$\nls\ntemplate_x.txt template_y.txt template_z.txt\n\n[01:22 PM] matt@Lunchbox:~/tmp/ba$\nfor i in template_*.txt ; do mv $i foo${i:8}; done\n\n[01:22 PM] matt@Lunchbox:~/tmp/ba$\nls\nfoo_x.txt foo_y.txt foo_z.txt\n</code></pre>\n"
},
{
"answer_id": 26456,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": true,
"text": "<pre>\nfor f in template_*.txt; do cp $f foo_${f#template_}; done\n</pre>\n"
},
{
"answer_id": 31349,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another way to do it:</p>\n\n<pre><code>$ ls template_*.txt | sed -e 's/^template\\(.*\\)$/cp template\\1 foo\\1/' | ksh -sx\n</code></pre>\n\n<p>I've always been impressed with the ImageMagick <a href=\"http://www.imagemagick.org/script/convert.php\" rel=\"nofollow noreferrer\">convert</a> program that does what you expect with image formats:</p>\n\n<pre><code>$ convert rose.jpg rose.png\n</code></pre>\n\n<p>It has a sister program that allows batch conversions:</p>\n\n<pre><code>$ mogrify -format png *.jpg\n</code></pre>\n\n<p>Obviously these are limited to image conversions, but they have interesting command line interfaces.</p>\n"
},
{
"answer_id": 63980,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 1,
"selected": false,
"text": "<p>The command <code>mmv</code> (available in <a href=\"http://packages.debian.org/etch/mmv\" rel=\"nofollow noreferrer\">Debian</a> or <a href=\"http://pdb.finkproject.org/pdb/package.php/mmv\" rel=\"nofollow noreferrer\">Fink</a> or easy to compile yourself) was created precisely for this task. With the plain Bash solution, I always have to look up the documentation about variable expansion. But <code>mmv</code> is much simpler to use, quite close to \"awesomeness\"! ;-)</p>\n\n<p>Your example would be:</p>\n\n<pre><code>mcp \"template_*.txt\" \"foo_#1.txt\"\n</code></pre>\n\n<p><code>mmv</code> can handle more complex patterns as well and it has some sanity checks, for example, it will make sure none of the files in the destination set appear in the source set (so you can't accidentally overwrite files).</p>\n"
},
{
"answer_id": 89102,
"author": "Roberto Bonvallet",
"author_id": 13169,
"author_profile": "https://Stackoverflow.com/users/13169",
"pm_score": 2,
"selected": false,
"text": "<p>My preferred way:</p>\n\n<pre><code>for f in template_*.txt\ndo\n cp $f ${f/template/foo}\ndone\n</code></pre>\n\n<p>The \"I-don't-remember-the-substitution-syntax\" way:</p>\n\n<pre><code>for i in x y z\ndo\n cp template_$i foo_$\ndone\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] | Say I have three files (template\_\*.txt):
* template\_x.txt
* template\_y.txt
* template\_z.txt
I want to copy them to three new files (foo\_\*.txt).
* foo\_x.txt
* foo\_y.txt
* foo\_z.txt
Is there some simple way to do that with one command, e.g.
`cp --enableAwesomeness template_*.txt foo_*.txt` | ```
for f in template_*.txt; do cp $f foo_${f#template_}; done
``` |
26,450 | <p>Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?</p>
<ul>
<li>Doing <code>session.contains(obj)</code> seems to only return true if the session contains that exact object, not another object with the same ID.</li>
<li>Using <code>merge(obj)</code> throws an exception if the object is new</li>
</ul>
| [
{
"answer_id": 26468,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried calling .SaveOrUpdateCopy()? \nIt should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).</p>\n\n<p>Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your \"new\" object.\nThis should be easy enough to do:</p>\n\n<pre><code>IPersistable entity = Whatever(); // This is the object we're trying to update\n// (IPersistable has an id field)\nsession.Evict(session.Get(entity.GetType(), entity.Id));\nsession.SaveOrUpdate(entity);\n</code></pre>\n\n<p>Although the above code could probably do with some null checking for the .Get() call.</p>\n"
},
{
"answer_id": 40768,
"author": "Georgy Bolyuba",
"author_id": 4052,
"author_profile": "https://Stackoverflow.com/users/4052",
"pm_score": 1,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>session.replicate(entity, ReplicationMode.OVERWRITE);\n</code></pre>\n\n<p>?</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2875/"
] | Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?
* Doing `session.contains(obj)` seems to only return true if the session contains that exact object, not another object with the same ID.
* Using `merge(obj)` throws an exception if the object is new | Have you tried calling .SaveOrUpdateCopy()?
It should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).
Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object.
This should be easy enough to do:
```
IPersistable entity = Whatever(); // This is the object we're trying to update
// (IPersistable has an id field)
session.Evict(session.Get(entity.GetType(), entity.Id));
session.SaveOrUpdate(entity);
```
Although the above code could probably do with some null checking for the .Get() call. |
26,455 | <p>Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach?</p>
<p>I came across the <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="noreferrer">Design by Contract</a> approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd.</p>
| [
{
"answer_id": 26484,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 5,
"selected": true,
"text": "<p>I can't recommend it highly enough. It's particularly nice if you have a suite that takes inline documentation contract specifications, like so:</p>\n\n<pre><code>// @returns null iff x = 0\npublic foo(int x) {\n ...\n}\n</code></pre>\n\n<p>and turns them into generated unit tests, like so:</p>\n\n<pre><code>public test_foo_returns_null_iff_x_equals_0() {\n assertNull foo(0);\n}\n</code></pre>\n\n<p>That way, you can actually see the tests you're running, but they're auto-generated. Generated tests shouldn't be checked into source control, by the way.</p>\n"
},
{
"answer_id": 26485,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 2,
"selected": false,
"text": "<p>It's absolutely foolish to not design by contract when doing anything in an SOA realm, and it's always helpful if you're working on any sort of modular work, where bits & pieces might be swapped out later on, especially if any black boxen are involved.</p>\n"
},
{
"answer_id": 26542,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 1,
"selected": false,
"text": "<p>In lieu of more expressive type systems, I would absolutely use design by contract on military grade projects.</p>\n\n<p>For weakly typed languages or languages with dynamic scope (PHP, JavaScript), functional contracts are also very handy.</p>\n\n<p>For everything else, I would toss it aside an rely upon beta testers and unit tests.</p>\n\n<p><a href=\"https://stackoverflow.com/users/1190/gaius\">Gaius</a>: A Null Pointer exception gets thrown for you automatically by the runtime, there is no benefit to testing that stuff in the function prologue. If you are more interested in documentation, then I would use annotations that can be used with static analyzers and the like (to make sure the code isn't breaking your annotations for example).</p>\n\n<p>A stronger type system coupled with Design by Contract seems to be the way to go. Take a look at <a href=\"http://research.microsoft.com/SpecSharp/\" rel=\"nofollow noreferrer\">Spec#</a> for an example:</p>\n\n<blockquote>\n <p>The Spec# programming language. Spec#\n is an extension of the object-oriented\n language C#. It extends the type\n system to include non-null types and\n checked exceptions. It provides\n method contracts in the form of pre-\n and postconditions as well as object\n invariants.</p>\n</blockquote>\n"
},
{
"answer_id": 26890,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "<p>I don't actually use Design by Contract, on a daily basis. I do, however know that it has been incorporated into the <a href=\"http://www.digitalmars.com/d/2.0/dbc.html\" rel=\"nofollow noreferrer\">D</a> language, as part of the language.</p>\n"
},
{
"answer_id": 26965,
"author": "popopome",
"author_id": 1556,
"author_profile": "https://Stackoverflow.com/users/1556",
"pm_score": 2,
"selected": false,
"text": "<p>If you look into STL, boost, MFC, ATL and many open source projects, you can see there are so many ASSERTION statements and that makes project going further more safely.</p>\n\n<p>Design-By-Contract! It really works in real product.</p>\n"
},
{
"answer_id": 34811,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/338/frank-krueger\">Frank Krueger</a> writes:</p>\n\n<blockquote>\n <p>Gaius: A Null Pointer exception gets thrown for you automatically by the runtime, there is no benefit to testing that stuff in the function prologue.</p>\n</blockquote>\n\n<p>I have two responses to this:</p>\n\n<ol>\n<li><p>Null was just an example. For square(x), I'd want to test that the square root of the result is (approximately) the value of the parameter. For setters, I'd want to test that the value actually changed. For atomic operations, I'd want to check that all component operations succeeded or all failed (really one test for success and n tests for failure). For factory methods in weakly-typed languages, I want to check that the right kind of object is returned. The list goes on and on. Basically, anything that can be tested in one line of code is a very good candidate for a code contract in a prologue comment.</p></li>\n<li><p>I disagree that you shouldn't test things because they generate runtime exceptions. If anything, you <em>should</em> test things that might generate runtime exceptions. I like runtime exceptions because they make the system <a href=\"http://en.wikipedia.org/wiki/Fail-fast\" rel=\"nofollow noreferrer\">fail fast</a>, which helps debugging. But the <code>null</code> in the example was a result value for some possible input. There's an argument to be made for never returning <code>null</code>, but if you're going to, you should test it.</p></li>\n</ol>\n"
},
{
"answer_id": 123667,
"author": "Ged Byrne",
"author_id": 10167,
"author_profile": "https://Stackoverflow.com/users/10167",
"pm_score": 4,
"selected": false,
"text": "<p>You really get to appreciate design by contract when you have an interface between to applications that have to talk to each other.</p>\n\n<p>Without contracts this situation quickly becomes a game of blame tennis. The teams keep knocking accusations back and forth and huge amounts of time get wasted.</p>\n\n<p>With a contract, the blame is clear.</p>\n\n<p>Did the caller satisfy the preconditions? If not the client team need to fix it.</p>\n\n<p>Given a valid request, did the receiver satisfy the post conditions? If not the server team need to fix that.</p>\n\n<p>Did both parties adhere to the contract, but the result is unsatisfactory? The contract is insufficient and the issue needs to be escalated.</p>\n\n<p>For this you don't need to have the contracts implemented in the form of assertions, you just need to make sure they are documented and agreed on by all parties.</p>\n"
},
{
"answer_id": 1526669,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Both Unit testing and Design by Contract are valuable test approaches in my experince.</p>\n\n<p>I have tried using Design by Contract in a System Automatic Testing framework and my experience is that is gives a flexibility and possibilities not easily obtained by unit testing. For example its possible to run longer sequence and verify that \nthe respons times are within limits every time an action is executed.</p>\n\n<p>Looking at the presentations at InfoQ it appears that Design by contract is a valuable addition to the conventional Unit tests in the integration phase of components.\nFor example it possible to create a mock interface first and then use the component after-\nor when a new version of a component is released.</p>\n\n<p>I have not found a toolkit covering all my design requirement to design by contract testing\nin the .Net/Microsoft platform.</p>\n"
},
{
"answer_id": 2158480,
"author": "Verhagen",
"author_id": 261378,
"author_profile": "https://Stackoverflow.com/users/261378",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it does! Actually a few years ago, I designed a little framework for Argument Validation. I was doing a SOA project, in which the different back-end system, did all kind of validation and checking. But to increase response times (in cases where the input was invalid, and to reduce to load those back-end systems), we started to validate the input parameters of the provided services. Not only for Not Null, but also for String patterns. Or values from within sets. And also the cases where parameters had dependencies between them.</p>\n\n<p>Now I realize we implemented at that time a small design by contract framework :)</p>\n\n<p>Here is the link for those who are interested in the small <a href=\"http://java-arg-val.sourceforge.net/\" rel=\"nofollow noreferrer\">Java Argument Validation</a> framework. Which is implemented as plain Java solution.</p>\n"
},
{
"answer_id": 4191245,
"author": "necode",
"author_id": 414678,
"author_profile": "https://Stackoverflow.com/users/414678",
"pm_score": 1,
"selected": false,
"text": "<p>I find it telling that Go programming language has no constructs that make design by contract possible. panic/defer/recover aren't exactly that as defer and recover logic make it possible to ignore panic, IOW to ignore broken contract. What's needed at very least is some form of unrecoverable panic, which is assert really. Or, at best, direct language support of design by contract constructs (pre and post-conditions, implementation and class invariants). But given strong-headedness of language purists at the helm of Go ship, I give little change of any of this done.</p>\n\n<p>One can implement assert-like behaviour by checking for special assert error in last defer function in panicking function and calling runtime.Breakpoint() to dump stack during recovery. To be assert-like that behaviour needs to be conditional. Of course this approach fells apart when new defer function is added after the one doing assert. Which will happen in large project exactly at the wrong time, resulting in missed bugs.</p>\n\n<p>My point is that is that assert is useful in so many ways that having to dance around it may be a headache.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach?
I came across the [Design by Contract](http://en.wikipedia.org/wiki/Design_by_contract) approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd. | I can't recommend it highly enough. It's particularly nice if you have a suite that takes inline documentation contract specifications, like so:
```
// @returns null iff x = 0
public foo(int x) {
...
}
```
and turns them into generated unit tests, like so:
```
public test_foo_returns_null_iff_x_equals_0() {
assertNull foo(0);
}
```
That way, you can actually see the tests you're running, but they're auto-generated. Generated tests shouldn't be checked into source control, by the way. |
26,478 | <p>I'm having trouble getting the following to work in SQL Server 2k, but it works in 2k5:</p>
<pre><code>--works in 2k5, not in 2k
create view foo as
SELECT usertable.legacyCSVVarcharCol as testvar
FROM usertable
WHERE rsrcID in
( select val
from
dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, default)
)
--error message:
Msg 170, Level 15, State 1, Procedure foo, Line 4
Line 25: Incorrect syntax near '.'.
</code></pre>
<p>So, legacyCSVVarcharCol is a column containing comma-separated lists of INTs. I realize that this is a huge WTF, but this is legacy code, and there's nothing that can be done about the schema right now. Passing "testvar" as the argument to the function doesn't work in 2k either. In fact, it results in a slightly different (and even weirder error):</p>
<pre><code>Msg 155, Level 15, State 1, Line 8
'testvar' is not a recognized OPTIMIZER LOCK HINTS option.
</code></pre>
<p>Passing a hard-coded string as the argument to fnSplitStringToInt works in both 2k and 2k5.</p>
<p>Does anyone know why this doesn't work in 2k? Is this perhaps a known bug in the query planner? Any suggestions for how to make it work? Again, I realize that the real answer is "don't store CSV lists in your DB!", but alas, that's beyond my control.</p>
<p>Some sample data, if it helps:</p>
<pre><code>INSERT INTO usertable (legacyCSVVarcharCol) values ('1,2,3');
INSERT INTO usertable (legacyCSVVarcharCol) values ('11,13,42');
</code></pre>
<p>Note that the data in the table does not seem to matter since this is a syntax error, and it occurs even if usertable is completely empty.</p>
<p>EDIT: Realizing that perhaps the initial example was unclear, here are two examples, one of which works and one of which does not, which should highlight the problem that's occurring:</p>
<pre><code>--fails in sql2000, works in 2005
SELECT t1.*
FROM usertable t1
WHERE 1 in
(Select val
from
fnSplitStringToInt(t1.legacyCSVVarcharCol, ',')
)
--works everywhere:
SELECT t1.*
FROM usertable t1
WHERE 1 in
( Select val
from
fnSplitStringToInt('1,4,543,56578', ',')
)
</code></pre>
<p>Note that the only difference is the first argument to fnSplitStringToInt is a column in the case that fails in 2k and a literal string in the case that succeeds in both.</p>
| [
{
"answer_id": 26577,
"author": "wcm",
"author_id": 2173,
"author_profile": "https://Stackoverflow.com/users/2173",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think functions can have default values in functions in SS2K.</p>\n\n<p>What happens when you run this SQL in SS2K?</p>\n\n<pre><code>select val \nfrom dbo.fnSplitStringToInt('1,2,3', default)\n</code></pre>\n"
},
{
"answer_id": 49638,
"author": "MobyDX",
"author_id": 3923,
"author_profile": "https://Stackoverflow.com/users/3923",
"pm_score": 2,
"selected": true,
"text": "<p>Passing column-values to a table-valued user-defined function is not supported in SQL Server 2000, you can only use constants, so the following (simpler version) would also fail:</p>\n\n<pre><code>SELECT *, (SELECT TOP 1 val FROM dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, ','))\nFROM usertable\n</code></pre>\n\n<p>It will work on SQL Server 2005, though, as you have found out.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2327/"
] | I'm having trouble getting the following to work in SQL Server 2k, but it works in 2k5:
```
--works in 2k5, not in 2k
create view foo as
SELECT usertable.legacyCSVVarcharCol as testvar
FROM usertable
WHERE rsrcID in
( select val
from
dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, default)
)
--error message:
Msg 170, Level 15, State 1, Procedure foo, Line 4
Line 25: Incorrect syntax near '.'.
```
So, legacyCSVVarcharCol is a column containing comma-separated lists of INTs. I realize that this is a huge WTF, but this is legacy code, and there's nothing that can be done about the schema right now. Passing "testvar" as the argument to the function doesn't work in 2k either. In fact, it results in a slightly different (and even weirder error):
```
Msg 155, Level 15, State 1, Line 8
'testvar' is not a recognized OPTIMIZER LOCK HINTS option.
```
Passing a hard-coded string as the argument to fnSplitStringToInt works in both 2k and 2k5.
Does anyone know why this doesn't work in 2k? Is this perhaps a known bug in the query planner? Any suggestions for how to make it work? Again, I realize that the real answer is "don't store CSV lists in your DB!", but alas, that's beyond my control.
Some sample data, if it helps:
```
INSERT INTO usertable (legacyCSVVarcharCol) values ('1,2,3');
INSERT INTO usertable (legacyCSVVarcharCol) values ('11,13,42');
```
Note that the data in the table does not seem to matter since this is a syntax error, and it occurs even if usertable is completely empty.
EDIT: Realizing that perhaps the initial example was unclear, here are two examples, one of which works and one of which does not, which should highlight the problem that's occurring:
```
--fails in sql2000, works in 2005
SELECT t1.*
FROM usertable t1
WHERE 1 in
(Select val
from
fnSplitStringToInt(t1.legacyCSVVarcharCol, ',')
)
--works everywhere:
SELECT t1.*
FROM usertable t1
WHERE 1 in
( Select val
from
fnSplitStringToInt('1,4,543,56578', ',')
)
```
Note that the only difference is the first argument to fnSplitStringToInt is a column in the case that fails in 2k and a literal string in the case that succeeds in both. | Passing column-values to a table-valued user-defined function is not supported in SQL Server 2000, you can only use constants, so the following (simpler version) would also fail:
```
SELECT *, (SELECT TOP 1 val FROM dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, ','))
FROM usertable
```
It will work on SQL Server 2005, though, as you have found out. |
26,512 | <p>I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 26553,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>BindingUtils</code> to get notified when the <code>dataProvider</code> property of the combo box changes:</p>\n\n<pre><code>BindingUtils.bindSetter(comboBoxDataProviderChanged, comboBox, \"dataProvider\");\n</code></pre>\n\n<p><code>BindingUtils</code> lives in the <code>mx.binding.utils</code> package.</p>\n\n<p>I have a longer description of how to work with <code>BindingUtils</code> here: <a href=\"https://stackoverflow.com/questions/14247/flex-does-painless-programmatic-data-binding-exist#14261\">Does painless programmatic data binding exist?</a></p>\n"
},
{
"answer_id": 26563,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "<p>You can also listen for the <code>ResultEvent.RESULT</code> on the HTTPService, that would be called slightly before the combo box got populated I guess, but it might be good enough.</p>\n"
},
{
"answer_id": 26580,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a mx.binding.utils.ChangeWatcher as described <a href=\"http://www.adobe.com/livedocs/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=databinding_091_08.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 26647,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "<p>Where are you adding the listener compared to the loading of the data? Is it possible the data is being loaded, and the event fired, before you've added your listener?</p>\n"
},
{
"answer_id": 26695,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>@Herms</p>\n\n<p>The listener is definitely added before the web service call, here is an example of what my code look like (I simplified lots of things...):</p>\n\n<p>I have this flex component:</p>\n\n<pre>\n<code>\npublic class FooComboBox extends ComboBox\n{\n private var service:HTTPService = null;\n public function ProjectAutoComplete()\n {\n service = new HTTPService();\n service.url = Application.application.poxmlUrl;\n service.addEventListener(FaultEvent.FAULT,serviceFault);\n service.addEventListener(ResultEvent.RESULT,resultReturned);\n\n\n this.addEventListener(FlexEvent.DATA_CHANGE,dataChange);\n }\n public function init():void\n {\n var postdata:Object = {};\n postdata[\"key\"] = \"ProjectName\";\n postdata[\"accountId\"] = Application.application.accountId\n service.send(postdata);\n }\n private function resultReturned(event:ResultEvent):void\n {\n this.dataProvider = service.lastResult.Array.Element;\n // thought I could do it here...but no luck...\n }\n private function dataChange(e:FlexEvent):void\n {\n // combobox has been databound\n mx.controls.Alert.show(\"databound!\");\n }\n ...\n}\n</code>\n</pre>\n\n<p>and then in a mxml file I have the FooComboBox with id \"foo\" and I call:</p>\n\n<pre>\n<code>\nfoo.init();\n</code>\n</pre>\n\n<p>I need to execute some code after the combobox is <strong>completely</strong> databound...any ideas?</p>\n"
},
{
"answer_id": 26736,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe the event doesn't trigger when the data provider is first set? Try setting the data provider to an empty array in the constructor, so that it's definitely <em>changing</em> instead of just being initially assigned later in your resultReturned() method. I've no clue if that will help, but it's worth a shot.</p>\n\n<p>Also, you're setting the provider to lastResult.Array.Element. That looks a little suspicious to me, as the data provider should probably be an array. Granted, I have no clue what your data looks like, so what you have could very well be correct, but it's something I noticed that might be related. Maybe it should just be lastResult.Array?</p>\n"
},
{
"answer_id": 27467,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "<p>In your example code, try running <code>validateNow()</code> in the <code>resultReturned</code> method. That will force the combo box to commit its properties. The thing is that even though the property is set the new value isn't used until <code>commitProperties</code> is run, which it will do at the earliest on the next frame, <code>validateNow()</code> forces it to be done at once.</p>\n"
},
{
"answer_id": 3366706,
"author": "Shashi Penumarthy",
"author_id": 367464,
"author_profile": "https://Stackoverflow.com/users/367464",
"pm_score": 2,
"selected": false,
"text": "<p>Flex doesn't have a specific data-binding events in the way that say ASP .Net does. You have to watch for the dataProvider property like John says in the first answer, but not simply to the combobox or its dataProvider property. Let's say you have a setup like this:</p>\n\n<pre><code><!-- Assume you have extracted an XMLList out of the result \nand attached it to the collection -->\n<mx:HttpService id=\"svc\" result=\"col.source = event.result.Project\"/>\n<mx:XMLListCollection id=\"col\"/>\n\n<mx:ComboBox id=\"cbProject\" dataProvider=\"{col}\"/>\n</code></pre>\n\n<p>Now if you set a changewatcher like this:</p>\n\n<pre><code>// Strategy 1\nChangeWatcher.watch(cbProject, \"dataProvider\", handler) ;\n</code></pre>\n\n<p>your handler will <em>not</em> get triggered when the data comes back. Why? Because the <em>dataProvider</em> itself didn't change - its underlying collection did. To trigger that, you have to do this:</p>\n\n<pre><code>// Strategy 2\nChangeWatcher.watch(cbProject, [\"dataProvider\", \"source\"], handler) ;\n</code></pre>\n\n<p>Now, when your collection has updated, your handler will get triggered. If you want to make it work using Strategy 1, <em>don't</em> set your dataProvider in MXML. Rather, handle the <em>collectionChange</em> event of your XMLListCollection and in AS, over-write the dataProvider of the ComboBox.</p>\n\n<p>Are these exactly the same as a databound event? No, but I've used them and never had an issue. If you want to be <em>absolutely</em> sure your data <em>has</em> bound, just put a changeWatcher on the selectedItem property of your combobox and do your processing there. Just be prepared to have that event trigger multiple times and handle that appropriately.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.
How can I do this? | Flex doesn't have a specific data-binding events in the way that say ASP .Net does. You have to watch for the dataProvider property like John says in the first answer, but not simply to the combobox or its dataProvider property. Let's say you have a setup like this:
```
<!-- Assume you have extracted an XMLList out of the result
and attached it to the collection -->
<mx:HttpService id="svc" result="col.source = event.result.Project"/>
<mx:XMLListCollection id="col"/>
<mx:ComboBox id="cbProject" dataProvider="{col}"/>
```
Now if you set a changewatcher like this:
```
// Strategy 1
ChangeWatcher.watch(cbProject, "dataProvider", handler) ;
```
your handler will *not* get triggered when the data comes back. Why? Because the *dataProvider* itself didn't change - its underlying collection did. To trigger that, you have to do this:
```
// Strategy 2
ChangeWatcher.watch(cbProject, ["dataProvider", "source"], handler) ;
```
Now, when your collection has updated, your handler will get triggered. If you want to make it work using Strategy 1, *don't* set your dataProvider in MXML. Rather, handle the *collectionChange* event of your XMLListCollection and in AS, over-write the dataProvider of the ComboBox.
Are these exactly the same as a databound event? No, but I've used them and never had an issue. If you want to be *absolutely* sure your data *has* bound, just put a changeWatcher on the selectedItem property of your combobox and do your processing there. Just be prepared to have that event trigger multiple times and handle that appropriately. |
26,515 | <p>I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following:</p>
<pre><code>$query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30');
// Example 1
$query = $query->fetch_assoc();
// Example 2
$query_r = $query->fetch_assoc();
$query->free();
</code></pre>
<p>Now if I'm right Example 1 should be more efficient as <code>$query</code> is <code>unset</code> when I reassign it which should free any memory associated with it. However there is a method (<code>MySQLi_Result::free()</code>) which frees associated memory - is this the same thing?</p>
<p>If I don't call <code>::free()</code> to free any memory associated with the result but <code>unset</code> it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas?</p>
| [
{
"answer_id": 26537,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 4,
"selected": true,
"text": "<p>The <a href=\"http://us2.php.net/manual/en/mysqli-result.free.php\" rel=\"noreferrer\">manual</a> seems to suggest that you should still be using <code>free()</code> to release the memory. I believe the reasoning is that <code>free()</code> is freeing the memory in <em>MySQL</em>, not in PHP. Since PHP can't garbage-collect for MySQL, you need to call <code>free()</code>.</p>\n"
},
{
"answer_id": 31903,
"author": "John Douthat",
"author_id": 2774,
"author_profile": "https://Stackoverflow.com/users/2774",
"pm_score": 2,
"selected": false,
"text": "<p>Example 1 <strong>dissociates</strong> the $query variable from the MySQL result. The MySQL result still exists in memory, and will continue to exist and waste memory until garbage collection occurs.</p>\n\n<p>Example 2 <strong>frees</strong> the MySQL result immediately, releasing the used resources.</p>\n\n<p>However, since PHP pages are generally short-lived with small result-sets, the memory saved is trivial. You will not notice a slowdown unless you leave <strong>a ton</strong> of results in memory over a long period of time on pages that run for a long time.</p>\n\n<p>Brian,\nPHP <em>can</em> garbage collect the MySQL result, it just doesn't happen immediately.\nThe result lives in PHP's memory pool, not in the MySQL server's.</p>\n\n<p>(the locality of memory when using unbuffered queries is slightly different, but they're so rarely used in PHP as to not be worth mentioning) </p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] | I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following:
```
$query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30');
// Example 1
$query = $query->fetch_assoc();
// Example 2
$query_r = $query->fetch_assoc();
$query->free();
```
Now if I'm right Example 1 should be more efficient as `$query` is `unset` when I reassign it which should free any memory associated with it. However there is a method (`MySQLi_Result::free()`) which frees associated memory - is this the same thing?
If I don't call `::free()` to free any memory associated with the result but `unset` it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas? | The [manual](http://us2.php.net/manual/en/mysqli-result.free.php) seems to suggest that you should still be using `free()` to release the memory. I believe the reasoning is that `free()` is freeing the memory in *MySQL*, not in PHP. Since PHP can't garbage-collect for MySQL, you need to call `free()`. |
26,522 | <p>Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like:</p>
<pre><code>[0, 0, 0] = 2
[0, 0, 1] = 32
</code></pre>
<p>And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead?</p>
| [
{
"answer_id": 26546,
"author": "Gabriël",
"author_id": 2104,
"author_profile": "https://Stackoverflow.com/users/2104",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/2ca85aa4-0672-40ad-b780-e181b28fcd80/\" rel=\"nofollow noreferrer\">Take a look at this:</a> might helpful for you.</p>\n"
},
{
"answer_id": 26582,
"author": "Jake Pearson",
"author_id": 632,
"author_profile": "https://Stackoverflow.com/users/632",
"pm_score": 3,
"selected": true,
"text": "<p>Thanks for the answer, here is what I wrote while I waited:</p>\n\n<pre><code>public static string Format(Array array)\n{\n var builder = new StringBuilder();\n builder.AppendLine(\"Count: \" + array.Length);\n var counter = 0;\n\n var dimensions = new List<int>();\n for (int i = 0; i < array.Rank; i++)\n {\n dimensions.Add(array.GetUpperBound(i) + 1);\n }\n\n foreach (var current in array)\n {\n var index = \"\";\n var remainder = counter;\n foreach (var bound in dimensions)\n {\n index = remainder % bound + \", \" + index;\n remainder = remainder / bound;\n }\n index = index.Substring(0, index.Length - 2);\n\n builder.AppendLine(\" [\" + index + \"] \" + current);\n counter++;\n }\n return builder.ToString();\n}\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632/"
] | Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like:
```
[0, 0, 0] = 2
[0, 0, 1] = 32
```
And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead? | Thanks for the answer, here is what I wrote while I waited:
```
public static string Format(Array array)
{
var builder = new StringBuilder();
builder.AppendLine("Count: " + array.Length);
var counter = 0;
var dimensions = new List<int>();
for (int i = 0; i < array.Rank; i++)
{
dimensions.Add(array.GetUpperBound(i) + 1);
}
foreach (var current in array)
{
var index = "";
var remainder = counter;
foreach (var bound in dimensions)
{
index = remainder % bound + ", " + index;
remainder = remainder / bound;
}
index = index.Substring(0, index.Length - 2);
builder.AppendLine(" [" + index + "] " + current);
counter++;
}
return builder.ToString();
}
``` |
26,547 | <p>Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it?</p>
<p>Basic detection can be done with the URL itself, such as “<a href="http://myblog.blogger.com" rel="nofollow noreferrer">http://myblog.blogger.com</a>” etc. But what if it's self hosted?</p>
<p>I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.</p>
| [
{
"answer_id": 26579,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 1,
"selected": false,
"text": "<p>Some blogs provide a Generator meta tag - e.g. Wordpress - you could find out if there's any exceptions to this.</p>\n\n<p>You'll have to be careful how you detect it though, Google surprised me with this line:</p>\n\n<pre><code><meta content='blogger' name='generator'/>\n</code></pre>\n\n<p>Single quotes are blasphemy.</p>\n"
},
{
"answer_id": 26589,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 3,
"selected": true,
"text": "<p>Many (most?) blogs will have a meta tag for \"generator\" which will list the blog engine. For example a blogger blog will contain the following meta tag: </p>\n\n<pre><code><meta name=\"generator\" content=\"Blogger\" /> \n</code></pre>\n\n<p>My Subtext blog shows the following generator meta tag: </p>\n\n<pre><code><meta name=\"Generator\" content=\"Subtext Version 1.9.5.177\" /> \n</code></pre>\n\n<p>This meta tag would be the first place to look. For blogs that don't set this meta tag in the source, you'd have to resort to looking for patterns to determine the blog type. </p>\n"
},
{
"answer_id": 26634,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 1,
"selected": false,
"text": "<p>To determine other patterns to look for in determining the blogging engine (for those that don't have a generator meta tag), you'd basically just look through the source to determine something specific to that blog type. You'd also need to compare this across multiple blogs of that type as you want to make sure that it's not something specific to the skin or theme in use on the blog only. </p>\n\n<p>Another thought would be to read the docs of the various common blogging engine to know how to discover the location of it's paths to things like MetaWebLog API, etc. IIRC, Live Writer has built-in support for the most common types, the rest are categorized \"MetaWebLog API Blog\" or something.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it?
Basic detection can be done with the URL itself, such as “<http://myblog.blogger.com>” etc. But what if it's self hosted?
I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language. | Many (most?) blogs will have a meta tag for "generator" which will list the blog engine. For example a blogger blog will contain the following meta tag:
```
<meta name="generator" content="Blogger" />
```
My Subtext blog shows the following generator meta tag:
```
<meta name="Generator" content="Subtext Version 1.9.5.177" />
```
This meta tag would be the first place to look. For blogs that don't set this meta tag in the source, you'd have to resort to looking for patterns to determine the blog type. |
26,551 | <p>I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.</p>
<p>Here's what the command line looks like:</p>
<pre><code>test.cmd admin P@55w0rd > test-log.txt
</code></pre>
| [
{
"answer_id": 26556,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 6,
"selected": false,
"text": "<p>Yep, and just don't forget to use variables like <code>%%1</code> when using <code>if</code> and <code>for</code> and the gang.</p>\n\n<p>If you forget the double <code>%</code>, then you will be substituting in (possibly null) command line arguments and you will receive some pretty confusing error messages.</p>\n"
},
{
"answer_id": 26702,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 10,
"selected": false,
"text": "<p>Another useful tip is to use <code>%*</code> to mean "all". For example:</p>\n<pre><code>echo off\nset arg1=%1\nset arg2=%2\nshift\nshift\nfake-command /u %arg1% /p %arg2% %*\n</code></pre>\n<p>When you run:</p>\n<pre><code>test-command admin password foo bar\n</code></pre>\n<p>The above batch file will run:</p>\n<pre><code>fake-command /u admin /p password admin password foo bar\n</code></pre>\n<p>I may have the syntax slightly wrong, but this is the general idea.</p>\n"
},
{
"answer_id": 26742,
"author": "thelsdj",
"author_id": 163,
"author_profile": "https://Stackoverflow.com/users/163",
"pm_score": 7,
"selected": false,
"text": "<p>If you want to intelligently handle missing parameters you can do something like:</p>\n\n<pre><code>IF %1.==. GOTO No1\nIF %2.==. GOTO No2\n... do stuff...\nGOTO End1\n\n:No1\n ECHO No param 1\nGOTO End1\n:No2\n ECHO No param 2\nGOTO End1\n\n:End1\n</code></pre>\n"
},
{
"answer_id": 92057,
"author": "Keng",
"author_id": 730,
"author_profile": "https://Stackoverflow.com/users/730",
"pm_score": 9,
"selected": true,
"text": "<p>Here's how I did it:</p>\n\n<pre><code>@fake-command /u %1 /p %2\n</code></pre>\n\n<p>Here's what the command looks like:</p>\n\n<pre><code>test.cmd admin P@55w0rd > test-log.txt\n</code></pre>\n\n<p>The <code>%1</code> applies to the first parameter the <code>%2</code> (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.</p>\n"
},
{
"answer_id": 4913598,
"author": "SvenVP",
"author_id": 605296,
"author_profile": "https://Stackoverflow.com/users/605296",
"pm_score": 2,
"selected": false,
"text": "<p>Make a new batch file (example: openclass.bat) and write this line in the file:</p>\n\n<pre><code>java %~n1\n</code></pre>\n\n<p>Then place the batch file in, let's say, the system32 folder, go to your Java class file, right click, Properties, Open with..., then find your batch file, select it and that's that...</p>\n\n<p>It works for me.</p>\n\n<p>PS: I can't find a way to close the cmd window when I close the Java class. For now...</p>\n"
},
{
"answer_id": 5493124,
"author": "jeb",
"author_id": 463115,
"author_profile": "https://Stackoverflow.com/users/463115",
"pm_score": 7,
"selected": false,
"text": "<p>Accessing batch parameters can be simple with %1, %2, ... %9 or also %*,<br>\nbut only if the content is simple. </p>\n\n<p>There is no simple way for complex contents like <code>\"&\"^&</code>, as it's not possible to access %1 without producing an error. </p>\n\n<pre><code>set var=%1\nset \"var=%1\"\nset var=%~1\nset \"var=%~1\"\n</code></pre>\n\n<p>The lines expand to </p>\n\n<pre><code>set var=\"&\"&\nset \"var=\"&\"&\"\nset var=\"&\"&\nset \"var=\"&\"&\"\n</code></pre>\n\n<p>And each line fails, as one of the <code>&</code> is outside of the quotes.</p>\n\n<p>It can be solved with reading from a temporary file a <strong>remarked</strong> version of the parameter.</p>\n\n<pre><code>@echo off\nSETLOCAL DisableDelayedExpansion\n\nSETLOCAL\nfor %%a in (1) do (\n set \"prompt=\"\n echo on\n for %%b in (1) do rem * #%1#\n @echo off\n) > param.txt\nENDLOCAL\n\nfor /F \"delims=\" %%L in (param.txt) do (\n set \"param1=%%L\"\n)\nSETLOCAL EnableDelayedExpansion\nset \"param1=!param1:*#=!\"\nset \"param1=!param1:~0,-2!\"\necho %%1 is '!param1!'\n</code></pre>\n\n<p>The trick is to enable <code>echo on</code> and expand the %1 after a <code>rem</code> statement (works also with <code>%2 .. %*</code>).<br>\nSo even <code>\"&\"&</code> could be echoed without producing an error, as it is remarked. </p>\n\n<p>But to be able to redirect the output of the <code>echo on</code>, you need the two for-loops.</p>\n\n<p>The extra characters <code>* #</code> are used to be safe against contents like <code>/?</code> (would show the help for <code>REM</code>).<br>\nOr a caret ^ at the line end could work as a multiline character, even in after a <code>rem</code>. </p>\n\n<p>Then reading the <strong>rem parameter</strong> output from the file, but carefully.<br>\nThe FOR /F should work with delayed expansion off, else contents with \"!\" would be destroyed.<br>\nAfter removing the extra characters in <code>param1</code>, you got it.</p>\n\n<p>And to use <code>param1</code> in a safe way, enable the delayed expansion.</p>\n"
},
{
"answer_id": 10219730,
"author": "DearWebby",
"author_id": 1342715,
"author_profile": "https://Stackoverflow.com/users/1342715",
"pm_score": 6,
"selected": false,
"text": "<p>There is no need to complicate it. It is simply command %1 %2 parameters, for example,</p>\n\n<pre><code>@echo off\n\nxcopy %1 %2 /D /E /C /Q /H /R /K /Y /Z\n\necho copied %1 to %2\n\npause\n</code></pre>\n\n<p>The \"pause\" displays what the batch file has done and waits for you to hit the ANY key. Save that as xx.bat in the Windows folder.</p>\n\n<p>To use it, type, for example:</p>\n\n<pre><code>xx c:\\f\\30\\*.* f:\\sites\\30\n</code></pre>\n\n<p>This batch file takes care of all the necessary parameters, like copying only files, that are newer, etc. I have used it since before Windows. If you like seeing the names of the files, as they are being copied, leave out the <code>Q</code> parameter.</p>\n"
},
{
"answer_id": 19985230,
"author": "CMS_95",
"author_id": 2358955,
"author_profile": "https://Stackoverflow.com/users/2358955",
"pm_score": 3,
"selected": false,
"text": "<p>To refer to a set variable in command line you would need to use <code>%a%</code> so for example:</p>\n\n<pre><code>set a=100 \necho %a% \nrem output = 100 \n</code></pre>\n\n<p>Note: This works for Windows 7 pro.</p>\n"
},
{
"answer_id": 22397352,
"author": "rightcodeatrighttime",
"author_id": 3414206,
"author_profile": "https://Stackoverflow.com/users/3414206",
"pm_score": 5,
"selected": false,
"text": "<pre><code>@ECHO OFF\n:Loop\nIF \"%1\"==\"\" GOTO Continue\nSHIFT\nGOTO Loop\n:Continue\n</code></pre>\n\n<p>Note: IF <code>\"%1\"==\"\"</code> will cause problems if <code>%1</code> is enclosed in quotes itself.</p>\n\n<p>In that case, use <code>IF [%1]==[]</code> or, in NT 4 (SP6) and later only, <code>IF \"%~1\"==\"\"</code> instead.</p>\n"
},
{
"answer_id": 27118914,
"author": "Amr Ali",
"author_id": 4208440,
"author_profile": "https://Stackoverflow.com/users/4208440",
"pm_score": 5,
"selected": false,
"text": "<pre><code>FOR %%A IN (%*) DO (\n REM Now your batch file handles %%A instead of %1\n REM No need to use SHIFT anymore.\n ECHO %%A\n)\n</code></pre>\n\n<p>This loops over the batch parameters (%*) either they are quoted or not, then echos each parameter. </p>\n"
},
{
"answer_id": 34550007,
"author": "Love and peace - Joe Codeswell",
"author_id": 601770,
"author_profile": "https://Stackoverflow.com/users/601770",
"pm_score": 5,
"selected": false,
"text": "<p>Let's keep this simple.</p>\n\n<p>Here is the .cmd file.</p>\n\n<pre><code>@echo off\nrem this file is named echo_3params.cmd\necho %1\necho %2\necho %3\nset v1=%1\nset v2=%2\nset v3=%3\necho v1 equals %v1%\necho v2 equals %v2%\necho v3 equals %v3%\n</code></pre>\n\n<p>Here are 3 calls from the command line.</p>\n\n<pre><code>C:\\Users\\joeco>echo_3params 1abc 2 def 3 ghi\n1abc\n2\ndef\nv1 equals 1abc\nv2 equals 2\nv3 equals def\n\nC:\\Users\\joeco>echo_3params 1abc \"2 def\" \"3 ghi\"\n1abc\n\"2 def\"\n\"3 ghi\"\nv1 equals 1abc\nv2 equals \"2 def\"\nv3 equals \"3 ghi\"\n\nC:\\Users\\joeco>echo_3params 1abc '2 def' \"3 ghi\"\n1abc\n'2\ndef'\nv1 equals 1abc\nv2 equals '2\nv3 equals def'\n\nC:\\Users\\joeco>\n</code></pre>\n"
},
{
"answer_id": 35445653,
"author": "Evan Kennedy",
"author_id": 1572938,
"author_profile": "https://Stackoverflow.com/users/1572938",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote a simple read_params script that can be called as a function (or external <code>.bat</code>) and will put all variables into the current environment. It won't modify the original parameters because the function is being <code>call</code>ed with a copy of the original parameters.</p>\n\n<p>For example, given the following command:</p>\n\n<pre><code>myscript.bat some -random=43 extra -greeting=\"hello world\" fluff\n</code></pre>\n\n<p><code>myscript.bat</code> would be able to use the variables after calling the function:</p>\n\n<pre><code>call :read_params %*\n\necho %random%\necho %greeting%\n</code></pre>\n\n<p>Here's the function:</p>\n\n<pre><code>:read_params\nif not %1/==/ (\n if not \"%__var%\"==\"\" (\n if not \"%__var:~0,1%\"==\"-\" (\n endlocal\n goto read_params\n )\n endlocal & set %__var:~1%=%~1\n ) else (\n setlocal & set __var=%~1\n )\n shift\n goto read_params\n)\nexit /B\n</code></pre>\n\n<hr>\n\n<p><strong>Limitations</strong></p>\n\n<ul>\n<li>Cannot load arguments with no value such as <code>-force</code>. You could use <code>-force=true</code> but I can't think of a way to allow blank values without knowing a list of parameters ahead of time that won't have a value.</li>\n</ul>\n\n<hr>\n\n<p><strong>Changelog</strong></p>\n\n<ul>\n<li><strong>2/18/2016</strong>\n\n<ul>\n<li>No longer requires delayed expansion</li>\n<li>Now works with other command line arguments by looking for <code>-</code> before parameters.</li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 45070967,
"author": "kodybrown",
"author_id": 139793,
"author_profile": "https://Stackoverflow.com/users/139793",
"pm_score": 6,
"selected": false,
"text": "<p>A friend was asking me about this subject recently, so I thought I'd post how I handle command-line arguments in batch files.</p>\n<p>This technique has a bit of overhead as you'll see, but it makes my batch files very easy to understand and quick to implement. As well as supporting the following structures:</p>\n<pre><code>>template.bat [-f] [--flag] [--namedvalue value] arg1 [arg2][arg3][...]\n</code></pre>\n<p>The jist of it is having the <code>:init</code>, <code>:parse</code>, and <code>:main</code> functions.</p>\n<blockquote>\n<p>Example usage</p>\n</blockquote>\n<pre><code>>template.bat /?\ntest v1.23\nThis is a sample batch file template,\nproviding command-line arguments and flags.\n\nUSAGE:\ntest.bat [flags] "required argument" "optional argument"\n\n/?, --help shows this help\n/v, --version shows the version\n/e, --verbose shows detailed output\n-f, --flag value specifies a named parameter value\n\n>template.bat <- throws missing argument error\n(same as /?, plus..)\n**** ****\n**** MISSING "REQUIRED ARGUMENT" ****\n**** ****\n\n>template.bat -v\n1.23\n\n>template.bat --version\ntest v1.23\nThis is a sample batch file template,\nproviding command-line arguments and flags.\n\n>template.bat -e arg1\n**** DEBUG IS ON\nUnNamedArgument: "arg1"\nUnNamedOptionalArg: not provided\nNamedFlag: not provided\n\n>template.bat --flag "my flag" arg1 arg2\nUnNamedArgument: "arg1"\nUnNamedOptionalArg: "arg2"\nNamedFlag: "my flag"\n\n>template.bat --verbose "argument #1" --flag "my flag" second\n**** DEBUG IS ON\nUnNamedArgument: "argument #1"\nUnNamedOptionalArg: "second"\nNamedFlag: "my flag"\n</code></pre>\n<blockquote>\n<p>template.bat</p>\n</blockquote>\n<pre><code>@::!/dos/rocks\n@echo off\ngoto :init\n\n:header\n echo %__NAME% v%__VERSION%\n echo This is a sample batch file template,\n echo providing command-line arguments and flags.\n echo.\n goto :eof\n\n:usage\n echo USAGE:\n echo %__BAT_NAME% [flags] "required argument" "optional argument" \n echo.\n echo. /?, --help shows this help\n echo. /v, --version shows the version\n echo. /e, --verbose shows detailed output\n echo. -f, --flag value specifies a named parameter value\n goto :eof\n\n:version\n if "%~1"=="full" call :header & goto :eof\n echo %__VERSION%\n goto :eof\n\n:missing_argument\n call :header\n call :usage\n echo.\n echo **** ****\n echo **** MISSING "REQUIRED ARGUMENT" ****\n echo **** ****\n echo.\n goto :eof\n\n:init\n set "__NAME=%~n0"\n set "__VERSION=1.23"\n set "__YEAR=2017"\n\n set "__BAT_FILE=%~0"\n set "__BAT_PATH=%~dp0"\n set "__BAT_NAME=%~nx0"\n\n set "OptHelp="\n set "OptVersion="\n set "OptVerbose="\n\n set "UnNamedArgument="\n set "UnNamedOptionalArg="\n set "NamedFlag="\n\n:parse\n if "%~1"=="" goto :validate\n\n if /i "%~1"=="/?" call :header & call :usage "%~2" & goto :end\n if /i "%~1"=="-?" call :header & call :usage "%~2" & goto :end\n if /i "%~1"=="--help" call :header & call :usage "%~2" & goto :end\n\n if /i "%~1"=="/v" call :version & goto :end\n if /i "%~1"=="-v" call :version & goto :end\n if /i "%~1"=="--version" call :version full & goto :end\n\n if /i "%~1"=="/e" set "OptVerbose=yes" & shift & goto :parse\n if /i "%~1"=="-e" set "OptVerbose=yes" & shift & goto :parse\n if /i "%~1"=="--verbose" set "OptVerbose=yes" & shift & goto :parse\n\n if /i "%~1"=="--flag" set "NamedFlag=%~2" & shift & shift & goto :parse\n if /i "%~1"=="-f" set "NamedFlag=%~2" & shift & shift & goto :parse\n\n if not defined UnNamedArgument set "UnNamedArgument=%~1" & shift & goto :parse\n if not defined UnNamedOptionalArg set "UnNamedOptionalArg=%~1" & shift & goto :parse\n\n shift\n goto :parse\n\n:validate\n if not defined UnNamedArgument call :missing_argument & goto :end\n\n:main\n if defined OptVerbose (\n echo **** DEBUG IS ON\n )\n\n echo UnNamedArgument: "%UnNamedArgument%"\n\n if defined UnNamedOptionalArg echo UnNamedOptionalArg: "%UnNamedOptionalArg%"\n if not defined UnNamedOptionalArg echo UnNamedOptionalArg: not provided\n\n if defined NamedFlag echo NamedFlag: "%NamedFlag%"\n if not defined NamedFlag echo NamedFlag: not provided\n\n:end\n call :cleanup\n exit /B\n\n:cleanup\n REM The cleanup function is only really necessary if you\n REM are _not_ using SETLOCAL.\n set "__NAME="\n set "__VERSION="\n set "__YEAR="\n\n set "__BAT_FILE="\n set "__BAT_PATH="\n set "__BAT_NAME="\n\n set "OptHelp="\n set "OptVersion="\n set "OptVerbose="\n\n set "UnNamedArgument="\n set "UnNamedArgument2="\n set "NamedFlag="\n\n goto :eof\n</code></pre>\n"
},
{
"answer_id": 50653047,
"author": "Garret Wilson",
"author_id": 421049,
"author_profile": "https://Stackoverflow.com/users/421049",
"pm_score": 4,
"selected": false,
"text": "<p>Inspired by an <a href=\"https://stackoverflow.com/a/14298769/421049\">answer elsewhere</a> by @Jon, I have crafted a more general algorithm for extracting named parameters, optional values, and switches.</p>\n\n<p>Let us say that we want to implement a utility <code>foobar</code>. It requires an initial command. It has an optional parameter <code>--foo</code> which takes an <em>optional</em> value (which cannot be another parameter, of course); if the value is missing it defaults to <code>default</code>. It also has an optional parameter <code>--bar</code> which takes a <em>required</em> value. Lastly it can take a flag <code>--baz</code> with no value allowed. Oh, and these parameters can come in any order.</p>\n\n<p>In other words, it looks like this:</p>\n\n<pre><code>foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]\n</code></pre>\n\n<p>Here is a solution:</p>\n\n<pre><code>@ECHO OFF\nSETLOCAL\nREM FooBar parameter demo\nREM By Garret Wilson\n\nSET CMD=%~1\n\nIF \"%CMD%\" == \"\" (\n GOTO usage\n)\nSET FOO=\nSET DEFAULT_FOO=default\nSET BAR=\nSET BAZ=\n\nSHIFT\n:args\nSET PARAM=%~1\nSET ARG=%~2\nIF \"%PARAM%\" == \"--foo\" (\n SHIFT\n IF NOT \"%ARG%\" == \"\" (\n IF NOT \"%ARG:~0,2%\" == \"--\" (\n SET FOO=%ARG%\n SHIFT\n ) ELSE (\n SET FOO=%DEFAULT_FOO%\n )\n ) ELSE (\n SET FOO=%DEFAULT_FOO%\n )\n) ELSE IF \"%PARAM%\" == \"--bar\" (\n SHIFT\n IF NOT \"%ARG%\" == \"\" (\n SET BAR=%ARG%\n SHIFT\n ) ELSE (\n ECHO Missing bar value. 1>&2\n ECHO:\n GOTO usage\n )\n) ELSE IF \"%PARAM%\" == \"--baz\" (\n SHIFT\n SET BAZ=true\n) ELSE IF \"%PARAM%\" == \"\" (\n GOTO endargs\n) ELSE (\n ECHO Unrecognized option %1. 1>&2\n ECHO:\n GOTO usage\n)\nGOTO args\n:endargs\n\nECHO Command: %CMD%\nIF NOT \"%FOO%\" == \"\" (\n ECHO Foo: %FOO%\n)\nIF NOT \"%BAR%\" == \"\" (\n ECHO Bar: %BAR%\n)\nIF \"%BAZ%\" == \"true\" (\n ECHO Baz\n)\n\nREM TODO do something with FOO, BAR, and/or BAZ\nGOTO :eof\n\n:usage\nECHO FooBar\nECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]\nEXIT /B 1\n</code></pre>\n\n<ul>\n<li>Use <code>SETLOCAL</code> so that the variables don't escape into the calling environment.</li>\n<li>Don't forget to initialize the variables <code>SET FOO=</code>, etc. in case someone defined them in the calling environment.</li>\n<li>Use <code>%~1</code> to remove quotes.</li>\n<li>Use <code>IF \"%ARG%\" == \"\"</code> and not <code>IF [%ARG%] == []</code> because <code>[</code> and <code>]</code> don't play will at all with values ending in a space.</li>\n<li>Even if you <code>SHIFT</code> inside an <code>IF</code> block, the current args such as <code>%~1</code> don't get updated because they are determined when the <code>IF</code> is parsed. You could use <code>%~1</code> and <code>%~2</code> inside the <code>IF</code> block, but it would be confusing because you had a <code>SHIFT</code>. You could put the <code>SHIFT</code> at the end of the block for clarity, but that might get lost and/or confuse people as well. So \"capturing\" <code>%~1</code> and <code>%~1</code> outside the block seems best.</li>\n<li>You don't want to use a parameter in place of another parameter's optional value, so you have to check <code>IF NOT \"%ARG:~0,2%\" == \"--\"</code>.</li>\n<li>Be careful only to <code>SHIFT</code> when you <em>use</em> one of the parameters.</li>\n<li>The duplicate code <code>SET FOO=%DEFAULT_FOO%</code> is regrettable, but the alternative would be to add an <code>IF \"%FOO%\" == \"\" SET FOO=%DEFAULT_FOO%</code> outside the <code>IF NOT \"%ARG%\" == \"\"</code> block. However because this is still inside the <code>IF \"%PARAM%\" == \"--foo\"</code> block, the <code>%FOO%</code> value would have been evaluated and set before you ever entered the block, so you would never detect that <em>both</em> the <code>--foo</code> parameter was present <em>and also</em> that the <code>%FOO%</code> value was missing.</li>\n<li>Note that <code>ECHO Missing bar value. 1>&2</code> sends the error message to stderr.</li>\n<li>Want a blank line in a Windows batch file? You gotta use <code>ECHO:</code> or one of the variations.</li>\n</ul>\n"
},
{
"answer_id": 51156281,
"author": "Amol Patil",
"author_id": 1811749,
"author_profile": "https://Stackoverflow.com/users/1811749",
"pm_score": 2,
"selected": false,
"text": "<p>Simple solution(even though question is old)</p>\n\n<p>Test1.bat</p>\n\n<pre><code>echo off\necho \"Batch started\"\nset arg1=%1\necho \"arg1 is %arg1%\"\necho on\npause\n</code></pre>\n\n<p>CallTest1.bat</p>\n\n<pre><code>call \"C:\\Temp\\Test1.bat\" pass123\n</code></pre>\n\n<p>output</p>\n\n<pre><code>YourLocalPath>call \"C:\\Temp\\test.bat\" pass123\n\nYourLocalPath>echo off\n\"Batch started\"\n\"arg1 is pass123\"\n\nYourLocalPath>pause\nPress any key to continue . . .\n</code></pre>\n\n<p>Where YourLocalPath is current directory path. </p>\n\n<p>To keep things simple store the command param in variable and use variable for comparison. </p>\n\n<p>Its not just simple to write but its simple to maintain as well so if later some other person or you read your script after long period of time, it will be easy to understand and maintain.</p>\n\n<p>To write code inline : see other answers.</p>\n"
},
{
"answer_id": 54635244,
"author": "Io-oI",
"author_id": 8177207,
"author_profile": "https://Stackoverflow.com/users/8177207",
"pm_score": 3,
"selected": false,
"text": "\n<p><a href=\"https://i.stack.imgur.com/L2hkd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L2hkd.png\" alt=\"enter image description here\" /></a></p>\n<blockquote>\n<p><em>For to use looping get all arguments and in pure batch:</em></p>\n</blockquote>\n<p><strong>Obs:</strong> For using without: <strong><code>?*&|<></code></strong></p>\n<hr />\n<pre class=\"lang-bat prettyprint-override\"><code>@echo off && setlocal EnableDelayedExpansion\n\n for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && (\n call set "_arg_[!_cnt!]=!_arg_!" && for /l %%l in (!_cnt! 1 !_cnt!\n )do echo/ The argument n:%%l is: !_arg_[%%l]!\n )\n\ngoto :eof \n</code></pre>\n<blockquote>\n<p><em>Your code is ready to do something with the argument number where it needs, like...</em></p>\n</blockquote>\n\n<pre class=\"lang-bat prettyprint-override\"><code> @echo off && setlocal EnableDelayedExpansion\n\n for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!"\n \n fake-command /u !_arg_[1]! /p !_arg_[2]! > test-log.txt\n \n</code></pre>\n"
},
{
"answer_id": 58447844,
"author": "The Godfather",
"author_id": 2261656,
"author_profile": "https://Stackoverflow.com/users/2261656",
"pm_score": 5,
"selected": false,
"text": "<p>In batch file</p>\n<pre><code>set argument1=%1\nset argument2=%2\necho %argument1%\necho %argument2%\n</code></pre>\n<p><code>%1</code> and <code>%2</code> return the first and second argument values respectively.</p>\n<p>And in command line, pass the argument</p>\n<pre><code>Directory> batchFileName admin P@55w0rd \n</code></pre>\n<p>Output will be</p>\n<pre><code>admin\nP@55w0rd\n</code></pre>\n"
},
{
"answer_id": 64749745,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 2,
"selected": false,
"text": "<h2>Paired arguments</h2>\n<p>If you prefer passing the arguments in a key-value pair you can use something like this:</p>\n<pre><code>@echo off\n\nsetlocal enableDelayedExpansion\n\n::::: asigning arguments as a key-value pairs:::::::::::::\nset counter=0\nfor %%# in (%*) do ( \n set /a counter=counter+1\n set /a even=counter%%2\n \n if !even! == 0 (\n echo setting !prev! to %%#\n set "!prev!=%%~#"\n )\n set "prev=%%~#"\n)\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n:: showing the assignments\necho %one% %two% %three% %four% %five%\n\nendlocal\n</code></pre>\n<p>And an example :</p>\n<pre><code>c:>argumentsDemo.bat one 1 "two" 2 three 3 four 4 "five" 5\n1 2 3 4 5\n</code></pre>\n<h2>Predefined variables</h2>\n<p>You can also set some environment variables in advance. It can be done by setting them in the console or <a href=\"https://www.computerhope.com/issues/ch000549.htm\" rel=\"nofollow noreferrer\">setting them from my computer</a>:</p>\n<pre><code>@echo off\n\nif defined variable1 (\n echo %variable1%\n)\n\nif defined variable2 (\n echo %variable2%\n)\n</code></pre>\n<p>and calling it like:</p>\n<pre><code>c:\\>set variable1=1\n\nc:\\>set variable2=2\n\nc:\\>argumentsTest.bat\n1\n2\n</code></pre>\n<h2>File with listed values</h2>\n<p>You can also point to a file where the needed values are preset.\nIf this is the script:</p>\n<pre><code>@echo off\n\nsetlocal\n::::::::::\nset "VALUES_FILE=E:\\scripts\\values.txt"\n:::::::::::\n\n\nfor /f "usebackq eol=: tokens=* delims=" %%# in ("%VALUES_FILE%") do set "%%#"\n\necho %key1% %key2% %some_other_key%\n\nendlocal\n</code></pre>\n<p>and values file is this:</p>\n<pre><code>:::: use EOL=: in the FOR loop to use it as a comment\n\nkey1=value1\n\nkey2=value2\n\n:::: do not left spaces arround the =\n:::: or at the begining of the line\n\nsome_other_key=something else\n\nand_one_more=more\n</code></pre>\n<p>the output of calling it will be:</p>\n<blockquote>\n<p>value1 value2 something else</p>\n</blockquote>\n<p>Of course you can combine all approaches. Check also <a href=\"https://ss64.com/nt/syntax-args.html\" rel=\"nofollow noreferrer\">arguments syntax</a> , <a href=\"https://ss64.com/nt/shift.html\" rel=\"nofollow noreferrer\">shift</a></p>\n"
},
{
"answer_id": 67860255,
"author": "i Mr Oli i",
"author_id": 11199164,
"author_profile": "https://Stackoverflow.com/users/11199164",
"pm_score": 5,
"selected": false,
"text": "<p>Everyone has answered with really complex responses, however it is actually really simple. <code>%1 %2 %3</code> and so on are the arguements parsed to the file. <code>%1</code> is arguement 1, <code>%2</code> is arguement 2 and so on.</p>\n<p>So, if I have a bat script containing this:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>@echo off\necho %1\n</code></pre>\n<p>and when I run the batch script, I type in this:</p>\n<pre><code>C:> script.bat Hello\n</code></pre>\n<p>The script will simply output this:</p>\n<pre><code>Hello\n</code></pre>\n<p>This can be very useful for certain variables in a script, such as a name and age. So, if I have a script like this:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>@echo off\necho Your name is: %1\necho Your age is: %2\n</code></pre>\n<p>When I type in this:</p>\n<pre><code>C:> script.bat Oliver 1000\n</code></pre>\n<p>I get the output of this:</p>\n<pre><code>Your name is: Oliver\nYour age is: 1000\n</code></pre>\n"
},
{
"answer_id": 69130861,
"author": "Zimba",
"author_id": 5958708,
"author_profile": "https://Stackoverflow.com/users/5958708",
"pm_score": 0,
"selected": false,
"text": "<p>If you're worried about security/password theft (that led you to design this solution that takes login credentials at execution instead of static hard coding without the need for a database), then you could store the api or half the code of password decryption or decryption key in the program file, so at run time, user would type username/password in console to be hashed/decrypted before passed to program code for execution via <code>set /p</code>, if you're looking at user entering credentials at run time.</p>\n<p>If you're running a script to run your program with various user/password, then command line args will suit you.</p>\n<p>If you're making a test file to see the output/effects of different logins, then you could store all the logins in an encrypted file, to be passed as arg to test.cmd, unless you wanna sit at command line & type all the logins until finished.</p>\n<p>The number of args that can be supplied is <a href=\"https://learn.microsoft.com/en-us/troubleshoot/windows-client/shell-experience/command-line-string-limitation\" rel=\"nofollow noreferrer\">limited to total characters on command line</a>. To overcome this limitation, the previous paragraph trick is a workaround without risking exposure of user passwords.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.
Here's what the command line looks like:
```
test.cmd admin P@55w0rd > test-log.txt
``` | Here's how I did it:
```
@fake-command /u %1 /p %2
```
Here's what the command looks like:
```
test.cmd admin P@55w0rd > test-log.txt
```
The `%1` applies to the first parameter the `%2` (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way. |
26,567 | <p>I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information.</p>
<p>My idea was to do:</p>
<pre><code>Name: Address: City: State: ...
Jon Doe Addr1 ThisTown XX ...
Addr2
Addr3
-----------------------------------------------
Jane Doe Addr1 ThisTown XX ...
Addr2
Addr3
-----------------------------------------------
</code></pre>
<p>Is there some way to set a <code>textbox</code> to be multi-line (or the SQL result)? Have I missed something bloody obvious?</p>
<hr>
<p>The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried <code>/n</code>, <code>\n</code> (since I can never remember which is the correct slash to put), <code><br></code>, <code><br /></code> (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text. </p>
<p>Is there some way to get the results from the database as 3 lines of text/characters?
</p>
| [
{
"answer_id": 26953,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you need to set the CanGrow property to <strong>true</strong> on the Textbox. See <a href=\"http://msdn.microsoft.com/en-us/library/ms159116(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms159116(SQL.90).aspx</a> for some details.</p>\n"
},
{
"answer_id": 30409,
"author": "Pulsehead",
"author_id": 2156,
"author_profile": "https://Stackoverflow.com/users/2156",
"pm_score": 6,
"selected": true,
"text": "<p>Alter the report's text box to:</p>\n\n<pre><code>= Fields!Addr1.Value + VbCrLf + \n Fields!Addr2.Value + VbCrLf + \n Fields!Addr3.Value\n</code></pre>\n"
},
{
"answer_id": 1663604,
"author": "zhengokusa",
"author_id": 201212,
"author_profile": "https://Stackoverflow.com/users/201212",
"pm_score": 1,
"selected": false,
"text": "<p>link break do this </p>\n\n<p>chr(10)</p>\n"
},
{
"answer_id": 3582842,
"author": "Sam",
"author_id": 432755,
"author_profile": "https://Stackoverflow.com/users/432755",
"pm_score": 3,
"selected": false,
"text": "<p>I had an additional problem after putting in the <code>chr(10)</code> into the database.</p>\n\n<p>In the field (within the report) add in:</p>\n\n<pre><code>=REPLACE(Fields!Addr1.Value, CHR(10), vbCrLf)\n</code></pre>\n"
},
{
"answer_id": 6849829,
"author": "James An",
"author_id": 372645,
"author_profile": "https://Stackoverflow.com/users/372645",
"pm_score": 2,
"selected": false,
"text": "<p>Hitting Shift+Enter while typing in the textbox creates a line break.</p>\n"
},
{
"answer_id": 16785761,
"author": "Adriaan Davel",
"author_id": 776271,
"author_profile": "https://Stackoverflow.com/users/776271",
"pm_score": 3,
"selected": false,
"text": "<p>My data was captured in a SL application, needed this for the field expression</p>\n\n<pre><code>=REPLACE(Fields!Text.Value, CHR(13), vbCrLf)\n</code></pre>\n"
},
{
"answer_id": 41986590,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try this one :</p>\n\n<pre><code>= Fields!Field1.Value + System.Environment.NewLine + Fields!Field2.Value\n</code></pre>\n"
},
{
"answer_id": 45657284,
"author": "Hemal",
"author_id": 2270492,
"author_profile": "https://Stackoverflow.com/users/2270492",
"pm_score": 0,
"selected": false,
"text": "<p>In RDLC reports, you can convert a textbox to placehoder.\nThen right click that textbox placeholder, select placehoder properties and select HTML. Then for multiline to take effect, you have to insert <code><br/></code> tag between those lines.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2156/"
] | I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information.
My idea was to do:
```
Name: Address: City: State: ...
Jon Doe Addr1 ThisTown XX ...
Addr2
Addr3
-----------------------------------------------
Jane Doe Addr1 ThisTown XX ...
Addr2
Addr3
-----------------------------------------------
```
Is there some way to set a `textbox` to be multi-line (or the SQL result)? Have I missed something bloody obvious?
---
The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried `/n`, `\n` (since I can never remember which is the correct slash to put), `<br>`, `<br />` (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text.
Is there some way to get the results from the database as 3 lines of text/characters?
| Alter the report's text box to:
```
= Fields!Addr1.Value + VbCrLf +
Fields!Addr2.Value + VbCrLf +
Fields!Addr3.Value
``` |
26,595 | <p>Is there any difference between:</p>
<pre><code>if foo is None: pass
</code></pre>
<p>and</p>
<pre><code>if foo == None: pass
</code></pre>
<p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
| [
{
"answer_id": 26611,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 9,
"selected": true,
"text": "<p><code>is</code> always returns <code>True</code> if it compares the same object instance</p>\n\n<p>Whereas <code>==</code> is ultimately determined by the <code>__eq__()</code> method</p>\n\n<p>i.e.</p>\n\n<pre><code>\n>>> class Foo(object):\n def __eq__(self, other):\n return True\n\n>>> f = Foo()\n>>> f == None\nTrue\n>>> f is None\nFalse\n</code></pre>\n"
},
{
"answer_id": 26626,
"author": "borrego",
"author_id": 2772,
"author_profile": "https://Stackoverflow.com/users/2772",
"pm_score": 6,
"selected": false,
"text": "<p>You may want to read this <a href=\"http://mail.python.org/pipermail/python-list/2001-November/094920.html\" rel=\"noreferrer\">object identity and equivalence</a>.</p>\n\n<p>The statement 'is' is used for object identity, it checks if objects refer to the same instance (same address in memory).</p>\n\n<p>And the '==' statement refers to equality (same value).</p>\n"
},
{
"answer_id": 26654,
"author": "Stephen Pellicer",
"author_id": 360,
"author_profile": "https://Stackoverflow.com/users/360",
"pm_score": 3,
"selected": false,
"text": "<p>For None there shouldn't be a difference between equality (==) and identity (is). The NoneType probably returns identity for equality. Since None is the only instance you can make of NoneType (I think this is true), the two operations are the same. In the case of other types this is not always the case. For example:</p>\n\n<pre><code>list1 = [1, 2, 3]\nlist2 = [1, 2, 3]\nif list1==list2: print \"Equal\"\nif list1 is list2: print \"Same\"\n</code></pre>\n\n<p>This would print \"Equal\" since lists have a comparison operation that is not the default returning of identity.</p>\n"
},
{
"answer_id": 26963,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 3,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none#26698\">Jason</a>:</p>\n\n<blockquote>\n <p>I recommend using something more along the lines of</p>\n\n<pre><code>if foo:\n #foo isn't None\nelse:\n #foo is None\n</code></pre>\n</blockquote>\n\n<p>I don't like using \"if foo:\" unless foo truly represents a boolean value (i.e. 0 or 1). If foo is a string or an object or something else, \"if foo:\" may work, but it looks like a lazy shortcut to me. If you're checking to see if x is None, say \"if x is None:\".</p>\n"
},
{
"answer_id": 28067,
"author": "Tendayi Mawushe",
"author_id": 2979,
"author_profile": "https://Stackoverflow.com/users/2979",
"pm_score": 5,
"selected": false,
"text": "<p>A word of caution: </p>\n\n<pre><code>if foo:\n # do something\n</code></pre>\n\n<p>Is <strong>not</strong> exactly the same as:</p>\n\n<pre><code>if x is not None:\n # do something\n</code></pre>\n\n<p>The former is a boolean value test and can evaluate to false in different contexts. There are a number of things that represent false in a boolean value tests for example empty containers, boolean values. None also evaluates to false in this situation but other things do too.</p>\n"
},
{
"answer_id": 585491,
"author": "Mykola Kharechko",
"author_id": 69885,
"author_profile": "https://Stackoverflow.com/users/69885",
"pm_score": 4,
"selected": false,
"text": "<p><code>(ob1 is ob2)</code> equal to <code>(id(ob1) == id(ob2))</code></p>\n"
},
{
"answer_id": 2932590,
"author": "mthurlin",
"author_id": 39991,
"author_profile": "https://Stackoverflow.com/users/39991",
"pm_score": 4,
"selected": false,
"text": "<p>The reason <code>foo is None</code> is the preferred way is that you might be handling an object that defines its own <code>__eq__</code>, and that defines the object to be equal to None. So, always use <code>foo is None</code> if you need to see if it is infact <code>None</code>.</p>\n"
},
{
"answer_id": 5451786,
"author": "ncmathsadist",
"author_id": 467379,
"author_profile": "https://Stackoverflow.com/users/467379",
"pm_score": 1,
"selected": false,
"text": "<p>John Machin's conclusion that <code>None</code> is a singleton is a conclusion bolstered by this code.</p>\n\n<pre><code>>>> x = None\n>>> y = None\n>>> x == y\nTrue\n>>> x is y\nTrue\n>>> \n</code></pre>\n\n<p>Since <code>None</code> is a singleton, <code>x == None</code> and <code>x is None</code> would have the same result. However, in my aesthetical opinion, <code>x == None</code> is best.</p>\n"
},
{
"answer_id": 16636124,
"author": "Bleeding Fingers",
"author_id": 1309352,
"author_profile": "https://Stackoverflow.com/users/1309352",
"pm_score": 2,
"selected": false,
"text": "<p>Some more details:</p>\n\n<ol>\n<li><p>The <code>is</code> clause actually checks if the two <code>object</code>s are at the same\nmemory location or not. i.e whether they both point to the same\nmemory location and have the same <code>id</code>. </p></li>\n<li><p>As a consequence of 1, <code>is</code> ensures whether, or not, the two lexically represented <code>object</code>s have identical attributes (attributes-of-attributes...) or not</p></li>\n<li><p>Instantiation of primitive types like <code>bool</code>, <code>int</code>, <code>string</code>(with some exception), <code>NoneType</code> having a same value will always be in the same memory location.</p></li>\n</ol>\n\n<p>E.g.</p>\n\n<pre><code>>>> int(1) is int(1)\nTrue\n>>> str(\"abcd\") is str(\"abcd\")\nTrue\n>>> bool(1) is bool(2)\nTrue\n>>> bool(0) is bool(0)\nTrue\n>>> bool(0)\nFalse\n>>> bool(1)\nTrue\n</code></pre>\n\n<p>And since <code>NoneType</code> can only have one instance of itself in the python's \"look-up\" table therefore the former and the latter are more of a programming style of the developer who wrote the code(maybe for consistency) rather then having any subtle logical reason to choose one over the other.</p>\n"
},
{
"answer_id": 16636358,
"author": "Thijs van Dien",
"author_id": 1163893,
"author_profile": "https://Stackoverflow.com/users/1163893",
"pm_score": 3,
"selected": false,
"text": "<p>There is no difference because objects which are identical will of course be equal. However, <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\" title=\"PEP 8\">PEP 8</a> clearly states you should use <code>is</code>:</p>\n\n<blockquote>\n <p>Comparisons to singletons like None should always be done with is or is not, never the equality operators.</p>\n</blockquote>\n"
},
{
"answer_id": 27559554,
"author": "Chillar Anand",
"author_id": 2698552,
"author_profile": "https://Stackoverflow.com/users/2698552",
"pm_score": 3,
"selected": false,
"text": "<p><code>is</code> tests for identity, <strong>not</strong> equality. For your statement <code>foo is none</code>, Python simply compares the memory address of objects. It means you are asking the question \"Do I have two names for the same object?\"</p>\n\n<p><code>==</code> on the other hand tests for equality as determined by the <code>__eq__()</code> method. It doesn't cares about identity.</p>\n\n<pre><code>In [102]: x, y, z = 2, 2, 2.0\n\nIn [103]: id(x), id(y), id(z)\nOut[103]: (38641984, 38641984, 48420880)\n\nIn [104]: x is y\nOut[104]: True\n\nIn [105]: x == y\nOut[105]: True\n\nIn [106]: x is z\nOut[106]: False\n\nIn [107]: x == z\nOut[107]: True\n</code></pre>\n\n<p><code>None</code> is a singleton operator. So <code>None is None</code> is always true.</p>\n\n<pre><code>In [101]: None is None\nOut[101]: True\n</code></pre>\n"
},
{
"answer_id": 55489100,
"author": "Aks",
"author_id": 4417090,
"author_profile": "https://Stackoverflow.com/users/4417090",
"pm_score": 0,
"selected": false,
"text": "<pre><code>a is b # returns true if they a and b are true alias\na == b # returns true if they are true alias or they have values that are deemed equivalence \n\n\na = [1,3,4]\nb = a[:] #creating copy of list\na is b # if gives false\nFalse\na == b # gives true\nTrue\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156/"
] | Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might? | `is` always returns `True` if it compares the same object instance
Whereas `==` is ultimately determined by the `__eq__()` method
i.e.
```
>>> class Foo(object):
def __eq__(self, other):
return True
>>> f = Foo()
>>> f == None
True
>>> f is None
False
``` |
26,620 | <p>In my web app, I submit some form fields with jQuery's <code>$.getJSON()</code> method. I am having some problems with the encoding. The character-set of my app is <code>charset=ISO-8859-1</code>, but I think these fields are submitted with <code>UTF-8</code>. </p>
<p>How I can set encoding used in <code>$.getJSON</code> calls? </p>
| [
{
"answer_id": 26681,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 6,
"selected": true,
"text": "<p>I think that you'll probably have to use <a href=\"http://docs.jquery.com/Ajax/jQuery.ajax#options\" rel=\"noreferrer\"><code>$.ajax()</code></a> if you want to change the encoding, see the <code>contentType</code> param below (the <code>success</code> and <code>error</code> callbacks assume you have <code><div id=\"success\"></div></code> and <code><div id=\"error\"></div></code> in the html):</p>\n\n<pre><code>$.ajax({\n type: \"POST\",\n url: \"SomePage.aspx/GetSomeObjects\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n data: \"{id: '\" + someId + \"'}\",\n success: function(json) {\n $(\"#success\").html(\"json.length=\" + json.length);\n itemAddCallback(json);\n },\n error: function (xhr, textStatus, errorThrown) {\n $(\"#error\").html(xhr.responseText);\n }\n});\n</code></pre>\n\n<p>I actually just had to do this about an hour ago, what a coincidence!</p>\n"
},
{
"answer_id": 27023,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 6,
"selected": false,
"text": "<p>If you want to use <code>$.getJSON()</code> you can add the following before the call :</p>\n\n<pre><code>$.ajaxSetup({\n scriptCharset: \"utf-8\",\n contentType: \"application/json; charset=utf-8\"\n});\n</code></pre>\n\n<p>You can use the charset you want instead of <code>utf-8</code>.</p>\n\n<p>The options are explained <a href=\"http://docs.jquery.com/Ajax/jQuery.ajax#toptions\" rel=\"noreferrer\">here</a>.</p>\n\n<p><code>contentType :</code> When sending data to the server, use this <code>content-type</code>. Default is <code>application/x-www-form-urlencoded</code>, which is fine for most cases.</p>\n\n<p><code>scriptCharset :</code> Only for requests with <code>jsonp</code> or <code>script</code> dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.</p>\n\n<p>You may need one or both ...</p>\n"
},
{
"answer_id": 8707420,
"author": "Anderson Mao",
"author_id": 818400,
"author_profile": "https://Stackoverflow.com/users/818400",
"pm_score": 1,
"selected": false,
"text": "<p>Use <code>encodeURI()</code> in client JS and use <code>URLDecoder.decode()</code> in server Java side works.</p>\n\n<hr>\n\n<p>Example: </p>\n\n<ul>\n<li><p><strong>Javascript</strong>:</p>\n\n<pre><code>$.getJSON(\n url,\n {\n \"user\": encodeURI(JSON.stringify(user))\n },\n onSuccess\n);\n</code></pre></li>\n<li><p><strong>Java</strong>:</p>\n\n<p><code>java.net.URLDecoder.decode(params.user, \"UTF-8\");</code></p></li>\n</ul>\n"
},
{
"answer_id": 9606241,
"author": "Felipe Alcará",
"author_id": 1255308,
"author_profile": "https://Stackoverflow.com/users/1255308",
"pm_score": 3,
"selected": false,
"text": "<p>You need to analyze the JSON calls using Wireshark, so you will see if you include the charset in the formation of the JSON page or not, for example:</p>\n\n<ul>\n<li>If the page is simple if text / html</li>\n</ul>\n\n<pre>\n0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK.\n0010 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 .Content -Type: t\n0020 65 78 74 2f 68 74 6d 6c 0d 0a 43 61 63 68 65 2d ext/html ..Cache-\n0030 43 6f 6e 74 72 6f 6c 3a 20 6e 6f 2d 63 61 63 68 Control: no-cach\n</pre>\n\n<ul>\n<li>If the page is of the type including custom JSON with MIME \"charset = ISO-8859-1\"</li>\n</ul>\n\n<pre>\n0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK.\n0010 0a 43 61 63 68 65 2d 43 6f 6e 74 72 6f 6c 3a 20 .Cache-C ontrol: \n0020 6e 6f 2d 63 61 63 68 65 0d 0a 43 6f 6e 74 65 6e no-cache ..Conten\n0030 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 68 74 6d t-Type: text/htm\n0040 6c 3b 20 63 68 61 72 73 65 74 3d 49 53 4f 2d 38 l; chars et=ISO-8\n0050 38 35 39 2d 31 0d 0a 43 6f 6e 6e 65 63 74 69 6f 859-1..C onnectio\n</pre>\n\n<p>Why is that? because we can not put on the page of JSON a goal like this:\n</p>\n\n<p>In my case I use the manufacturer Connect Me 9210 Digi:</p>\n\n<ul>\n<li>I had to use a flag to indicate that one would use non-standard MIME:\n p-> theCgiPtr-> = fDataType eRpDataTypeOther;</li>\n<li>It added the new MIME in the variable:\n strcpy (p-> theCgiPtr-> fOtherMimeType, \"text / html;\ncharset = ISO-8859-1 \");</li>\n</ul>\n\n<p><strong>It worked for me</strong> without having to convert the data passed by JSON for UTF-8 and then redo the conversion on the page ...</p>\n"
},
{
"answer_id": 26887335,
"author": "Vipin Kohli",
"author_id": 3167919,
"author_profile": "https://Stackoverflow.com/users/3167919",
"pm_score": 0,
"selected": false,
"text": "<p>Use this function to regain the utf-8 characters</p>\n\n<pre><code>function decode_utf8(s) { \n return decodeURIComponent(escape(s)); \n}\n</code></pre>\n\n<p>Example:\n var new_Str=decode_utf8(str);</p>\n"
},
{
"answer_id": 58890056,
"author": "zahra salmaninejad",
"author_id": 11372789,
"author_profile": "https://Stackoverflow.com/users/11372789",
"pm_score": 0,
"selected": false,
"text": "<p>f you want to use $.getJSON() you can add the following before the call :</p>\n\n<pre><code>$.ajaxSetup({\n scriptCharset: \"utf-8\",\n contentType: \"application/json; charset=utf-8\"\n});\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | In my web app, I submit some form fields with jQuery's `$.getJSON()` method. I am having some problems with the encoding. The character-set of my app is `charset=ISO-8859-1`, but I think these fields are submitted with `UTF-8`.
How I can set encoding used in `$.getJSON` calls? | I think that you'll probably have to use [`$.ajax()`](http://docs.jquery.com/Ajax/jQuery.ajax#options) if you want to change the encoding, see the `contentType` param below (the `success` and `error` callbacks assume you have `<div id="success"></div>` and `<div id="error"></div>` in the html):
```
$.ajax({
type: "POST",
url: "SomePage.aspx/GetSomeObjects",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
$("#success").html("json.length=" + json.length);
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
```
I actually just had to do this about an hour ago, what a coincidence! |
26,652 | <p>Is there a way to make a TSQL variable constant?</p>
| [
{
"answer_id": 26655,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<p>There are no such thing as \"creating a constant\" in database literature. Constants exist as they are and often called values. One can declare a variable and assign a value (constant) to it. From a scholastic view:</p>\n\n<pre><code>DECLARE @two INT\nSET @two = 2\n</code></pre>\n\n<p>Here @two is a variable and 2 is a value/constant.</p>\n"
},
{
"answer_id": 26656,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 7,
"selected": true,
"text": "<p>No, but you can create a function and hardcode it in there and use that.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>CREATE FUNCTION fnConstant()\nRETURNS INT\nAS\nBEGIN\n RETURN 2\nEND\nGO\n\nSELECT dbo.fnConstant()\n</code></pre>\n"
},
{
"answer_id": 26673,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 3,
"selected": false,
"text": "<p>No, but good old naming conventions should be used.</p>\n\n<pre><code>declare @MY_VALUE as int\n</code></pre>\n"
},
{
"answer_id": 26675,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, lets see</p>\n\n<p>Constants are immutable values which are known at compile time and do not change for the life of the program</p>\n\n<p>that means you can never have a constant in SQL Server</p>\n\n<pre><code>declare @myvalue as int\nset @myvalue = 5\nset @myvalue = 10--oops we just changed it\n</code></pre>\n\n<p>the value just changed</p>\n"
},
{
"answer_id": 26676,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "<p>There is no built-in support for constants in T-SQL. You could use SQLMenace's approach to simulate it (though you can never be sure whether someone else has overwritten the function to return something else…), or possibly write a table containing constants, <a href=\"http://www.sqlteam.com/article/simulating-constants-using-user-defined-functions\" rel=\"noreferrer\">as suggested over here</a>. Perhaps write a trigger that rolls back any changes to the <code>ConstantValue</code> column?</p>\n"
},
{
"answer_id": 12723310,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 5,
"selected": false,
"text": "<p>My workaround to missing constans is to give hints about the value to the optimizer.</p>\n\n<pre><code>DECLARE @Constant INT = 123;\n\nSELECT * \nFROM [some_relation] \nWHERE [some_attribute] = @Constant\nOPTION( OPTIMIZE FOR (@Constant = 123))\n</code></pre>\n\n<p>This tells the query compiler to treat the variable as if it was a constant when creating the execution plan. The down side is that you have to define the value twice.</p>\n"
},
{
"answer_id": 13685800,
"author": "Tony Wall",
"author_id": 1080914,
"author_profile": "https://Stackoverflow.com/users/1080914",
"pm_score": -1,
"selected": false,
"text": "<p>The best answer is from SQLMenace according to the requirement if that is to create a temporary constant for use within scripts, i.e. across multiple GO statements/batches.</p>\n\n<p>Just create the procedure in the tempdb then you have no impact on the target database.</p>\n\n<p>One practical example of this is a database create script which writes a control value at the end of the script containing the logical schema version. At the top of the file are some comments with change history etc... But in practice most developers will forget to scroll down and update the schema version at the bottom of the file.</p>\n\n<p>Using the above code allows a visible schema version constant to be defined at the top before the database script (copied from the generate scripts feature of SSMS) creates the database but used at the end. This is right in the face of the developer next to the change history and other comments, so they are very likely to update it.</p>\n\n<p>For example:</p>\n\n<pre><code>use tempdb\ngo\ncreate function dbo.MySchemaVersion()\nreturns int\nas\nbegin\n return 123\nend\ngo\n\nuse master\ngo\n\n-- Big long database create script with multiple batches...\nprint 'Creating database schema version ' + CAST(tempdb.dbo.MySchemaVersion() as NVARCHAR) + '...'\ngo\n-- ...\ngo\n-- ...\ngo\nuse MyDatabase\ngo\n\n-- Update schema version with constant at end (not normally possible as GO puts\n-- local @variables out of scope)\ninsert MyConfigTable values ('SchemaVersion', tempdb.dbo.MySchemaVersion())\ngo\n\n-- Clean-up\nuse tempdb\ndrop function MySchemaVersion\ngo\n</code></pre>\n"
},
{
"answer_id": 14096239,
"author": "Robert",
"author_id": 1938754,
"author_profile": "https://Stackoverflow.com/users/1938754",
"pm_score": 3,
"selected": false,
"text": "<p>Prior to using a SQL function run the following script to see the differences in performance:</p>\n\n<pre><code>IF OBJECT_ID('fnFalse') IS NOT NULL\nDROP FUNCTION fnFalse\nGO\n\nIF OBJECT_ID('fnTrue') IS NOT NULL\nDROP FUNCTION fnTrue\nGO\n\nCREATE FUNCTION fnTrue() RETURNS INT WITH SCHEMABINDING\nAS\nBEGIN\nRETURN 1\nEND\nGO\n\nCREATE FUNCTION fnFalse() RETURNS INT WITH SCHEMABINDING\nAS\nBEGIN\nRETURN ~ dbo.fnTrue()\nEND\nGO\n\nDECLARE @TimeStart DATETIME = GETDATE()\nDECLARE @Count INT = 100000\nWHILE @Count > 0 BEGIN\nSET @Count -= 1\n\nDECLARE @Value BIT\nSELECT @Value = dbo.fnTrue()\nIF @Value = 1\n SELECT @Value = dbo.fnFalse()\nEND\nDECLARE @TimeEnd DATETIME = GETDATE()\nPRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using function'\nGO\n\nDECLARE @TimeStart DATETIME = GETDATE()\nDECLARE @Count INT = 100000\nDECLARE @FALSE AS BIT = 0\nDECLARE @TRUE AS BIT = ~ @FALSE\n\nWHILE @Count > 0 BEGIN\nSET @Count -= 1\n\nDECLARE @Value BIT\nSELECT @Value = @TRUE\nIF @Value = 1\n SELECT @Value = @FALSE\nEND\nDECLARE @TimeEnd DATETIME = GETDATE()\nPRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using local variable'\nGO\n\nDECLARE @TimeStart DATETIME = GETDATE()\nDECLARE @Count INT = 100000\n\nWHILE @Count > 0 BEGIN\nSET @Count -= 1\n\nDECLARE @Value BIT\nSELECT @Value = 1\nIF @Value = 1\n SELECT @Value = 0\nEND\nDECLARE @TimeEnd DATETIME = GETDATE()\nPRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using hard coded values'\nGO\n</code></pre>\n"
},
{
"answer_id": 32373858,
"author": "mbobka",
"author_id": 2201119,
"author_profile": "https://Stackoverflow.com/users/2201119",
"pm_score": 5,
"selected": false,
"text": "<p>One solution, offered by Jared Ko is to use <strong>pseudo-constants</strong>.</p>\n<p>As explained in <a href=\"https://blogs.msdn.microsoft.com/sql_server_appendix_z/2013/09/16/sql-server-variables-parameters-or-literals-or-constants/\" rel=\"noreferrer\">SQL Server: Variables, Parameters or Literals? Or… Constants?</a>:</p>\n<blockquote>\n<p>Pseudo-Constants are not variables or parameters. Instead, they're simply views with one row, and enough columns to support your constants. With these simple rules, the SQL Engine completely ignores the value of the view but still builds an execution plan based on its value. The execution plan doesn't even show a join to the view!</p>\n<p>Create like this:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE SCHEMA ShipMethod\nGO\n-- Each view can only have one row.\n-- Create one column for each desired constant.\n-- Each column is restricted to a single value.\nCREATE VIEW ShipMethod.ShipMethodID AS\nSELECT CAST(1 AS INT) AS [XRQ - TRUCK GROUND]\n ,CAST(2 AS INT) AS [ZY - EXPRESS]\n ,CAST(3 AS INT) AS [OVERSEAS - DELUXE]\n ,CAST(4 AS INT) AS [OVERNIGHT J-FAST]\n ,CAST(5 AS INT) AS [CARGO TRANSPORT 5]\n</code></pre>\n<p>Then use like this:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT h.*\nFROM Sales.SalesOrderHeader h\nJOIN ShipMethod.ShipMethodID const\n ON h.ShipMethodID = const.[OVERNIGHT J-FAST]\n</code></pre>\n<p>Or like this:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT h.*\nFROM Sales.SalesOrderHeader h\nWHERE h.ShipMethodID = (SELECT TOP 1 [OVERNIGHT J-FAST] FROM ShipMethod.ShipMethodID)\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 39659808,
"author": "Michal D.",
"author_id": 2150054,
"author_profile": "https://Stackoverflow.com/users/2150054",
"pm_score": 3,
"selected": false,
"text": "<p>If you are interested in getting optimal execution plan for a value in the variable you can use a dynamic sql code. It makes the variable constant.</p>\n\n<pre><code>DECLARE @var varchar(100) = 'some text'\nDECLARE @sql varchar(MAX)\nSET @sql = 'SELECT * FROM table WHERE col = '''+@var+''''\nEXEC (@sql)\n</code></pre>\n"
},
{
"answer_id": 48013270,
"author": "monkeyhouse",
"author_id": 1778606,
"author_profile": "https://Stackoverflow.com/users/1778606",
"pm_score": 3,
"selected": false,
"text": "<p>For enums or simple constants, a view with a single row has great performance and compile time checking / dependency tracking ( cause its a column name )</p>\n\n<p>See Jared Ko's blog post <a href=\"https://blogs.msdn.microsoft.com/sql_server_appendix_z/2013/09/16/sql-server-variables-parameters-or-literals-or-constants/\" rel=\"nofollow noreferrer\">https://blogs.msdn.microsoft.com/sql_server_appendix_z/2013/09/16/sql-server-variables-parameters-or-literals-or-constants/</a></p>\n\n<p>create the view</p>\n\n<pre><code> CREATE VIEW ShipMethods AS\n SELECT CAST(1 AS INT) AS [XRQ - TRUCK GROUND]\n ,CAST(2 AS INT) AS [ZY - EXPRESS]\n ,CAST(3 AS INT) AS [OVERSEAS - DELUXE]\n , CAST(4 AS INT) AS [OVERNIGHT J-FAST]\n ,CAST(5 AS INT) AS [CARGO TRANSPORT 5]\n</code></pre>\n\n<p>use the view</p>\n\n<pre><code>SELECT h.*\nFROM Sales.SalesOrderHeader \nWHERE ShipMethodID = ( select [OVERNIGHT J-FAST] from ShipMethods )\n</code></pre>\n"
},
{
"answer_id": 48025646,
"author": "Gert-Jan",
"author_id": 8992916,
"author_profile": "https://Stackoverflow.com/users/8992916",
"pm_score": 1,
"selected": false,
"text": "<p>Since there is no build in support for constants, my solution is very simple.</p>\n\n<p>Since this is not supported:</p>\n\n<pre><code>Declare Constant @supplement int = 240\nSELECT price + @supplement\nFROM what_does_it_cost\n</code></pre>\n\n<p>I would simply convert it to</p>\n\n<pre><code>SELECT price + 240/*CONSTANT:supplement*/\nFROM what_does_it_cost\n</code></pre>\n\n<p>Obviously, this relies on the whole thing (the value without trailing space and the comment) to be unique. Changing it is possible with a global search and replace.</p>\n"
},
{
"answer_id": 74219496,
"author": "JensG",
"author_id": 19150755,
"author_profile": "https://Stackoverflow.com/users/19150755",
"pm_score": 0,
"selected": false,
"text": "<p>SQLServer 2022 (currently only as Preview available) is now able to Inline the function proposed by SQLMenace, this should prevent the performance hit described by some comments.</p>\n<p><code>CREATE FUNCTION fnConstant() RETURNS INT AS BEGIN RETURN 2 END GO</code></p>\n<p><code>SELECT is_inlineable FROM sys.sql_modules WHERE [object_id]=OBJECT_ID('dbo.fnConstant');</code></p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>is_inlineable</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><code>SELECT dbo.fnConstant()</code></p>\n<p><a href=\"https://i.stack.imgur.com/3SMqo.png\" rel=\"nofollow noreferrer\">ExecutionPlan</a></p>\n<hr />\n<p>To test if it also uses the value coming from the Function, I added a second function returning value "1"</p>\n<pre><code>CREATE FUNCTION fnConstant1()\nRETURNS INT\nAS\nBEGIN\n RETURN 1\nEND\nGO\n</code></pre>\n<p>Create Temp Table with about 500k rows with Value 1 and 4 rows with Value 2:</p>\n<pre><code>DROP TABLE IF EXISTS #temp ; \ncreate table #temp (value_int INT) \nDECLARE @counter INT; \nSET @counter = 0 \nWHILE @counter <= 500000 \nBEGIN \n INSERT INTO #temp VALUES (1); \n SET @counter = @counter +1 \nEND \nSET @counter = 0\n \nWHILE @counter <= 3 \nBEGIN \n INSERT INTO #temp VALUES (2);\n SET @counter = @counter +1\nEND\ncreate index i_temp on #temp (value_int);\n</code></pre>\n<p>Using the describe plan we can see that the Optimizer expects 500k values for<br />\n<code>select * from #temp where value_int = dbo.fnConstant1(); --Returns 500001 rows</code>\n<a href=\"https://i.stack.imgur.com/MDW4T.png\" rel=\"nofollow noreferrer\">Constant 1</a></p>\n<p>and 4 rows for<br />\n<code>select * from #temp where value_int = dbo.fnConstant(); --Returns 4rows</code><br />\n<a href=\"https://i.stack.imgur.com/Vu8T3.png\" rel=\"nofollow noreferrer\">Constant 2</a></p>\n"
},
{
"answer_id": 74360479,
"author": "pricerc",
"author_id": 2258866,
"author_profile": "https://Stackoverflow.com/users/2258866",
"pm_score": 0,
"selected": false,
"text": "<p>Robert's performance test is interesting. And even in late 2022, the scalar functions are much slower (by an order of magnitude) than variables or literals. A view (as suggested mbobka) is somewhere in-between when used for this same test.</p>\n<p>That said, using a loop like that in SQL Server is not something I'd ever do, because I'd normally be operating on a whole set.</p>\n<p>In SQL 2019, if you use schema-bound functions in a set operation, the difference is much less noticeable.</p>\n<p>I created and populated a test table:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>create table #testTable (id int identity(1, 1) primary key, value tinyint);\n</code></pre>\n<p>And changed the test so that instead of looping and changing a variable, it queries the test table and returns true or false depending on the value in the test table, e.g.:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>insert @testTable(value)\nselect case when value > 127\n then @FALSE\n else @TRUE\nend\nfrom #testTable with(nolock)\n</code></pre>\n<p>I tested 5 scenarios:</p>\n<ol>\n<li>hard-coded values</li>\n<li>local variables</li>\n<li>scalar functions</li>\n<li>a view</li>\n<li>a table-valued function</li>\n</ol>\n<p>running the test 10 times, yielded the following results:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: left;\">scenario</th>\n<th style=\"text-align: center;\">min</th>\n<th style=\"text-align: center;\">max</th>\n<th style=\"text-align: center;\">avg</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">scalar functions</td>\n<td style=\"text-align: center;\">233</td>\n<td style=\"text-align: center;\">259</td>\n<td style=\"text-align: center;\">240</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">hard-coded values</td>\n<td style=\"text-align: center;\">236</td>\n<td style=\"text-align: center;\">265</td>\n<td style=\"text-align: center;\">243</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">local variables</td>\n<td style=\"text-align: center;\">235</td>\n<td style=\"text-align: center;\">278</td>\n<td style=\"text-align: center;\">245</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">table-valued function</td>\n<td style=\"text-align: center;\">243</td>\n<td style=\"text-align: center;\">272</td>\n<td style=\"text-align: center;\">253</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">view</td>\n<td style=\"text-align: center;\">244</td>\n<td style=\"text-align: center;\">267</td>\n<td style=\"text-align: center;\">254</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Suggesting to me, that for set-based work in (at least) 2019 and better, there's not much in it.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>set nocount on;\ngo\n\n-- create test data table\ndrop table if exists #testTable;\ncreate table #testTable (id int identity(1, 1) primary key, value tinyint);\n\n-- populate test data\ninsert #testTable (value)\nselect top (1000000) convert(binary (1), newid()) \nfrom sys.all_objects a\n , sys.all_objects b\ngo\n\n-- scalar function for True\ndrop function if exists fnTrue;\ngo\ncreate function dbo.fnTrue() returns bit with schemabinding as\nbegin\n return 1\nend\ngo\n\n-- scalar function for False\ndrop function if exists fnFalse;\ngo\ncreate function dbo.fnFalse () returns bit with schemabinding as\nbegin\n return 0\nend\ngo\n\n-- table-valued function for booleans\ndrop function if exists dbo.tvfBoolean;\ngo\ncreate function tvfBoolean() returns table with schemabinding as\nreturn\n select convert(bit, 1) as true, convert(bit, 0) as false\ngo\n\n-- view for booleans\ndrop view if exists dbo.viewBoolean;\ngo\ncreate view dbo.viewBoolean with schemabinding as\n select convert(bit, 1) as true, convert(bit, 0) as false\ngo\n\n-- create table for results\ndrop table if exists #testResults\ncreate table #testResults (id int identity(1,1), test int, elapsed bigint, message varchar(1000));\n\n-- define tests\ndeclare @tests table(testNumber int, description nvarchar(100), sql nvarchar(max))\ninsert @tests values \n (1, N'hard-coded values', N'\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when t.value > 127 \n then 0 \n else 1\nend\nfrom #testTable t')\n, (2, N'local variables', N'\ndeclare @FALSE as bit = 0\ndeclare @TRUE as bit = 1\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when t.value > 127 \n then @FALSE\n else @TRUE\nend\nfrom #testTable t'), \n(3, N'scalar functions', N'\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when t.value > 127 \n then dbo.fnFalse()\n else dbo.fnTrue()\nend\nfrom #testTable t'), \n(4, N'view', N'\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when value > 127\n then b.false\n else b.true\nend\nfrom #testTable t with(nolock), viewBoolean b'),\n(5, N'table-valued function', N'\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when value > 127\n then b.false\n else b.true\nend\nfrom #testTable with(nolock), dbo.tvfBoolean() b')\n;\n\ndeclare @testNumber int, @description varchar(100), @sql nvarchar(max)\n\ndeclare @testRuns int = 10;\n\n-- execute tests\nwhile @testRuns > 0 begin\n set @testRuns -= 1\n\n declare testCursor cursor for select testNumber, description, sql from @tests;\n open testCursor\n\n fetch next from testCursor into @testNumber, @description, @sql\n while @@FETCH_STATUS = 0 begin\n \n declare @TimeStart datetime2(7) = sysdatetime();\n\n execute sp_executesql @sql;\n\n declare @TimeEnd datetime2(7) = sysdatetime()\n\n insert #testResults(test, elapsed, message) \n select @testNumber, datediff_big(ms, @TimeStart, @TimeEnd), @description\n\n fetch next from testCursor into @testNumber, @description, @sql\n end \n close testCursor\n deallocate testCursor\nend\n\n\n-- display results\nselect test, message, count(*) runs, min(elapsed) as min, max(elapsed) as max, avg(elapsed) as avg\nfrom #testResults\ngroup by test, message\norder by avg(elapsed);\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
] | Is there a way to make a TSQL variable constant? | No, but you can create a function and hardcode it in there and use that.
Here is an example:
```
CREATE FUNCTION fnConstant()
RETURNS INT
AS
BEGIN
RETURN 2
END
GO
SELECT dbo.fnConstant()
``` |
26,670 | <p>I'm creating PDFs on-demand with ColdFusion's <a href="http://cfquickdocs.com/cf8/?getDoc=cfdocument" rel="nofollow noreferrer">CFDocument</a> tag, like so:</p>
<pre><code><cfdocument format="PDF" filename="#attributes.fileName#" overwrite="true">
<cfdocumentitem type="footer">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left"><font face="Tahoma" color="black"><strong>My Client's Corporation</strong><br/>Street address<br/>City, ST 55555</font></td>
<td align="right"><font face="Tahoma" color="black">Phone: 555.555.5555<br/>Fax: 555.555.5555<br/>Email: [email protected]</font></td>
</tr>
</table>
</cfdocumentitem>
<html>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<!--- some content here ... --->
</table>
</body>
</html>
</cfdocument>
</code></pre>
<p>The problem I'm having is that sometimes (actually, most of the time, but not always) <strong><em>some</em></strong> of the footer text is there, but invisible. I can highlight it and copy/paste it into notepad, where I can see it all -- but in the generated PDF only the first line of the left column of the footer is visible, the rest is invisible. Hence why I added the font color of black in the code.</p>
<p><img src="https://i.stack.imgur.com/LHZ96.png" alt="screenshot of problem"></p>
<p>Any ideas on how to correct this?</p>
| [
{
"answer_id": 30688,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 3,
"selected": true,
"text": "<p>A PDF is what I'm after, so I'm not sure how outputting another format would help.</p>\n\n<p>As it turns out, the footer space just wasn't enough to fit all of this text; verified by the fact that changing the font size to 4pt would fit it all in without a problem.</p>\n\n<p>I spent some time attempting to rewrite the footer code using DDX <a href=\"http://www.coldfusionjedi.com/index.cfm/2008/6/2/Changing-the-size-of-a-footer-in-CFDOCUMENT\" rel=\"nofollow noreferrer\">as outlined here</a> and the <a href=\"http://cfquickdocs.com/cf8/?getDoc=cfpdf\" rel=\"nofollow noreferrer\">CFPDF</a> tag to implement it; but even after several hours of hacking away and finally getting a valid DDX as reported by the new <a href=\"http://cfquickdocs.com/cf8/?getDoc=IsDDX\" rel=\"nofollow noreferrer\">isDDX function</a>, the CFPDF tag reported that it was invalid DDX for some reason.</p>\n\n<p>At this point I decided I had wasted enough of the client's time/money and just reformatted the footer to be 2 lines of centered text, which was good enough.</p>\n"
},
{
"answer_id": 224415,
"author": "Chris Dolan",
"author_id": 14783,
"author_profile": "https://Stackoverflow.com/users/14783",
"pm_score": 1,
"selected": false,
"text": "<p>Usually when PDF shows blank text, it's because the font metrics are embedded in the document, but the glyphs are not. I know nothing about ColdFusion, but you might try the following:</p>\n\n<ul>\n<li>Try a font other than Tahoma as a test. All PDF readers must support 14 basic fonts, including 4 Helvetica variants, 4 Times variants, 4 Courier variants, Symbol and ZapfDingbats, so those are always safe choices</li>\n<li>See if ColdFusion offers any control over font embedding</li>\n<li>Try a list of alternatives in your font declaration, like \"Tahoma,Helvetica,sans-serif\"</li>\n</ul>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
] | I'm creating PDFs on-demand with ColdFusion's [CFDocument](http://cfquickdocs.com/cf8/?getDoc=cfdocument) tag, like so:
```
<cfdocument format="PDF" filename="#attributes.fileName#" overwrite="true">
<cfdocumentitem type="footer">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left"><font face="Tahoma" color="black"><strong>My Client's Corporation</strong><br/>Street address<br/>City, ST 55555</font></td>
<td align="right"><font face="Tahoma" color="black">Phone: 555.555.5555<br/>Fax: 555.555.5555<br/>Email: [email protected]</font></td>
</tr>
</table>
</cfdocumentitem>
<html>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<!--- some content here ... --->
</table>
</body>
</html>
</cfdocument>
```
The problem I'm having is that sometimes (actually, most of the time, but not always) ***some*** of the footer text is there, but invisible. I can highlight it and copy/paste it into notepad, where I can see it all -- but in the generated PDF only the first line of the left column of the footer is visible, the rest is invisible. Hence why I added the font color of black in the code.

Any ideas on how to correct this? | A PDF is what I'm after, so I'm not sure how outputting another format would help.
As it turns out, the footer space just wasn't enough to fit all of this text; verified by the fact that changing the font size to 4pt would fit it all in without a problem.
I spent some time attempting to rewrite the footer code using DDX [as outlined here](http://www.coldfusionjedi.com/index.cfm/2008/6/2/Changing-the-size-of-a-footer-in-CFDOCUMENT) and the [CFPDF](http://cfquickdocs.com/cf8/?getDoc=cfpdf) tag to implement it; but even after several hours of hacking away and finally getting a valid DDX as reported by the new [isDDX function](http://cfquickdocs.com/cf8/?getDoc=IsDDX), the CFPDF tag reported that it was invalid DDX for some reason.
At this point I decided I had wasted enough of the client's time/money and just reformatted the footer to be 2 lines of centered text, which was good enough. |
26,715 | <p>How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example:</p>
<pre><code>--index.aspx
--about.aspx
--contact.aspx
--/feature1
--/feature1/subfeature/action
--/feature2/subfeature/action
</code></pre>
<p>I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application.</p>
<p>I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice.</p>
| [
{
"answer_id": 26741,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 5,
"selected": true,
"text": "<p>There isn't any issues with organizing your controllers. You just need to setup the routes to take the organization into consideration. The problem you will run into is finding the view for the controller, since you changed the convention. There isn't any built in functionality for it yet, but it is easy to create a work around yourself with a ActionFilterAttribute and a custom view locator that inherits off ViewLocator. Then when creating your controller, you just specify what ViewLocator to use, so the controller knows how to find the view. I can post some code if needed.</p>\n\n<p>This method kind of goes along with some advice I gave another person for separating their views out for a portal using ASP.NET MVC. Here is the <a href=\"https://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc\">link to the question</a> as a reference.</p>\n"
},
{
"answer_id": 29530,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 3,
"selected": false,
"text": "<p>In terms of how you arrange your views, you can put your views in subfolders if you'd like and create your own view structure. All views can always be referenced by their full path using the ~syntax. So if you put Index.aspx in \\Views\\Feature1\\Home then you could reference that view using ~/Views/Feature1/Home/Index.aspx.</p>\n"
},
{
"answer_id": 579937,
"author": "Stephen Curial",
"author_id": 1399919,
"author_profile": "https://Stackoverflow.com/users/1399919",
"pm_score": 3,
"selected": false,
"text": "<p>Here's two good blog posts that I found that may help other readers:</p>\n\n<p><a href=\"http://stephenwalther.com/blog/archive/2008/07/23/asp-net-mvc-tip-24-retrieve-views-from-different-folders.aspx\" rel=\"nofollow noreferrer\">http://stephenwalther.com/blog/archive/2008/07/23/asp-net-mvc-tip-24-retrieve-views-from-different-folders.aspx</a></p>\n\n<p>This one talks a little more in-depth about what Haacked described above.</p>\n\n<p><a href=\"http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx\" rel=\"nofollow noreferrer\">http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx</a></p>\n\n<p>This is a nice alternative for grouping your site into \"areas.\"</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041/"
] | How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example:
```
--index.aspx
--about.aspx
--contact.aspx
--/feature1
--/feature1/subfeature/action
--/feature2/subfeature/action
```
I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application.
I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice. | There isn't any issues with organizing your controllers. You just need to setup the routes to take the organization into consideration. The problem you will run into is finding the view for the controller, since you changed the convention. There isn't any built in functionality for it yet, but it is easy to create a work around yourself with a ActionFilterAttribute and a custom view locator that inherits off ViewLocator. Then when creating your controller, you just specify what ViewLocator to use, so the controller knows how to find the view. I can post some code if needed.
This method kind of goes along with some advice I gave another person for separating their views out for a portal using ASP.NET MVC. Here is the [link to the question](https://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc) as a reference. |
26,721 | <p>When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar.</p>
<p>My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to <strong>use</strong> the horizontal scrollbar that comes up.</p>
<p>Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all?</p>
| [
{
"answer_id": 26782,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 0,
"selected": false,
"text": "<p>If your controls are inside a panel, try setting the AutoScroll property of the Panel to False. This will hide the scrollbars. I hope this points you in the right direction.</p>\n\n<pre><code>myPanel.AutoScroll = False\n</code></pre>\n"
},
{
"answer_id": 27032,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>You will need your controls to resize slightly to accommodate the width of the vertical scroll bar. One way to achieve this achieved through docking. Rather than just dropping controls on the form, you'll have to play a bit with panels, padding, min/max sizing and docking.</p>\n\n<p>Here is example code you can place behind a blank new Form1. Resize the form, in designer or runtime and you'll see that the horizontal scrollbar is not shown and the fields are not overlapped. I've also given the fields a max width for good measure : </p>\n\n<pre><code>#region Windows Form Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent() {\n this.textBox1 = new System.Windows.Forms.TextBox();\n this.label1 = new System.Windows.Forms.Label();\n this.panel1 = new System.Windows.Forms.Panel();\n this.panel2 = new System.Windows.Forms.Panel();\n this.textBox2 = new System.Windows.Forms.TextBox();\n this.label2 = new System.Windows.Forms.Label();\n this.panel1.SuspendLayout();\n this.panel2.SuspendLayout();\n this.SuspendLayout();\n // \n // textBox1\n // \n this.textBox1.Dock = System.Windows.Forms.DockStyle.Top;\n this.textBox1.Location = new System.Drawing.Point(32, 0);\n this.textBox1.MaximumSize = new System.Drawing.Size(250, 0);\n this.textBox1.Name = \"textBox1\";\n this.textBox1.Size = new System.Drawing.Size(250, 20);\n this.textBox1.TabIndex = 0;\n // \n // label1\n // \n this.label1.AutoSize = true;\n this.label1.Dock = System.Windows.Forms.DockStyle.Left;\n this.label1.Location = new System.Drawing.Point(0, 0);\n this.label1.Name = \"label1\";\n this.label1.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);\n this.label1.Size = new System.Drawing.Size(32, 16);\n this.label1.TabIndex = 0;\n this.label1.Text = \"Field:\";\n // \n // panel1\n // \n this.panel1.Controls.Add(this.textBox1);\n this.panel1.Controls.Add(this.label1);\n this.panel1.Dock = System.Windows.Forms.DockStyle.Top;\n this.panel1.Location = new System.Drawing.Point(0, 0);\n this.panel1.Name = \"panel1\";\n this.panel1.Size = new System.Drawing.Size(392, 37);\n this.panel1.TabIndex = 2;\n // \n // panel2\n // \n this.panel2.Controls.Add(this.textBox2);\n this.panel2.Controls.Add(this.label2);\n this.panel2.Dock = System.Windows.Forms.DockStyle.Top;\n this.panel2.Location = new System.Drawing.Point(0, 37);\n this.panel2.Name = \"panel2\";\n this.panel2.Size = new System.Drawing.Size(392, 37);\n this.panel2.TabIndex = 3;\n // \n // textBox2\n // \n this.textBox2.Dock = System.Windows.Forms.DockStyle.Top;\n this.textBox2.Location = new System.Drawing.Point(32, 0);\n this.textBox2.MaximumSize = new System.Drawing.Size(250, 0);\n this.textBox2.Name = \"textBox2\";\n this.textBox2.Size = new System.Drawing.Size(250, 20);\n this.textBox2.TabIndex = 0;\n // \n // label2\n // \n this.label2.AutoSize = true;\n this.label2.Dock = System.Windows.Forms.DockStyle.Left;\n this.label2.Location = new System.Drawing.Point(0, 0);\n this.label2.Name = \"label2\";\n this.label2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);\n this.label2.Size = new System.Drawing.Size(32, 16);\n this.label2.TabIndex = 0;\n this.label2.Text = \"Field:\";\n // \n // Form1\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.AutoScroll = true;\n this.ClientSize = new System.Drawing.Size(392, 116);\n this.Controls.Add(this.panel2);\n this.Controls.Add(this.panel1);\n this.Name = \"Form1\";\n this.Text = \"Form1\";\n this.panel1.ResumeLayout(false);\n this.panel1.PerformLayout();\n this.panel2.ResumeLayout(false);\n this.panel2.PerformLayout();\n this.ResumeLayout(false);\n\n }\n\n #endregion\n\n private System.Windows.Forms.TextBox textBox1;\n private System.Windows.Forms.Label label1;\n private System.Windows.Forms.Panel panel1;\n private System.Windows.Forms.Panel panel2;\n private System.Windows.Forms.TextBox textBox2;\n private System.Windows.Forms.Label label2;\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2729/"
] | When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar.
My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to **use** the horizontal scrollbar that comes up.
Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all? | You will need your controls to resize slightly to accommodate the width of the vertical scroll bar. One way to achieve this achieved through docking. Rather than just dropping controls on the form, you'll have to play a bit with panels, padding, min/max sizing and docking.
Here is example code you can place behind a blank new Form1. Resize the form, in designer or runtime and you'll see that the horizontal scrollbar is not shown and the fields are not overlapped. I've also given the fields a max width for good measure :
```
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.textBox1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Top;
this.textBox1.Location = new System.Drawing.Point(32, 0);
this.textBox1.MaximumSize = new System.Drawing.Size(250, 0);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(250, 20);
this.textBox1.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Dock = System.Windows.Forms.DockStyle.Left;
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);
this.label1.Size = new System.Drawing.Size(32, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Field:";
//
// panel1
//
this.panel1.Controls.Add(this.textBox1);
this.panel1.Controls.Add(this.label1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(392, 37);
this.panel1.TabIndex = 2;
//
// panel2
//
this.panel2.Controls.Add(this.textBox2);
this.panel2.Controls.Add(this.label2);
this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
this.panel2.Location = new System.Drawing.Point(0, 37);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(392, 37);
this.panel2.TabIndex = 3;
//
// textBox2
//
this.textBox2.Dock = System.Windows.Forms.DockStyle.Top;
this.textBox2.Location = new System.Drawing.Point(32, 0);
this.textBox2.MaximumSize = new System.Drawing.Size(250, 0);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(250, 20);
this.textBox2.TabIndex = 0;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Dock = System.Windows.Forms.DockStyle.Left;
this.label2.Location = new System.Drawing.Point(0, 0);
this.label2.Name = "label2";
this.label2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);
this.label2.Size = new System.Drawing.Size(32, 16);
this.label2.TabIndex = 0;
this.label2.Text = "Field:";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(392, 116);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label2;
``` |
26,732 | <pre><code><servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>workflow.WDispatcher</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>*NEXTEVENT*</url-pattern>
</servlet-mapping>
</code></pre>
<p>Above is the snippet from Tomcat's <code>web.xml</code>. The URL pattern <code>*NEXTEVENT*</code> on start up throws</p>
<blockquote>
<p>java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping</p>
</blockquote>
<p>It will be greatly appreciated if someone can hint at the error.
</p>
| [
{
"answer_id": 26744,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 8,
"selected": true,
"text": "<pre><code><url-pattern>*NEXTEVENT*</url-pattern>\n</code></pre>\n\n<p>The URL pattern is not valid. It can either end in an asterisk or start with one (to denote a file extension mapping).</p>\n\n<p>The url-pattern specification:</p>\n\n<blockquote>\n <ul>\n <li>A string beginning with a ‘/’ character and ending with a ‘/*’\n suffix is used for path mapping.</li>\n <li>A string beginning with a ‘*.’ prefix is used as an extension\n mapping.</li>\n <li>A string containing only the ’/’ character indicates the \"default\"\n servlet of the application. In this\n case the servlet path is the request\n URI minus the context path and the\n path info is null.</li>\n <li>All other strings are used for exact matches only.</li>\n </ul>\n</blockquote>\n\n<p>See section 12.2 of the <a href=\"https://jcp.org/aboutJava/communityprocess/final/jsr340/index.html\" rel=\"noreferrer\">Java Servlet Specification</a> Version 3.1 for more details.</p>\n"
},
{
"answer_id": 61951,
"author": "talg",
"author_id": 3332,
"author_profile": "https://Stackoverflow.com/users/3332",
"pm_score": 1,
"selected": false,
"text": "<p>A workaround that can achieve that is to add a servlet filter to do URL re-writes e.g.\nre-write <em>NEXTEVENT</em> to /NEXTEVENT/<em>(the one before the NEXTEVENT)/</em>(the one after NEXTEVENT) or something similar.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>workflow.WDispatcher</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>*NEXTEVENT*</url-pattern>
</servlet-mapping>
```
Above is the snippet from Tomcat's `web.xml`. The URL pattern `*NEXTEVENT*` on start up throws
>
> java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping
>
>
>
It will be greatly appreciated if someone can hint at the error.
| ```
<url-pattern>*NEXTEVENT*</url-pattern>
```
The URL pattern is not valid. It can either end in an asterisk or start with one (to denote a file extension mapping).
The url-pattern specification:
>
> * A string beginning with a ‘/’ character and ending with a ‘/\*’
> suffix is used for path mapping.
> * A string beginning with a ‘\*.’ prefix is used as an extension
> mapping.
> * A string containing only the ’/’ character indicates the "default"
> servlet of the application. In this
> case the servlet path is the request
> URI minus the context path and the
> path info is null.
> * All other strings are used for exact matches only.
>
>
>
See section 12.2 of the [Java Servlet Specification](https://jcp.org/aboutJava/communityprocess/final/jsr340/index.html) Version 3.1 for more details. |
26,733 | <p>Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?</p>
<p>This is what I want to re-write:</p>
<pre><code>foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
</code></pre>
| [
{
"answer_id": 26745,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": false,
"text": "<p>loop through all loaded assemblies, loop through all their types, and check if they implement the interface.</p>\n\n<p>something like:</p>\n\n<pre><code>Type ti = typeof(IYourInterface);\nforeach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {\n foreach (Type t in asm.GetTypes()) {\n if (ti.IsAssignableFrom(t)) {\n // here's your type in t\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 26750,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 11,
"selected": true,
"text": "<p>Mine would be this in c# 3.0 :)</p>\n\n<pre><code>var type = typeof(IMyInterface);\nvar types = AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .Where(p => type.IsAssignableFrom(p));\n</code></pre>\n\n<p>Basically, the least amount of iterations will always be:</p>\n\n<pre><code>loop assemblies \n loop types \n see if implemented.\n</code></pre>\n"
},
{
"answer_id": 26752,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 2,
"selected": false,
"text": "<p>Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.</p>\n\n<p>Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.</p>\n\n<pre><code>public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {\n List<Type> list = new List<Type>();\n IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();\n while (enumerator.MoveNext()) {\n try {\n Type[] types = ((Assembly) enumerator.Current).GetTypes();\n if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith(\"System.\"))) {\n IEnumerator enumerator2 = types.GetEnumerator();\n while (enumerator2.MoveNext()) {\n Type current = (Type) enumerator2.Current;\n if (type.IsInterface) {\n if (current.GetInterface(type.FullName) != null) {\n list.Add(current);\n }\n } else if (current.IsSubclassOf(type)) {\n list.Add(current);\n }\n }\n }\n } catch {\n }\n }\n return list;\n}\n</code></pre>\n\n<p>It's not pretty, I'll admit.</p>\n"
},
{
"answer_id": 26754,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 2,
"selected": false,
"text": "<p>There's no easy way (in terms of performance) to do what you want to do.</p>\n\n<p>Reflection works with assemblys and types mainly so you'll have to get all the types of the assembly and query them for the right interface. Here's an example:</p>\n\n<pre><code>Assembly asm = Assembly.Load(\"MyAssembly\");\nType[] types = asm.GetTypes();\nType[] result = types.where(x => x.GetInterface(\"IMyInterface\") != null);\n</code></pre>\n\n<p>That will get you all the types that implement the IMyInterface in the Assembly MyAssembly</p>\n"
},
{
"answer_id": 26766,
"author": "Ryan Rinaldi",
"author_id": 2278,
"author_profile": "https://Stackoverflow.com/users/2278",
"pm_score": -1,
"selected": false,
"text": "<p>You could use some LINQ to get the list:</p>\n\n<pre><code>var types = from type in this.GetType().Assembly.GetTypes()\n where type is ISomeInterface\n select type;\n</code></pre>\n\n<p>But really, is that more readable?</p>\n"
},
{
"answer_id": 26768,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 6,
"selected": false,
"text": "<p>To find all types in an assembly that implement IFoo interface:</p>\n\n<pre><code>var results = from type in someAssembly.GetTypes()\n where typeof(IFoo).IsAssignableFrom(type)\n select type;\n</code></pre>\n\n<p>Note that Ryan Rinaldi's suggestion was incorrect. It will return 0 types. You cannot write</p>\n\n<pre><code>where type is IFoo\n</code></pre>\n\n<p>because type is a System.Type instance, and will never be of type IFoo. Instead, you check to see if IFoo is assignable from the type. That will get your expected results.</p>\n\n<p>Also, Adam Wright's suggestion, which is currently marked as the answer, is incorrect as well, and for the same reason. At runtime, you'll see 0 types come back, because all System.Type instances weren't IFoo implementors.</p>\n"
},
{
"answer_id": 4165635,
"author": "Carl Nayak",
"author_id": 505851,
"author_profile": "https://Stackoverflow.com/users/505851",
"pm_score": 4,
"selected": false,
"text": "<p>This worked for me (if you wish you could exclude system types in the lookup):</p>\n\n<pre><code>Type lookupType = typeof (IMenuItem);\nIEnumerable<Type> lookupTypes = GetType().Assembly.GetTypes().Where(\n t => lookupType.IsAssignableFrom(t) && !t.IsInterface); \n</code></pre>\n"
},
{
"answer_id": 10947832,
"author": "hillstuk",
"author_id": 1298296,
"author_profile": "https://Stackoverflow.com/users/1298296",
"pm_score": 5,
"selected": false,
"text": "<p>Other answers here use <code>IsAssignableFrom</code>. You can also use <code>FindInterfaces</code> from the <code>System</code> namespace, as described <a href=\"http://msdn.microsoft.com/en-us/library/system.type.findinterfaces%28v=vs.100%29.aspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Here's an example that checks all assemblies in the currently executing assembly's folder, looking for classes that implement a certain interface (avoiding LINQ for clarity).</p>\n\n<pre><code>static void Main() {\n const string qualifiedInterfaceName = \"Interfaces.IMyInterface\";\n var interfaceFilter = new TypeFilter(InterfaceFilter);\n var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\n var di = new DirectoryInfo(path);\n foreach (var file in di.GetFiles(\"*.dll\")) {\n try {\n var nextAssembly = Assembly.ReflectionOnlyLoadFrom(file.FullName);\n foreach (var type in nextAssembly.GetTypes()) {\n var myInterfaces = type.FindInterfaces(interfaceFilter, qualifiedInterfaceName);\n if (myInterfaces.Length > 0) {\n // This class implements the interface\n }\n }\n } catch (BadImageFormatException) {\n // Not a .net assembly - ignore\n }\n }\n}\n\npublic static bool InterfaceFilter(Type typeObj, Object criteriaObj) {\n return typeObj.ToString() == criteriaObj.ToString();\n}\n</code></pre>\n\n<p>You can set up a list of interfaces if you want to match more than one.</p>\n"
},
{
"answer_id": 12602220,
"author": "Ben Watkins",
"author_id": 1700301,
"author_profile": "https://Stackoverflow.com/users/1700301",
"pm_score": 6,
"selected": false,
"text": "<p>This worked for me. It loops though the classes and checks to see if they are derrived from myInterface</p>\n\n<pre><code> foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()\n .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {\n //do stuff\n }\n</code></pre>\n"
},
{
"answer_id": 29379834,
"author": "rism",
"author_id": 70149,
"author_profile": "https://Stackoverflow.com/users/70149",
"pm_score": 6,
"selected": false,
"text": "<p>I appreciate this is a very old question but I thought I would add another answer for future users as all the answers to date use some form of <a href=\"https://msdn.microsoft.com/en-us/library/system.reflection.assembly.gettypes%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>Assembly.GetTypes</code></a>. </p>\n\n<p>Whilst GetTypes() will indeed return all types, it does not necessarily mean you could activate them and could thus potentially throw a <a href=\"https://msdn.microsoft.com/en-us/library/system.reflection.reflectiontypeloadexception%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>ReflectionTypeLoadException</code></a>.</p>\n\n<p>A classic example for not being able to activate a type would be when the type returned is <code>derived</code> from <code>base</code> but <code>base</code> is defined in a different assembly from that of <code>derived</code>, an assembly that the calling assembly does not reference. </p>\n\n<p>So say we have:</p>\n\n<pre><code>Class A // in AssemblyA\nClass B : Class A, IMyInterface // in AssemblyB\nClass C // in AssemblyC which references AssemblyB but not AssemblyA\n</code></pre>\n\n<p>If in <code>ClassC</code> which is in <code>AssemblyC</code> we then do something as per accepted answer:</p>\n\n<pre><code>var type = typeof(IMyInterface);\nvar types = AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .Where(p => type.IsAssignableFrom(p));\n</code></pre>\n\n<p>Then it will throw a <a href=\"https://msdn.microsoft.com/en-us/library/system.reflection.reflectiontypeloadexception%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>ReflectionTypeLoadException</code></a>. </p>\n\n<p>This is because without a reference to <code>AssemblyA</code> in <code>AssemblyC</code> you would not be able to:</p>\n\n<pre><code>var bType = typeof(ClassB);\nvar bClass = (ClassB)Activator.CreateInstance(bType);\n</code></pre>\n\n<p>In other words <code>ClassB</code> is not <em>loadable</em> which is something that the call to GetTypes checks and throws on.</p>\n\n<p>So to safely qualify the result set for loadable types then as per this <a href=\"http://haacked.com/\" rel=\"noreferrer\">Phil Haacked</a> article <a href=\"http://haacked.com/archive/2012/07/23/get-all-types-in-an-assembly.aspx/\" rel=\"noreferrer\">Get All Types in an Assembly</a> and <a href=\"https://stackoverflow.com/questions/7889228/how-to-prevent-reflectiontypeloadexception-when-calling-assembly-gettypes\">Jon Skeet code</a> you would instead do something like:</p>\n\n<pre><code>public static class TypeLoaderExtensions {\n public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) {\n if (assembly == null) throw new ArgumentNullException(\"assembly\");\n try {\n return assembly.GetTypes();\n } catch (ReflectionTypeLoadException e) {\n return e.Types.Where(t => t != null);\n }\n }\n}\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>private IEnumerable<Type> GetTypesWithInterface(Assembly asm) {\n var it = typeof (IMyInterface);\n return asm.GetLoadableTypes().Where(it.IsAssignableFrom).ToList();\n}\n</code></pre>\n"
},
{
"answer_id": 49006805,
"author": "akop",
"author_id": 6537157,
"author_profile": "https://Stackoverflow.com/users/6537157",
"pm_score": 0,
"selected": false,
"text": "<p>I got exceptions in the linq-code so I do it this way (without a complicated extension):</p>\n\n<pre><code>private static IList<Type> loadAllImplementingTypes(Type[] interfaces)\n{\n IList<Type> implementingTypes = new List<Type>();\n\n // find all types\n foreach (var interfaceType in interfaces)\n foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())\n try\n {\n foreach (var currentType in currentAsm.GetTypes())\n if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)\n implementingTypes.Add(currentType);\n }\n catch { }\n\n return implementingTypes;\n}\n</code></pre>\n"
},
{
"answer_id": 52411210,
"author": "Antonin GAVREL",
"author_id": 3161139,
"author_profile": "https://Stackoverflow.com/users/3161139",
"pm_score": 3,
"selected": false,
"text": "<p>Other answer were not working with a <strong>generic interface</strong>.</p>\n\n<p>This one does, just replace typeof(ISomeInterface) by typeof (T).</p>\n\n<pre><code>List<string> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())\n .Where(x => typeof(ISomeInterface).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)\n .Select(x => x.Name).ToList();\n</code></pre>\n\n<p>So with</p>\n\n<pre><code>AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())\n</code></pre>\n\n<p>we get all the assemblies</p>\n\n<pre><code>!x.IsInterface && !x.IsAbstract\n</code></pre>\n\n<p>is used to exclude the interface and abstract ones and</p>\n\n<pre><code>.Select(x => x.Name).ToList();\n</code></pre>\n\n<p>to have them in a list.</p>\n"
},
{
"answer_id": 54297288,
"author": "user489566",
"author_id": 10558750,
"author_profile": "https://Stackoverflow.com/users/10558750",
"pm_score": 2,
"selected": false,
"text": "<p>Even better when choosing the Assembly location. Filter most of the assemblies if you know all your implemented interfaces are within the same Assembly.DefinedTypes.</p>\n\n<pre><code>// We get the assembly through the base class\nvar baseAssembly = typeof(baseClass).GetTypeInfo().Assembly;\n\n// we filter the defined classes according to the interfaces they implement\nvar typeList = baseAssembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(IMyInterface))).ToList();\n</code></pre>\n\n<p><a href=\"https://social.msdn.microsoft.com/Forums/en-US/abf6e015-3ece-4eab-85c9-d1878a5135e6/reflection-getting-all-classes-that-implement-a-given-interface?forum=winappswithcsharp\" rel=\"nofollow noreferrer\">By Can Bilgin</a></p>\n"
},
{
"answer_id": 57359586,
"author": "Jonathan Santiago",
"author_id": 4457506,
"author_profile": "https://Stackoverflow.com/users/4457506",
"pm_score": -1,
"selected": false,
"text": "<pre><code> public IList<T> GetClassByType<T>()\n {\n return AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .ToList(p => typeof(T)\n .IsAssignableFrom(p) && !p.IsAbstract && !p.IsInterface)\n .SelectList(c => (T)Activator.CreateInstance(c));\n }\n</code></pre>\n"
},
{
"answer_id": 60841252,
"author": "Hamdi Baligh",
"author_id": 1745172,
"author_profile": "https://Stackoverflow.com/users/1745172",
"pm_score": 0,
"selected": false,
"text": "<p>OfType Linq method can be used exactly for this kind of scenarios:</p>\n\n<p><a href=\"https://learn.microsoft.com/fr-fr/dotnet/api/system.linq.enumerable.oftype?view=netframework-4.8\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/fr-fr/dotnet/api/system.linq.enumerable.oftype?view=netframework-4.8</a></p>\n"
},
{
"answer_id": 60949971,
"author": "diegosasw",
"author_id": 2948212,
"author_profile": "https://Stackoverflow.com/users/2948212",
"pm_score": 1,
"selected": false,
"text": "<p>There are many valid answers already but I'd like to add anther implementation as a Type extension and a list of unit tests to demonstrate different scenarios:</p>\n\n<pre><code>public static class TypeExtensions\n{\n public static IEnumerable<Type> GetAllTypes(this Type type)\n {\n var typeInfo = type.GetTypeInfo();\n var allTypes = GetAllImplementedTypes(type).Concat(typeInfo.ImplementedInterfaces);\n return allTypes;\n }\n\n private static IEnumerable<Type> GetAllImplementedTypes(Type type)\n {\n yield return type;\n var typeInfo = type.GetTypeInfo();\n var baseType = typeInfo.BaseType;\n if (baseType != null)\n {\n foreach (var foundType in GetAllImplementedTypes(baseType))\n {\n yield return foundType;\n }\n }\n }\n}\n</code></pre>\n\n<p>This algorithm supports the following scenarios:</p>\n\n<pre><code>public static class GetAllTypesTests\n{\n public class Given_A_Sample_Standalone_Class_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(SampleStandalone);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(SampleStandalone),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Abstract_Base_Class_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(SampleBase);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(SampleBase),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Child_Class_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(SampleChild);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(SampleChild),\n typeof(SampleBase),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Base_Interface_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(ISampleBase);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(ISampleBase)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Child_Interface_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(ISampleChild);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(ISampleBase),\n typeof(ISampleChild)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Implementation_Class_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(SampleImplementation);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(SampleImplementation),\n typeof(SampleChild),\n typeof(SampleBase),\n typeof(ISampleChild),\n typeof(ISampleBase),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Interface_Instance_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n class Foo : ISampleChild { }\n\n protected override void Given()\n {\n var foo = new Foo();\n _sut = foo.GetType();\n\n _expectedTypes =\n new List<Type>\n {\n typeof(Foo),\n typeof(ISampleChild),\n typeof(ISampleBase),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n sealed class SampleStandalone { }\n abstract class SampleBase { }\n class SampleChild : SampleBase { }\n interface ISampleBase { }\n interface ISampleChild : ISampleBase { }\n class SampleImplementation : SampleChild, ISampleChild { }\n}\n</code></pre>\n"
},
{
"answer_id": 63209158,
"author": "rvnlord",
"author_id": 3783852,
"author_profile": "https://Stackoverflow.com/users/3783852",
"pm_score": 3,
"selected": false,
"text": "<p>I see so many overcomplicated answers here and people always tell me that I tend to overcomplicate things. Also using <code>IsAssignableFrom</code> method for the purpose of solving OP problem is wrong!</p>\n<p>Here is my example, it selects all assemblies from the app domain, then it takes flat list of all available types and checks every single type's list of interfaces for match:</p>\n<pre><code>public static IEnumerable<Type> GetImplementingTypes(this Type itype) \n => AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes())\n .Where(t => t.GetInterfaces().Contains(itype));\n</code></pre>\n"
},
{
"answer_id": 66900943,
"author": "chtenb",
"author_id": 1546844,
"author_profile": "https://Stackoverflow.com/users/1546844",
"pm_score": 3,
"selected": false,
"text": "<p>All the answers posted thus far either take too few or too many assemblies into account. You need to only inspect the assemblies that reference the assembly containing the interface. This minimizes the number of static constructors being run unnecessarily and save a huge amount of time and possibly unexpected side effects in the case of third party assemblies.</p>\n<pre><code>public static class ReflectionUtils\n{\n public static bool DoesTypeSupportInterface(Type type, Type inter)\n {\n if (inter.IsAssignableFrom(type))\n return true;\n if (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))\n return true;\n return false;\n }\n\n public static IEnumerable<Assembly> GetReferencingAssemblies(Assembly assembly)\n {\n return AppDomain\n .CurrentDomain\n .GetAssemblies().Where(asm => asm.GetReferencedAssemblies().Any(asmName => AssemblyName.ReferenceMatchesDefinition(asmName, assembly.GetName())));\n }\n\n public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)\n {\n var assembliesToSearch = new Assembly[] { desiredType.Assembly }\n .Concat(GetReferencingAssemblies(desiredType.Assembly));\n return assembliesToSearch.SelectMany(assembly => assembly.GetTypes())\n .Where(type => DoesTypeSupportInterface(type, desiredType));\n }\n\n public static IEnumerable<Type> NonAbstractTypesImplementingInterface(Type desiredType)\n {\n return TypesImplementingInterface(desiredType).Where(t => !t.IsAbstract);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 72022365,
"author": "classicSchmosby98",
"author_id": 7368872,
"author_profile": "https://Stackoverflow.com/users/7368872",
"pm_score": 0,
"selected": false,
"text": "<p>If it helps anyone, this is what I'm using to make some of my unit tests easier :)</p>\n<pre><code>public static Type GetInterfacesImplementation(this Type type)\n{\n return type.Assembly.GetTypes()\n .Where(p => type.IsAssignableFrom(p) && !p.IsInterface)\n .SingleOrDefault();\n}\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
This is what I want to re-write:
```
foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
``` | Mine would be this in c# 3.0 :)
```
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
```
Basically, the least amount of iterations will always be:
```
loop assemblies
loop types
see if implemented.
``` |
26,743 | <p>I use .NET XML technologies quite extensively on my work. One of the things the I like very much is the XSLT engine, more precisely the extensibility of it. However there one little piece which keeps being a source of annoyance. Nothing major or something we can't live with but it is preventing us from producing the beautiful XML we would like to produce. </p>
<p>One of the things we do is transform nodes inline and importing nodes from one XML document to another. </p>
<p>Sadly , when you save nodes to an <code>XmlTextWriter</code> (actually whatever <code>XmlWriter.Create(Stream)</code> returns), the namespace definitions get all thrown in there, regardless of it is necessary (previously defined) or not. You get kind of the following xml:</p>
<pre><code><root xmlns:abx="http://bladibla">
<abx:child id="A">
<grandchild id="B">
<abx:grandgrandchild xmlns:abx="http://bladibla" />
</grandchild>
</abx:child>
</root>
</code></pre>
<p>Does anyone have a suggestion as to how to convince .NET to be efficient about its namespace definitions?</p>
<p>PS. As an added bonus I would like to override the default namespace, changing it as I write a node.</p>
| [
{
"answer_id": 6421794,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure this is what you're looking for, but you can use this kind of code when you start writing to the Xml stream:</p>\n\n<pre><code>myWriter.WriteAttributeString(\"xmlns\", \"abx\", null, \"http://bladibla\");\n</code></pre>\n\n<p>The XmlWriter should remember it and not rewrite it anymore. It may not be 100% bulletproof, but it works most of the time.</p>\n"
},
{
"answer_id": 6482730,
"author": "Kirill Polishchuk",
"author_id": 787016,
"author_profile": "https://Stackoverflow.com/users/787016",
"pm_score": 4,
"selected": false,
"text": "<p>Use this code:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>using (var writer = XmlWriter.Create(\"file.xml\"))\n{\n const string Ns = \"http://bladibla\";\n const string Prefix = \"abx\";\n\n writer.WriteStartDocument();\n\n writer.WriteStartElement(\"root\");\n\n // set root namespace\n writer.WriteAttributeString(\"xmlns\", Prefix, null, Ns);\n\n writer.WriteStartElement(Prefix, \"child\", Ns);\n writer.WriteAttributeString(\"id\", \"A\");\n\n writer.WriteStartElement(\"grandchild\");\n writer.WriteAttributeString(\"id\", \"B\");\n\n writer.WriteElementString(Prefix, \"grandgrandchild\", Ns, null);\n\n // grandchild\n writer.WriteEndElement();\n // child\n writer.WriteEndElement();\n // root\n writer.WriteEndElement();\n\n writer.WriteEndDocument();\n}\n</code></pre>\n\n<p>This code produced desired output:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root xmlns:abx=\"http://bladibla\">\n <abx:child id=\"A\">\n <grandchild id=\"B\">\n <abx:grandgrandchild />\n </grandchild>\n </abx:child>\n</root>\n</code></pre>\n"
},
{
"answer_id": 6493730,
"author": "habakuk",
"author_id": 254041,
"author_profile": "https://Stackoverflow.com/users/254041",
"pm_score": 2,
"selected": false,
"text": "<p>Did you try this?</p>\n\n<pre><code>Dim settings = New XmlWriterSettings With {.Indent = True,\n .NamespaceHandling = NamespaceHandling.OmitDuplicates,\n .OmitXmlDeclaration = True}\nDim s As New MemoryStream\nUsing writer = XmlWriter.Create(s, settings)\n ...\nEnd Using\n</code></pre>\n\n<p>Interesting is the 'NamespaceHandling.OmitDuplicates'</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2892/"
] | I use .NET XML technologies quite extensively on my work. One of the things the I like very much is the XSLT engine, more precisely the extensibility of it. However there one little piece which keeps being a source of annoyance. Nothing major or something we can't live with but it is preventing us from producing the beautiful XML we would like to produce.
One of the things we do is transform nodes inline and importing nodes from one XML document to another.
Sadly , when you save nodes to an `XmlTextWriter` (actually whatever `XmlWriter.Create(Stream)` returns), the namespace definitions get all thrown in there, regardless of it is necessary (previously defined) or not. You get kind of the following xml:
```
<root xmlns:abx="http://bladibla">
<abx:child id="A">
<grandchild id="B">
<abx:grandgrandchild xmlns:abx="http://bladibla" />
</grandchild>
</abx:child>
</root>
```
Does anyone have a suggestion as to how to convince .NET to be efficient about its namespace definitions?
PS. As an added bonus I would like to override the default namespace, changing it as I write a node. | Use this code:
```cs
using (var writer = XmlWriter.Create("file.xml"))
{
const string Ns = "http://bladibla";
const string Prefix = "abx";
writer.WriteStartDocument();
writer.WriteStartElement("root");
// set root namespace
writer.WriteAttributeString("xmlns", Prefix, null, Ns);
writer.WriteStartElement(Prefix, "child", Ns);
writer.WriteAttributeString("id", "A");
writer.WriteStartElement("grandchild");
writer.WriteAttributeString("id", "B");
writer.WriteElementString(Prefix, "grandgrandchild", Ns, null);
// grandchild
writer.WriteEndElement();
// child
writer.WriteEndElement();
// root
writer.WriteEndElement();
writer.WriteEndDocument();
}
```
This code produced desired output:
```
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:abx="http://bladibla">
<abx:child id="A">
<grandchild id="B">
<abx:grandgrandchild />
</grandchild>
</abx:child>
</root>
``` |
26,760 | <p>I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?</p>
| [
{
"answer_id": 26769,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 6,
"selected": true,
"text": "<p>This seems to work, though it is a bit hackish:</p>\n\n<pre><code>TimeSpan span;\n\n\nif (TimeSpan.TryParse(\"05h:30m\".Replace(\"m\",\"\").Replace(\"h\",\"\"), out span))\n MessageBox.Show(span.ToString());\n</code></pre>\n"
},
{
"answer_id": 26775,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 1,
"selected": false,
"text": "<p>Are <a href=\"http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx\" rel=\"nofollow noreferrer\">TimeSpan.Parse</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.timespan.tryparse.aspx\" rel=\"nofollow noreferrer\">TimeSpan.TryParse</a> not options? If you aren't using an \"approved\" format, you'll need to do the parsing manually. I'd probably capture your two integer values in a regular expression, and then try to parse them into integers, from there you can create a new TimeSpan with its constructor.</p>\n"
},
{
"answer_id": 26778,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "<p><code>DateTime.ParseExact</code> or <code>DateTime.TryParseExact</code> lets you specify the exact format of the input. After you get the <code>DateTime</code>, you can grab the <code>DateTime.TimeOfDay</code> which is a <code>TimeSpan</code>.</p>\n\n<p>In the absence of <code>TimeSpan.TryParseExact</code>, I think an 'elegant' solution is out of the mix.</p>\n\n<p>@buyutec As you suspected, this method would not work if the time spans have more than 24 hours.</p>\n"
},
{
"answer_id": 26780,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 2,
"selected": false,
"text": "<p>Here'e one possibility:</p>\n\n<pre><code>TimeSpan.Parse(s.Remove(2, 1).Remove(5, 1));\n</code></pre>\n\n<p>And if you want to make it more elegant in your code, use an extension method:</p>\n\n<pre><code>public static TimeSpan ToTimeSpan(this string s)\n{\n TimeSpan t = TimeSpan.Parse(s.Remove(2, 1).Remove(5, 1));\n return t;\n}\n</code></pre>\n\n<p>Then you can do </p>\n\n<pre><code>\"05h:30m\".ToTimeSpan();\n</code></pre>\n"
},
{
"answer_id": 952947,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>From another thread:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/62804/how-to-convert-xs-duration-to-timespan-in-vb-net/63219#63219\">How to convert xs:duration to timespan</a></p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan? | This seems to work, though it is a bit hackish:
```
TimeSpan span;
if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))
MessageBox.Show(span.ToString());
``` |
26,795 | <p>I have an extender (IExtenderProvider) which extends certain types of
controls with additional properties. For one of these properties, I have
written a UITypeEditor. So far, all works just fine.</p>
<p>The extender also has a couple of properties itself, which I am trying to
use as a sort of default for the UITypeEditor. What I want to do is to be
able to set a property on the extender itself (not the extended controls),
and when I open up the UITypeEditor for one of the additional properties on
an extended control, I want to set a value in the UITypeEditor to the value
of the property on the extender.</p>
<p>A simple example: The ExtenderProvider has a property DefaultExtendedValue. On the form I set the value of this property to "My Value". Extended controls have, through the provider, a property ExtendedValue with a UITypeEditor. When I open the editor for the property ExtendedValue the default (initial) value should be set to "My Value".</p>
<p>It seems to me that the best place to do this would be
UITypeEditor.EditValue, just before calling
IWindowsFormsEditorService.DropDownControl or .ShowDialog.</p>
<p>The only problem is that I can't (or I haven't discovered how to) get hold
of the extender provider itself in EditValue, to read the value of the property in question and set it in the UITypeEditor. Context gives me the extended
control, but that is of no use to me in this case.</p>
<p>Is there any way to achieve what I'm trying? Any help appreciated!</p>
<p>Thanks
Tom</p>
<hr>
<p>@samjudson: That's not a bad idea, but unfortunately it doesn't quite get me there. I'd really like to be able to set this default value individually for each instance of the extender provider. (I might have more than one on a single form with different values for different groups of extended controls.)</p>
| [
{
"answer_id": 30275,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>Have you considered adding the DefaultValue as a static property of the ExtenderProvider, then you can access it without requiring an instance of the provider?</p>\n"
},
{
"answer_id": 187256,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>Could you read the attribute yourself?</p>\n\n<pre><code>DefaultValueAttribute att = context.\n PropertyDescriptor.Attributes.\n OfType<DefaultValueAttribute>().\n FirstOrDefault();\nobject myDefault = null;\nif ( att != null )\n myDefault = att.Value;\n</code></pre>\n\n<p>I've used Linq to simplify the code, but you could do something similar back in .Net 1</p>\n"
},
{
"answer_id": 2193027,
"author": "Larry",
"author_id": 24472,
"author_profile": "https://Stackoverflow.com/users/24472",
"pm_score": 1,
"selected": false,
"text": "<p>Hi I have found this : <a href=\"http://social.msdn.microsoft.com/forums/en-US/winformsdesigner/thread/07299eb0-3e21-42a3-b36b-12e37282af83/\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/forums/en-US/winformsdesigner/thread/07299eb0-3e21-42a3-b36b-12e37282af83/</a></p>\n\n<p>Basically :</p>\n\n<pre><code>var Ctl = context.Instance as Control;\n\nType t = Type.GetType(\"System.ComponentModel.ExtendedPropertyDescriptor\");\nLocalizationProvider myProvider = GetValueOnPrivateMember(t, context.PropertyDescriptor, \"provider\") as MyOwnExtenderProvider;\n</code></pre>\n\n<p>And magically, myProvider got my IExtenderProvider control !</p>\n\n<p>where GetValueOnPrivateMember should be implemented this way:</p>\n\n<pre><code>static object GetValueOnPrivateMember(Type type, object dataobject, string fieldname)\n {\n BindingFlags getFieldBindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField;\n return type.InvokeMember(fieldname,\n getFieldBindingFlags,\n null,\n dataobject,\n null);\n }\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2899/"
] | I have an extender (IExtenderProvider) which extends certain types of
controls with additional properties. For one of these properties, I have
written a UITypeEditor. So far, all works just fine.
The extender also has a couple of properties itself, which I am trying to
use as a sort of default for the UITypeEditor. What I want to do is to be
able to set a property on the extender itself (not the extended controls),
and when I open up the UITypeEditor for one of the additional properties on
an extended control, I want to set a value in the UITypeEditor to the value
of the property on the extender.
A simple example: The ExtenderProvider has a property DefaultExtendedValue. On the form I set the value of this property to "My Value". Extended controls have, through the provider, a property ExtendedValue with a UITypeEditor. When I open the editor for the property ExtendedValue the default (initial) value should be set to "My Value".
It seems to me that the best place to do this would be
UITypeEditor.EditValue, just before calling
IWindowsFormsEditorService.DropDownControl or .ShowDialog.
The only problem is that I can't (or I haven't discovered how to) get hold
of the extender provider itself in EditValue, to read the value of the property in question and set it in the UITypeEditor. Context gives me the extended
control, but that is of no use to me in this case.
Is there any way to achieve what I'm trying? Any help appreciated!
Thanks
Tom
---
@samjudson: That's not a bad idea, but unfortunately it doesn't quite get me there. I'd really like to be able to set this default value individually for each instance of the extender provider. (I might have more than one on a single form with different values for different groups of extended controls.) | Could you read the attribute yourself?
```
DefaultValueAttribute att = context.
PropertyDescriptor.Attributes.
OfType<DefaultValueAttribute>().
FirstOrDefault();
object myDefault = null;
if ( att != null )
myDefault = att.Value;
```
I've used Linq to simplify the code, but you could do something similar back in .Net 1 |
26,796 | <p>What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:</p>
<pre><code>Dim x As New System.Web.UI.Control
x.ResolveUrl("~/someUrl")
</code></pre>
<p>Or C#:</p>
<pre><code>System.Web.UI.Control x = new System.Web.UI.Control();
x.ResolveUrl("~/someUrl");
</code></pre>
<p>But I realize that isn't the best way of calling it.</p>
| [
{
"answer_id": 26807,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 7,
"selected": true,
"text": "<p>I use <a href=\"http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility.aspx\" rel=\"noreferrer\">System.Web.VirtualPathUtility.ToAbsolute</a>.</p>\n"
},
{
"answer_id": 26812,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>I tend to use HttpContext.Current to get the page, then run any page/web control methods off that.</p>\n"
},
{
"answer_id": 528198,
"author": "jdw",
"author_id": 64181,
"author_profile": "https://Stackoverflow.com/users/64181",
"pm_score": 5,
"selected": false,
"text": "<p>It's worth noting that although System.Web.VirtualPathUtility.ToAbsolute is very useful here, it is <strong>not</strong> a perfect replacement for Control.ResolveUrl.</p>\n\n<p>There is at least one significant difference: Control.ResolveUrl handles Query Strings very nicely, but they cause VirtualPathUtility to throw an HttpException. This can be absolutely mystifying the first time it happens, especially if you're used to the way that Control.ResolveUrl works.</p>\n\n<p>If you know the exact structure of the Query String you want to use, this is easy enough to work around, viz:</p>\n\n<pre><code>public static string GetUrl(int id)\n{\n string path = VirtualPathUtility.ToAbsolute(\"~/SomePage.aspx\");\n return string.Format(\"{0}?id={1}\", path, id);\n}\n</code></pre>\n\n<p>...but if the Query String is getting passed in from an unknown source then you're going to need to parse it out somehow. (Before you get too deep into that, note that System.Uri might be able to do it for you).</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:
```
Dim x As New System.Web.UI.Control
x.ResolveUrl("~/someUrl")
```
Or C#:
```
System.Web.UI.Control x = new System.Web.UI.Control();
x.ResolveUrl("~/someUrl");
```
But I realize that isn't the best way of calling it. | I use [System.Web.VirtualPathUtility.ToAbsolute](http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility.aspx). |
26,800 | <p>I'm using XPath in .NET to parse an XML document, along the lines of:</p>
<pre class="lang-cs prettyprint-override"><code>XmlNodeList lotsOStuff = doc.SelectNodes("//stuff");
foreach (XmlNode stuff in lotsOStuff) {
XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild");
// ... etc
}
</code></pre>
<p>The issue is that the XPath Query for <code>stuffChild</code> is always returning the child of the first <code>stuff</code> element, never the rest. Can XPath not be used to query against an individual <code>XMLElement</code>?</p>
| [
{
"answer_id": 26805,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": true,
"text": "<p><code>//</code> at the beginning of an XPath expression starts from the document root. Try \".//stuffChild\". . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.</p>\n\n<p>So you have:</p>\n\n<pre><code>XmlNode stuffChild = stuff.SelectSingleNode(\".//stuffChild\");\n</code></pre>\n\n<p>which translates to:</p>\n\n<p><strike>xmlNode stuffChild = stuff.SelectSingleNode(\"self::node()/descendant::stuffChild\");</strike></p>\n\n<pre><code>xmlNode stuffChild = stuff.SelectSingleNode(\"self::node()/descendant-or-self::stuffChild\");\n</code></pre>\n\n<p>In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:</p>\n\n<pre><code>xmlNode stuffChild = stuff.SelectSingleNode(\"self::node()/descendant::stuffChild\");\n</code></pre>\n\n<p>Also note that if \"stuffChild\" is a direct descendant of \"stuff\", you can completely omit the prefixes, and just select \"stuffChild\".</p>\n\n<pre><code>XmlNode stuffChild = stuff.SelectSingleNode(\"stuffChild\");\n</code></pre>\n\n<p>The <a href=\"http://www.w3schools.com/xsl/xpath_syntax.asp\" rel=\"nofollow noreferrer\">W3Schools</a> tutorial has helpful info in an easy to digest format.</p>\n"
},
{
"answer_id": 26813,
"author": "Tom Lokhorst",
"author_id": 2597,
"author_profile": "https://Stackoverflow.com/users/2597",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>//</code> you use in front of <code>stuffChild</code> means you're looking for <code>stuffChild</code> elements, starting from the root.</p>\n\n<p>If you want to start from the current node (decendants of the current node), you should use <code>.//</code>, as in:</p>\n\n<pre><code>stuff.SelectSingleNode(\".//stuffChild\");\n</code></pre>\n"
},
{
"answer_id": 26817,
"author": "Rob Thomas",
"author_id": 803,
"author_profile": "https://Stackoverflow.com/users/803",
"pm_score": 1,
"selected": false,
"text": "<p>If \"stuffChild\" is a child node of \"stuff\", then your xpath should just be:</p>\n\n<pre><code>XmlNode stuffChild = stuff.SelectSingleNode(\"stuffChild\");\n</code></pre>\n"
},
{
"answer_id": 596498,
"author": "Azat Razetdinov",
"author_id": 9649,
"author_profile": "https://Stackoverflow.com/users/9649",
"pm_score": -1,
"selected": false,
"text": "<p>Selecting single node means you need only the first element. So, the best solution is:</p>\n\n<pre><code>XmlNode stuffChild = stuff.SelectSingleNode(\"descendant::stuffChild[1]\");\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm using XPath in .NET to parse an XML document, along the lines of:
```cs
XmlNodeList lotsOStuff = doc.SelectNodes("//stuff");
foreach (XmlNode stuff in lotsOStuff) {
XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild");
// ... etc
}
```
The issue is that the XPath Query for `stuffChild` is always returning the child of the first `stuff` element, never the rest. Can XPath not be used to query against an individual `XMLElement`? | `//` at the beginning of an XPath expression starts from the document root. Try ".//stuffChild". . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.
So you have:
```
XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild");
```
which translates to:
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
```
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild");
```
In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:
```
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
```
Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild".
```
XmlNode stuffChild = stuff.SelectSingleNode("stuffChild");
```
The [W3Schools](http://www.w3schools.com/xsl/xpath_syntax.asp) tutorial has helpful info in an easy to digest format. |
26,809 | <p>I frequently have problems dealing with <code>DataRows</code> returned from <code>SqlDataAdapters</code>. When I try to fill in an object using code like this:</p>
<pre><code>DataRow row = ds.Tables[0].Rows[0];
string value = (string)row;
</code></pre>
<p>What is the best way to deal with <code>DBNull's</code> in this type of situation.</p>
| [
{
"answer_id": 26832,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 6,
"selected": true,
"text": "<p>Nullable types are good, but only for types that are not nullable to begin with.</p>\n\n<p>To make a type \"nullable\" append a question mark to the type, for example: </p>\n\n<pre><code>int? value = 5;\n</code></pre>\n\n<p>I would also recommend using the \"<code>as</code>\" keyword instead of casting. You can only use the \"as\" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is </p>\n\n<ol>\n<li>If a type is nullable, the \"<code>as</code>\" keyword returns <code>null</code> if a value is <code>DBNull</code>.</li>\n<li>It's <a href=\"http://www.codeproject.com/Articles/8052/Type-casting-impact-over-execution-performance-in\" rel=\"noreferrer\">ever-so-slightly faster than casting</a> though <a href=\"https://stackoverflow.com/a/496167/392\">only in certain cases</a>. This on its own is never a good enough reason to use <code>as</code>, but coupled with the reason above it's useful.</li>\n</ol>\n\n<p>I'd recommend doing something like this</p>\n\n<pre><code>DataRow row = ds.Tables[0].Rows[0];\nstring value = row as string;\n</code></pre>\n\n<p>In the case above, if <code>row</code> comes back as <code>DBNull</code>, then <code>value</code> will become <code>null</code> instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned, <strong>using <code>as</code> will cause your code to silently fail</strong> and make values simple <code>null</code> instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves.</p>\n"
},
{
"answer_id": 26841,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 1,
"selected": false,
"text": "<p>You can also test with <a href=\"http://msdn.microsoft.com/en-us/library/system.convert.isdbnull.aspx\" rel=\"nofollow noreferrer\">Convert.IsDBNull (MSDN)</a>.</p>\n"
},
{
"answer_id": 26853,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>Add a reference to <code>System.Data.DataSetExtensions</code>, that adds Linq support for querying data tables.</p>\n\n<p>This would be something like:</p>\n\n<pre><code>string value = (\n from row in ds.Tables[0].Rows\n select row.Field<string>(0) ).FirstOrDefault();\n</code></pre>\n"
},
{
"answer_id": 27075,
"author": "Manu",
"author_id": 2133,
"author_profile": "https://Stackoverflow.com/users/2133",
"pm_score": 1,
"selected": false,
"text": "<p>I usually write my own ConvertDBNull class that wraps the built-in Convert class. If the value is DBNull it will return null if its a reference type or the default value if its a value type. \nExample: \n - <code>ConvertDBNull.ToInt64(object obj)</code> returns <code>Convert.ToInt64(obj)</code> unless obj is DBNull in which case it will return 0.</p>\n"
},
{
"answer_id": 27082,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 4,
"selected": false,
"text": "<p>If you aren't using nullable types, the best thing to do is check to see if the column's value is DBNull. If it is DBNull, then set your reference to what you use for null/empty for the corresponding datatype.</p>\n\n<pre><code>DataRow row = ds.Tables[0].Rows[0];\nstring value;\n\nif (row[\"fooColumn\"] == DBNull.Value)\n{\n value = string.Empty;\n}\nelse \n{\n value = Convert.ToString(row[\"fooColumn\"]);\n}\n</code></pre>\n\n<p>As Manu said, you can create a convert class with an overloaded convert method per type so you don't have to pepper your code with if/else blocks.</p>\n\n<p>I will however stress that nullable types is the better route to go if you can use them. The reasoning is that with non-nullable types, you are going to have to resort to \"magic numbers\" to represent null. For example, if you are mapping a column to an int variable, how are you going to represent DBNull? Often you can't use 0 because 0 has a valid meaning in most programs. Often I see people map DBNull to int.MinValue, but that could potentially be problematic too. My best advice is this: </p>\n\n<ul>\n<li>For columns that can be null in the database, use nullable types. </li>\n<li>For columns that cannot be null in the database, use regular types. </li>\n</ul>\n\n<p>Nullable types were made to solve this problem. That being said, if you are on an older version of the framework or work for someone who doesn't grok nullable types, the code example will do the trick. </p>\n"
},
{
"answer_id": 27093,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "<p>For some reason I've had problems with doing a check against DBNull.Value, so I've done things slightly different and leveraged a property within the DataRow object:</p>\n\n<pre><code>if (row.IsNull[\"fooColumn\"])\n{\n value = string.Empty();\n}\n{\nelse\n{\n value = row[\"fooColumn\"].ToString;\n}\n</code></pre>\n"
},
{
"answer_id": 49006,
"author": "Steve Schoon",
"author_id": 3881,
"author_profile": "https://Stackoverflow.com/users/3881",
"pm_score": 3,
"selected": false,
"text": "<p>If you have control of the query that is returning the results, you can use ISNULL() to return non-null values like this:</p>\n\n<pre><code>SELECT \n ISNULL(name,'') AS name\n ,ISNULL(age, 0) AS age\nFROM \n names\n</code></pre>\n\n<p>If your situation can tolerate these magic values to substitute for NULL, taking this approach can fix the issue through your entire app without cluttering your code.</p>\n"
},
{
"answer_id": 66201,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": 3,
"selected": false,
"text": "<p>I always found it clear, concise, and problem free using a version of the If/Else check, only with the ternary operator. Keeps everything on one row, including assigning a default value if the column is null.</p>\n\n<p>So, assuming a nullable Int32 column named \"MyCol\", where we want to return -99 if the column is null, but return the integer value if the column is not null:</p>\n\n<pre><code>return row[\"MyCol\"] == DBNull.Value ? -99 : Convert.ToInt32(Row[\"MyCol\"]);\n</code></pre>\n\n<p>It is the same method as the If/Else winner above - But I've found if you're reading multiple columns in from a datareader, it's a real bonus having all the column-read lines one under another, lined up, as it's easier to spot errors:</p>\n\n<pre><code>Object.ID = DataReader[\"ID\"] == DBNull.Value ? -99 : Convert.ToInt32(DataReader[\"ID\"]);\nObject.Name = DataReader[\"Name\"] == DBNull.Value ? \"None\" : Convert.ToString(DataReader[\"Name\"]);\nObject.Price = DataReader[\"Price\"] == DBNull.Value ? 0.0 : Convert.ToFloat(DataReader[\"Price\"]);\n</code></pre>\n"
},
{
"answer_id": 234189,
"author": "Dejan",
"author_id": 11471,
"author_profile": "https://Stackoverflow.com/users/11471",
"pm_score": 0,
"selected": false,
"text": "<p>If you are concerned with getting DBNull when expecting strings, one option is to convert all the DBNull values in the DataTable into empty string.</p>\n\n<p>It is quite simple to do it but it would add some overhead especially if you are dealing with large DataTables. Check this <a href=\"http://www.ddejan.com/post/2008/10/24/Cleaning-DBNull-values-in-a-DataTable.aspx\" rel=\"nofollow noreferrer\">link</a> that shows how to do it if you are interested</p>\n"
},
{
"answer_id": 534305,
"author": "Simon",
"author_id": 53158,
"author_profile": "https://Stackoverflow.com/users/53158",
"pm_score": 1,
"selected": false,
"text": "<p>Brad Abrams posted something related just a couple of days ago\n<a href=\"http://blogs.msdn.com/brada/archive/2009/02/09/framework-design-guidelines-system-dbnull.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/brada/archive/2009/02/09/framework-design-guidelines-system-dbnull.aspx</a></p>\n\n<p>In Summary \"AVOID using System.DBNull. Prefer Nullable instead.\"</p>\n\n<p>And here is my two cents (of untested code :) )</p>\n\n<pre><code>// Or if (row[\"fooColumn\"] == DBNull.Value)\nif (row.IsNull[\"fooColumn\"])\n{\n // use a null for strings and a Nullable for value types \n // if it is a value type and null is invalid throw a \n // InvalidOperationException here with some descriptive text. \n // or dont check for null at all and let the cast exception below bubble \n value = null;\n}\nelse\n{\n // do a direct cast here. dont use \"as\", \"convert\", \"parse\" or \"tostring\"\n // as all of these will swallow the case where is the incorect type.\n // (Unless it is a string in the DB and really do want to convert it)\n value = (string)row[\"fooColumn\"];\n}\n</code></pre>\n\n<p>And one question... Any reason you are not using an ORM? </p>\n"
},
{
"answer_id": 675894,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>DBNull implements .ToString() like everything else. No need to do anything. Instead of the hard cast, call the object's .ToString() method.</p>\n\n<pre><code>DataRow row = ds.Tables[0].Rows[0];\nstring value;\n\nif (row[\"fooColumn\"] == DBNull.Value)\n{\n value = string.Empty;\n}\nelse \n{\n value = Convert.ToString(row[\"fooColumn\"]);\n}\n</code></pre>\n\n<p>this becomes:</p>\n\n<pre><code>DataRow row = ds.Tables[0].Rows[0];\nstring value = row.ToString()\n</code></pre>\n\n<p>DBNull.ToString() returns string.Empty</p>\n\n<p>I would imagine this is the best practice you're looking for</p>\n"
},
{
"answer_id": 12726127,
"author": "NeverHopeless",
"author_id": 751527,
"author_profile": "https://Stackoverflow.com/users/751527",
"pm_score": 1,
"selected": false,
"text": "<p>You should also look at the extension methods. <a href=\"http://shahanayyub.wordpress.com/2012/10/04/best-practice-to-check-for-dbnull-using-net/\" rel=\"nofollow\">Here</a> are some examples to deal with this scenerio.</p>\n\n<p>Recommended <a href=\"http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx\" rel=\"nofollow\">read</a></p>\n"
},
{
"answer_id": 16580743,
"author": "Jürgen Steinblock",
"author_id": 98491,
"author_profile": "https://Stackoverflow.com/users/98491",
"pm_score": 2,
"selected": false,
"text": "<p>It is worth mentioning, that <code>DBNull.Value.ToString()</code> equals <code>String.Empty</code></p>\n\n<p>You can use this to your advantage:</p>\n\n<pre><code>DataRow row = ds.Tables[0].Rows[0];\nstring value = row[\"name\"].ToString();\n</code></pre>\n\n<p>However, that only works for Strings, for everything else I would use the linq way or a extension method. For myself, I have written a little extension method that checks for DBNull and even does the casting via <code>Convert.ChangeType(...)</code></p>\n\n<pre><code>int value = row.GetValueOrDefault<int>(\"count\");\nint value = row.GetValueOrDefault<int>(\"count\", 15);\n</code></pre>\n"
},
{
"answer_id": 18943063,
"author": "João Pinho",
"author_id": 2606833,
"author_profile": "https://Stackoverflow.com/users/2606833",
"pm_score": 2,
"selected": false,
"text": "<p>Often when working with DataTables you have to deal with this cases, where the row field can be either null or DBNull, normally I deal with that like this:</p>\n\n<pre><code>string myValue = (myDataTable.Rows[i][\"MyDbNullableField\"] as string) ?? string.Empty;\n</code></pre>\n\n<p>The 'as' operator returns null for invalid cast's, like DBNull to string, and the '??' returns\nthe term to the right of the expression if the first is null.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191/"
] | I frequently have problems dealing with `DataRows` returned from `SqlDataAdapters`. When I try to fill in an object using code like this:
```
DataRow row = ds.Tables[0].Rows[0];
string value = (string)row;
```
What is the best way to deal with `DBNull's` in this type of situation. | Nullable types are good, but only for types that are not nullable to begin with.
To make a type "nullable" append a question mark to the type, for example:
```
int? value = 5;
```
I would also recommend using the "`as`" keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is
1. If a type is nullable, the "`as`" keyword returns `null` if a value is `DBNull`.
2. It's [ever-so-slightly faster than casting](http://www.codeproject.com/Articles/8052/Type-casting-impact-over-execution-performance-in) though [only in certain cases](https://stackoverflow.com/a/496167/392). This on its own is never a good enough reason to use `as`, but coupled with the reason above it's useful.
I'd recommend doing something like this
```
DataRow row = ds.Tables[0].Rows[0];
string value = row as string;
```
In the case above, if `row` comes back as `DBNull`, then `value` will become `null` instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned, **using `as` will cause your code to silently fail** and make values simple `null` instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves. |
26,825 | <p>I have a CollapsiblePanelExtender that will not collapse. I have "collapsed" set to true and all the ControlID set correctly. I try to collapse and it goes through the animation but then expands almost instantly. This is in an User Control with the following structure.</p>
<pre><code><asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="odsPartners" Width="450px" BorderWidth="0"
ShowHeader="false" ShowFooter="false" AllowSorting="true"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Contract Partners" SortExpression="Name">
<ItemTemplate>
<asp:Panel id="pnlRow" runat="server">
<table>
...Stuff...
</table>
</asp:Panel>
<ajaxToolkit:CollapsiblePanelExtender runat="server" ID="DDE"
Collapsed="true" ImageControlID="btnExpander" ExpandedImage="../Images/collapse.jpg" CollapsedImage="../Images/expand.jpg"
TargetControlID="DropPanel" CollapseControlID="btnExpander" ExpandControlID="btnExpander" />
<asp:Panel ID="DropPanel" runat="server" CssClass="CollapsedPanel">
<asp:Table ID="tblContracts" runat="server">
<asp:TableRow ID="row" runat="server">
<asp:TableCell ID="spacer" runat="server" Width="30">&nbsp;</asp:TableCell>
<asp:TableCell ID="cellData" runat="server" Width="400">
<uc1:ContractList ID="ContractList1" runat="server" PartnerID='<%# Bind("ID") %>' />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tbFilter" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
</code></pre>
| [
{
"answer_id": 26912,
"author": "Ian Patrick Hughes",
"author_id": 2213,
"author_profile": "https://Stackoverflow.com/users/2213",
"pm_score": 3,
"selected": true,
"text": "<p>I am sorry I do not have time to trouble-shoot your code, so this is from the hip.</p>\n\n<p>There is a good chance that this a client-side action that is failing. Make certain that your page has the correct doctype tag if you took it out of your page or masterPage. Furthermore, attempt to set the ClientState as well:</p>\n\n<p>DDE.ClientState = true;</p>\n\n<p>The issue is you have that thing wrapped inside of your TemplateField. I have ran into issues using the AjaxControlToolkit on repeated fields and usually side with using a lighter weight client-side option, up to and including rolling your own show/hide method that can be reused just by passing in an DOM understood id.</p>\n"
},
{
"answer_id": 26918,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>Also check that the you have the following property set:</p>\n\n<pre><code>AutoExpand=\"False\"\n</code></pre>\n\n<p>One of the features of the collapsible panel is that it will auto expand when you put your mouse over it, and this tag will make sure that doesn't happen.</p>\n"
},
{
"answer_id": 27026,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>After checking the AutoExpand (which strangley had no visible effect) I checked the DOC Type. Sure enough. That was the culprit.</p>\n\n<p>This is the correct one:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\" > \n</code></pre>\n\n<p>Thanks Ian!</p>\n"
},
{
"answer_id": 28340499,
"author": "user4532236",
"author_id": 4532236,
"author_profile": "https://Stackoverflow.com/users/4532236",
"pm_score": -1,
"selected": false,
"text": "<p>It is working fine:</p>\n\n<pre><code>CollapsiblePanelExtender CpeForControls = (CollapsiblePanelExtender)tbl_Form.FindControl(\"cpe_controls\");\nCpeForControls.ClientState = \"true\";\nCpeForControls.Collapsed = true;\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] | I have a CollapsiblePanelExtender that will not collapse. I have "collapsed" set to true and all the ControlID set correctly. I try to collapse and it goes through the animation but then expands almost instantly. This is in an User Control with the following structure.
```
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="odsPartners" Width="450px" BorderWidth="0"
ShowHeader="false" ShowFooter="false" AllowSorting="true"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Contract Partners" SortExpression="Name">
<ItemTemplate>
<asp:Panel id="pnlRow" runat="server">
<table>
...Stuff...
</table>
</asp:Panel>
<ajaxToolkit:CollapsiblePanelExtender runat="server" ID="DDE"
Collapsed="true" ImageControlID="btnExpander" ExpandedImage="../Images/collapse.jpg" CollapsedImage="../Images/expand.jpg"
TargetControlID="DropPanel" CollapseControlID="btnExpander" ExpandControlID="btnExpander" />
<asp:Panel ID="DropPanel" runat="server" CssClass="CollapsedPanel">
<asp:Table ID="tblContracts" runat="server">
<asp:TableRow ID="row" runat="server">
<asp:TableCell ID="spacer" runat="server" Width="30"> </asp:TableCell>
<asp:TableCell ID="cellData" runat="server" Width="400">
<uc1:ContractList ID="ContractList1" runat="server" PartnerID='<%# Bind("ID") %>' />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tbFilter" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
``` | I am sorry I do not have time to trouble-shoot your code, so this is from the hip.
There is a good chance that this a client-side action that is failing. Make certain that your page has the correct doctype tag if you took it out of your page or masterPage. Furthermore, attempt to set the ClientState as well:
DDE.ClientState = true;
The issue is you have that thing wrapped inside of your TemplateField. I have ran into issues using the AjaxControlToolkit on repeated fields and usually side with using a lighter weight client-side option, up to and including rolling your own show/hide method that can be reused just by passing in an DOM understood id. |
26,842 | <p>I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the <a href="http://search.cpan.org/dist/AuthCAS" rel="nofollow noreferrer">AuthCAS</a> Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the <a href="http://search.cpan.org/dist/IO-Socket-SSL" rel="nofollow noreferrer">IO::Socket::SSL</a> module:</p>
<pre><code> 500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]')
([CAS Server] substituted for real server name)
</code></pre>
<p>Symptoms/Tests:</p>
<ol>
<li>If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name.</li>
<li>If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser.</li>
<li>If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser.</li>
</ol>
<p>Here is the bare-bones script that produces the error:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use AuthCAS;
use CGI::Carp qw( fatalsToBrowser );
my $id = $ENV{QUERY_STRING};
my $q = new CGI;
my $target = "http://localhost/cgi-bin/testCAS.cgi";
my $cas = new AuthCAS(casUrl => 'https://cas_server/cas');
if ($id eq ""){
my $login_url = $cas->getServerLoginURL($target);
printf "Location: $login_url\n\n";
exit 0;
} else {
print $q->header();
print "CAS TEST<br>\n";
## When coming back from the CAS server a ticket is provided in the QUERY_STRING
print "QUERY_STRING = " . $id . "</br>\n";
## $ST should contain the received Service Ticket
my $ST = $q->param('ticket');
my $user = $cas->validateST($target, $ST); #### This is what fails
printf "Error: %s\n", &AuthCAS::get_errors() unless (defined $user);
}
</code></pre>
<p>Any ideas on where the conflict might be?</p>
<hr>
<p>The error is coming from the line directly above the snippet Cebjyre quoted namely</p>
<pre><code>$ssl_socket = new IO::Socket::SSL(%ssl_options);
</code></pre>
<p>namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module.</p>
| [
{
"answer_id": 27602,
"author": "Cebjyre",
"author_id": 1612,
"author_profile": "https://Stackoverflow.com/users/1612",
"pm_score": -1,
"selected": false,
"text": "<p>Well, from the <a href=\"http://search.cpan.org/src/OSALAUN/AuthCAS-1.3.1/lib/AuthCAS.pm\" rel=\"nofollow noreferrer\">module source</a> it looks like that IO::Socket error is coming from get_https2</p>\n\n<pre><code>[...]\nunless ($ssl_socket) {\n $errors = sprintf \"error %s unable to connect https://%s:%s/\\n\",&IO::Socket::SSL::errstr,$host,$port;\n return undef;\n}\n[...]\n</code></pre>\n\n<p>which is called by callCAS, which is called by validateST.</p>\n\n<p>One option is to temporarily edit the module file to put some debug statements in if you can, but if I had to guess, I'd say the casUrl you are supplying isn't matching up to the _parse_url regex properly - maybe you have three slashes after the https?</p>\n"
},
{
"answer_id": 30538,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 3,
"selected": true,
"text": "<p>As usually happens when I post questions like this, I found the problem. It turns out the <a href=\"http://search.cpan.org/dist/Crypt-SSLeay\" rel=\"nofollow noreferrer\">Crypt::SSLeay</a> module was not installed or at least not up to date. Of course the error messages didn't give me any clues. Updating it and all the problems go away and things are working fine now.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/171/"
] | I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the [AuthCAS](http://search.cpan.org/dist/AuthCAS) Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the [IO::Socket::SSL](http://search.cpan.org/dist/IO-Socket-SSL) module:
```
500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]')
([CAS Server] substituted for real server name)
```
Symptoms/Tests:
1. If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name.
2. If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser.
3. If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser.
Here is the bare-bones script that produces the error:
```
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use AuthCAS;
use CGI::Carp qw( fatalsToBrowser );
my $id = $ENV{QUERY_STRING};
my $q = new CGI;
my $target = "http://localhost/cgi-bin/testCAS.cgi";
my $cas = new AuthCAS(casUrl => 'https://cas_server/cas');
if ($id eq ""){
my $login_url = $cas->getServerLoginURL($target);
printf "Location: $login_url\n\n";
exit 0;
} else {
print $q->header();
print "CAS TEST<br>\n";
## When coming back from the CAS server a ticket is provided in the QUERY_STRING
print "QUERY_STRING = " . $id . "</br>\n";
## $ST should contain the received Service Ticket
my $ST = $q->param('ticket');
my $user = $cas->validateST($target, $ST); #### This is what fails
printf "Error: %s\n", &AuthCAS::get_errors() unless (defined $user);
}
```
Any ideas on where the conflict might be?
---
The error is coming from the line directly above the snippet Cebjyre quoted namely
```
$ssl_socket = new IO::Socket::SSL(%ssl_options);
```
namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module. | As usually happens when I post questions like this, I found the problem. It turns out the [Crypt::SSLeay](http://search.cpan.org/dist/Crypt-SSLeay) module was not installed or at least not up to date. Of course the error messages didn't give me any clues. Updating it and all the problems go away and things are working fine now. |
26,855 | <p>I'm currently using the module <code>URI::URL</code> to generate a full URL from a relative URL; however, it isn't running as fast as I'd like it to be. Does anyone know another way to do this that may be faster?</p>
| [
{
"answer_id": 26894,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps I got the wrong end of the stick but wouldn't,</p>\n\n<pre><code>$full_url = $base_url . $relative_url</code></pre>\n\n<p>work? IIRC Perl text processing is pretty quick.</p>\n\n<p><i>@lennysan</i> Ah sure yes of course. Sorry I can't help, my Perl is pretty rusty.</p>\n"
},
{
"answer_id": 26960,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 3,
"selected": true,
"text": "<p>The following code should work.</p>\n\n<pre><code>$uri = URI->new_abs( $str, $base_uri )\n</code></pre>\n\n<p>You should also take a look at <a href=\"http://search.cpan.org/dist/URI/URI.pm\" rel=\"nofollow noreferrer\">the URI page on search.cpan.org</a>.</p>\n"
},
{
"answer_id": 26974,
"author": "lennysan",
"author_id": 2901,
"author_profile": "https://Stackoverflow.com/users/2901",
"pm_score": 1,
"selected": false,
"text": "<p>Brendan, I should have clarified that I can't guarantee what the relative path is going to look like. It could be pretty tricky (e.g. has a slash at the front, doesn't have a slash, has \"../\", etc).</p>\n\n<p>Peter, that's what I'm using now. Or is that faster then using the URI::URL->new($path)->abs?</p>\n"
},
{
"answer_id": 27993,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 2,
"selected": false,
"text": "<p>Just happened across <a href=\"http://blog.vipul.net/2008/08/24/redhat-perl-what-a-tragedy/\" rel=\"nofollow noreferrer\">this article</a> which point out shortcomings in Redhat/Centos/Fedora implementations of Perl which affect <code>URI</code> profoundly.</p>\n<p>If you are running one of these Linux flavours, you might want to recompile Perl from original source (not RPM source).</p>\n<blockquote>\n<p>I realized that anyone running perl code with the distribution perl interpretter on Redhat 5.2, Centos 5.2 or Fedora 9 is likely a victim. Yes, even if your code doesn’t use the fancy bless/overload idiom, many CPAN modules do! This google search shows 1500+ modules use the bless/overload idiom and they include some really popular ones like URI, JSON. ...</p>\n<p>... At this point, I decided to recompile perl from source. The bug was gone. And the difference was appalling. Everything got seriously fast. CPUs were chilling at a loadavg below 0.10 and we were processing data 100x to 1000x faster!</p>\n</blockquote>\n"
},
{
"answer_id": 31655,
"author": "gmuslera",
"author_id": 3133,
"author_profile": "https://Stackoverflow.com/users/3133",
"pm_score": 1,
"selected": false,
"text": "<p>Could depend a bit how you obtain those 2 strings. Probably the secure, fireproof way to do that is what is in URI::URL or similar libraries, where all alternatives, including malicious ones, would be considered. Maybe slower, but in some environments faster will be the speed of a bullet going to your own foot.</p>\n\n<p>But if you expect there something plain and not tricky could see if it starts with /, chains of ../, or any other char. The 1st would put the server name + the url, the 2nd chop paths from the base uri till getting in one of the other 2 alternatives, or just add it to the base url.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2901/"
] | I'm currently using the module `URI::URL` to generate a full URL from a relative URL; however, it isn't running as fast as I'd like it to be. Does anyone know another way to do this that may be faster? | The following code should work.
```
$uri = URI->new_abs( $str, $base_uri )
```
You should also take a look at [the URI page on search.cpan.org](http://search.cpan.org/dist/URI/URI.pm). |
26,857 | <p>Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?</p>
<p>Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a link/button on my site's page that will fill in those values and submit the info without having to copy/paste them across and click the submit button.</p>
<p>Further clarification: How do automated spam bots fill out forms and click the submit button if they were written in C#?</p>
| [
{
"answer_id": 26881,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 7,
"selected": true,
"text": "<p>The code will look something like this: </p>\n\n<pre><code>WebRequest req = WebRequest.Create(\"http://mysite/myform.aspx\");\nstring postData = \"item1=11111&item2=22222&Item3=33333\";\n\nbyte[] send = Encoding.Default.GetBytes(postData);\nreq.Method = \"POST\";\nreq.ContentType = \"application/x-www-form-urlencoded\";\nreq.ContentLength = send.Length;\n\nStream sout = req.GetRequestStream();\nsout.Write(send, 0, send.Length);\nsout.Flush();\nsout.Close();\n\nWebResponse res = req.GetResponse();\nStreamReader sr = new StreamReader(res.GetResponseStream());\nstring returnvalue = sr.ReadToEnd();\n</code></pre>\n"
},
{
"answer_id": 26932,
"author": "Ryan Rinaldi",
"author_id": 2278,
"author_profile": "https://Stackoverflow.com/users/2278",
"pm_score": 1,
"selected": false,
"text": "<p>View the source of the page and use the WebRequest class to do the posting. No need to drive IE. Just figure out what IE is sending to the server and replicate that. Using a tool like Fiddler will make it even easier.</p>\n"
},
{
"answer_id": 8378787,
"author": "John Kelvie",
"author_id": 929047,
"author_profile": "https://Stackoverflow.com/users/929047",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the UploadValues method on WebClient - all it requires is passing a URL and a NameValueCollection. It is the easiest approach that I have found, and the MS documentation has a nice example:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/9w7b4fz7.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/9w7b4fz7.aspx</a></p>\n\n<p>Here is a simple version with some error handling: </p>\n\n<pre><code>var webClient = new WebClient();\nDebug.Info(\"PostingForm: \" + url);\ntry\n{\n byte [] responseArray = webClient.UploadValues(url, nameValueCollection);\n return new Response(responseArray, (int) HttpStatusCode.OK);\n}\ncatch (WebException e)\n{\n var response = (HttpWebResponse)e.Response;\n byte[] responseBytes = IOUtil.StreamToBytes(response.GetResponseStream());\n return new Response(responseBytes, (int) response.StatusCode);\n} \n</code></pre>\n\n<p>The Response class is a simple wrapper for the response body and status code. </p>\n"
},
{
"answer_id": 14978752,
"author": "John",
"author_id": 1252113,
"author_profile": "https://Stackoverflow.com/users/1252113",
"pm_score": 0,
"selected": false,
"text": "<p>I had a situation where I needed to post free text from a html textarea programmatically and I had issues where I was getting <code><br /></code> in my param list i was building.</p>\n\n<p>My solution was a replace of the br tags with linebreak characters and htmlencoding just to be safe.</p>\n\n<pre><code>Regex.Replace( HttpUtility.HtmlDecode( test ), \"(<br.*?>)\", \"\\r\\n\" ,RegexOptions.IgnoreCase);\n</code></pre>\n"
},
{
"answer_id": 30785403,
"author": "user3887407",
"author_id": 3887407,
"author_profile": "https://Stackoverflow.com/users/3887407",
"pm_score": 0,
"selected": false,
"text": "<p>Where you encode the string:</p>\n\n<blockquote>\n <p>Encoding.Default.GetBytes(postData);</p>\n</blockquote>\n\n<p>Use Ascii instead for the google apis:</p>\n\n<blockquote>\n <p>Encoding.ASCII.GetBytes(postData);</p>\n</blockquote>\n\n<p>this makes your request the same as and equivalent \"curl --data \"...\" [url]\" request</p>\n"
},
{
"answer_id": 40257908,
"author": "Sadid Khan",
"author_id": 1999720,
"author_profile": "https://Stackoverflow.com/users/1999720",
"pm_score": 0,
"selected": false,
"text": "<p>you can send a post/get request with many ways. Different types of library is there to help. \nI found it is <strong>confusing</strong> to choose which one I should use and what are the <strong>differences</strong> among them. </p>\n\n<p>After surfing stack overflow this is the <strong>best answer I found</strong>. this thread explains all</p>\n\n<p><a href=\"https://stackoverflow.com/a/4015346/1999720\">https://stackoverflow.com/a/4015346/1999720</a></p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?
Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a link/button on my site's page that will fill in those values and submit the info without having to copy/paste them across and click the submit button.
Further clarification: How do automated spam bots fill out forms and click the submit button if they were written in C#? | The code will look something like this:
```
WebRequest req = WebRequest.Create("http://mysite/myform.aspx");
string postData = "item1=11111&item2=22222&Item3=33333";
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
``` |
26,877 | <p>In C#, what is the difference (if any) between these two lines of code?</p>
<pre><code>tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);
</code></pre>
<p>and</p>
<pre><code>tmrMain.Elapsed += tmrMain_Tick;
</code></pre>
<p>Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?</p>
| [
{
"answer_id": 26884,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": true,
"text": "<p>I did this</p>\n\n<pre><code>static void Hook1()\n{\n someEvent += new EventHandler( Program_someEvent );\n}\n\nstatic void Hook2()\n{\n someEvent += Program_someEvent;\n}\n</code></pre>\n\n<p>And then ran ildasm over the code.<br>\nThe generated MSIL was exactly the same.</p>\n\n<p>So to answer your question, yes they are the same thing.<br>\nThe compiler is just inferring that you want <code>someEvent += new EventHandler( Program_someEvent );</code><br>\n-- You can see it creating the new <code>EventHandler</code> object in both cases in the MSIL</p>\n"
},
{
"answer_id": 26893,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there's any difference. Certainly resharper says the first line has redundant code.</p>\n"
},
{
"answer_id": 26895,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": -1,
"selected": false,
"text": "<p>I think the one way to really tell would be to look at the MSIL produced for the code.. Tends to be a good acid test..</p>\n\n<p>I have funny concerns that it may somehow mess with GC.. Seems odd that there would be all the overhead of declaring the new delegate type if it never needed to be done this way, you know?</p>\n"
},
{
"answer_id": 26913,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 0,
"selected": false,
"text": "<p>Wasn't the <code>new XYZEventHandler</code> require until C#2003, and you were allowed to omit the redundant code in C#2005?</p>\n"
},
{
"answer_id": 26919,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 2,
"selected": false,
"text": "<p>It used to be (.NET 1.x days) that the long form was the only way to do it. In both cases you are newing up a delegate to point to the Program_someEvent method.</p>\n"
},
{
"answer_id": 27048,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 2,
"selected": false,
"text": "<p>A little offtopic :</p>\n\n<p>You could instantiate a delegate <code>(new EventHandler(MethodName))</code> and (if appropriate) reuse that instance.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] | In C#, what is the difference (if any) between these two lines of code?
```
tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);
```
and
```
tmrMain.Elapsed += tmrMain_Tick;
```
Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter? | I did this
```
static void Hook1()
{
someEvent += new EventHandler( Program_someEvent );
}
static void Hook2()
{
someEvent += Program_someEvent;
}
```
And then ran ildasm over the code.
The generated MSIL was exactly the same.
So to answer your question, yes they are the same thing.
The compiler is just inferring that you want `someEvent += new EventHandler( Program_someEvent );`
-- You can see it creating the new `EventHandler` object in both cases in the MSIL |
26,879 | <p>I have a website that is perfectely centered aligned. The CSS code works fine. The problem doesn't really have to do with CSS. I have headers for each page that perfectely match eachother.</p>
<p>However, when the content gets larger, Opera and FireFox show a scrollbar at the left so you can scroll to the content not on the screen. This makes my site jump a few pixels to the left. Thus the headers are not perfectely aligned anymore.</p>
<p>IE always has a scrollbar, so the site never jumps around in IE. </p>
<p>Does anyone know a JavaScript/CSS/HTML solution for this problem?</p>
| [
{
"answer_id": 26891,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>Are you aligning with percentage widths or fixed widths? I'm also guessing you're applying a background to the body - I've had this problem myself.</p>\n\n<p>It'll be much easier to help you if you upload the page so we can see the source code however.</p>\n"
},
{
"answer_id": 26907,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code> #middle \n { \nposition: relative;\nmargin: 0px auto 0px auto; \nwidth: 1000px; \nmax-width: 1000px;\n}\n</code></pre>\n\n<p>is my centered DIV</p>\n"
},
{
"answer_id": 26911,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>Well you don't need the <code>position: relative;</code> - it should work fine without it.</p>\n\n<p>I take it that <code>div</code> <em>has</em> to be <code>1000px</code> wide? It would still be a lot easier to answer this with the actual website.</p>\n"
},
{
"answer_id": 26924,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 4,
"selected": true,
"text": "<p>I use </p>\n\n<pre><code>html { overflow-y: scroll; }\n</code></pre>\n\n<p>To standardize the scrollbar behavior in IE and FF</p>\n"
},
{
"answer_id": 94534,
"author": "Carl Camera",
"author_id": 12804,
"author_profile": "https://Stackoverflow.com/users/12804",
"pm_score": 2,
"selected": false,
"text": "<p>FWIW: I use</p>\n\n<pre><code>html { height: 101%; }\n</code></pre>\n\n<p>to force scrollbars to always appear in Firefox.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a website that is perfectely centered aligned. The CSS code works fine. The problem doesn't really have to do with CSS. I have headers for each page that perfectely match eachother.
However, when the content gets larger, Opera and FireFox show a scrollbar at the left so you can scroll to the content not on the screen. This makes my site jump a few pixels to the left. Thus the headers are not perfectely aligned anymore.
IE always has a scrollbar, so the site never jumps around in IE.
Does anyone know a JavaScript/CSS/HTML solution for this problem? | I use
```
html { overflow-y: scroll; }
```
To standardize the scrollbar behavior in IE and FF |
26,882 | <p>My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns).</p>
<p>They can select a report using two methods. With <code>SelectedReport=MyReport</code> in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down.</p>
<p>My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want <code>SelectedReport=MyNewReport</code> in the query string and the page to post back.</p>
<p>At the moment it's just doing a normal postback, which leaves the <code>SelectedReport=MyReport</code> in the query string, even if it's not the currently selected report.</p>
<p><strong>Edit:</strong> And I also need to preserve ViewState.</p>
<p>I've tried doing <code>Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)</code> in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown.</p>
<p>Maybe I'm asking the impossible or going about it completely the wrong way. </p>
<p><strong>@Craig</strong> The QueryString collection is read-only and cannot be modified.<br>
<strong>@Jason</strong> That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).</p>
| [
{
"answer_id": 26902,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If it's an automatic post when the data changes then you should be able to redirect to the new query string with a server side handler of the dropdown's 'onchange' event. If it's a button, handle server side in the click event. I'd post a sample of what I'm talking about but I'm on the way out to pick up the kids.</p>\n"
},
{
"answer_id": 26908,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried to modify the Request.QueryString[] on the SelectedIndexChanged for the DropDown? That should do the trick.</p>\n"
},
{
"answer_id": 26938,
"author": "Kevin Pang",
"author_id": 1574,
"author_profile": "https://Stackoverflow.com/users/1574",
"pm_score": 0,
"selected": false,
"text": "<p>You could populate your dropdown based on the querystring on non-postbacks, then always use the value from the dropdown. That way the user's first visit to the page will be based on the querystring and subsequent changes they make to the dropdown will change the selected report.</p>\n"
},
{
"answer_id": 26943,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 2,
"selected": false,
"text": "<p>You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page.</p>\n\n<p>EDIT: Here is some quick and dirty code that is indicative of what would do the trick:</p>\n\n<pre><code><script>\n function changeReport(dropDownList) {\n var selectedReport = dropDownList.options[dropDownList.selectedIndex];\n window.location = (\"scratch.htm?SelectedReport=\" + selectedReport.value);\n }\n</script>\n\n<select id=\"SelectedReport\" onchange=\"changeReport(this)\">\n <option value=\"foo\">foo</option>\n <option value=\"bar\">bar</option>\n <option value=\"baz\">baz</option>\n</select>\n</code></pre>\n\n<p>Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example).</p>\n\n<p><strong>@Ray:</strong> You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell?</p>\n"
},
{
"answer_id": 29605,
"author": "Tom",
"author_id": 3139,
"author_profile": "https://Stackoverflow.com/users/3139",
"pm_score": 0,
"selected": false,
"text": "<p>The view state only lasts for <a href=\"http://msdn.microsoft.com/en-us/library/540y83hx.aspx\" rel=\"nofollow noreferrer\">multiple requests for the same page</a>. Changing the query string in the URL is requesting a new page, thus clearing the view state.</p>\n\n<p>Is it possible to remove the reliance on the view state by adding more query string parameters? You can then build a new URL and Response.Redirect to it.</p>\n\n<p>Another option is to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.action.aspx\" rel=\"nofollow noreferrer\">Action property</a> on the form to clear the query string so at least the query string does not contradict what's displayed on the page after the user selects a different report.</p>\n\n<pre><code>Form.Action = Request.Path;\n</code></pre>\n"
},
{
"answer_id": 16968178,
"author": "Rajat Agrawal",
"author_id": 2460674,
"author_profile": "https://Stackoverflow.com/users/2460674",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following function to modify the querystring on postback in asp.net using the Webresource.axd script as below.</p>\n\n<pre><code>var url = updateQueryStringParameter(window.location.href,\n 'Search',\n document.getElementById('txtSearch').value);\nWebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(\"searchbutton\", \"\",\n true, \"aa\", url, false, true));\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] | My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns).
They can select a report using two methods. With `SelectedReport=MyReport` in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down.
My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want `SelectedReport=MyNewReport` in the query string and the page to post back.
At the moment it's just doing a normal postback, which leaves the `SelectedReport=MyReport` in the query string, even if it's not the currently selected report.
**Edit:** And I also need to preserve ViewState.
I've tried doing `Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)` in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown.
Maybe I'm asking the impossible or going about it completely the wrong way.
**@Craig** The QueryString collection is read-only and cannot be modified.
**@Jason** That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response). | You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page.
EDIT: Here is some quick and dirty code that is indicative of what would do the trick:
```
<script>
function changeReport(dropDownList) {
var selectedReport = dropDownList.options[dropDownList.selectedIndex];
window.location = ("scratch.htm?SelectedReport=" + selectedReport.value);
}
</script>
<select id="SelectedReport" onchange="changeReport(this)">
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="baz">baz</option>
</select>
```
Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example).
**@Ray:** You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell? |
26,903 | <p>Is there a way?</p>
<p>I need all types that implement a specific interface to have a parameterless constructor, can it be done?</p>
<p>I am developing the base code for other developers in my company to use in a specific project.</p>
<p>There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).</p>
<p>The interface will be internal to the assembly</p>
<p>If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration...</p>
| [
{
"answer_id": 26909,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think so. </p>\n\n<p>You also can't use an abstract class for this.</p>\n"
},
{
"answer_id": 26928,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 5,
"selected": false,
"text": "<p>Not to be too blunt, but you've misunderstood the purpose of interfaces.</p>\n\n<p>An interface means that several people can implement it in their own classes, and then pass instances of those classes to other classes to be used. Creation creates an unnecessary strong coupling.</p>\n\n<p>It sounds like you really need some kind of registration system, either to have people register instances of usable classes that implement the interface, or of factories that can create said items upon request.</p>\n"
},
{
"answer_id": 26997,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 3,
"selected": false,
"text": "<p>Juan,</p>\n\n<p>Unfortunately there is no way to get around this in a strongly typed language. You won't be able to ensure at compile time that the classes will be able to be instantiated by your Activator-based code.</p>\n\n<p>(ed: removed an erroneous alternative solution)</p>\n\n<p>The reason is that, unfortunately, it's not possible to use interfaces, abstract classes, or virtual methods in combination with either constructors or static methods. The short reason is that the former contain no explicit type information, and the latter require explicit type information.</p>\n\n<p>Constructors and static methods <strong>must</strong> have explicit (right there in the code) type information available at the time of the call. This is required because there is no instance of the class involved which can be queried by the runtime to obtain the underlying type, which the runtime needs to determine which actual concrete method to call.</p>\n\n<p>The entire point of an interface, abstract class, or virtual method is to be able to make a function call <strong>without</strong> explicit type information, and this is enabled by the fact that there is an instance being referenced, which has \"hidden\" type information not directly available to the calling code. So these two mechanisms are quite simply mutually exclusive. They can't be used together because when you mix them, you end up with no concrete type information at all anywhere, which means the runtime has no idea where to find the function you're asking it to call.</p>\n"
},
{
"answer_id": 27031,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p>I would like to remind everyone that:</p>\n\n<ol>\n<li>Writing attributes in .NET is easy</li>\n<li>Writing static analysis tools in .NET that ensure conformance with company standards is easy</li>\n</ol>\n\n<p>Writing a tool to grab all concrete classes that implement a certain interface/have an attribute and verifying that it has a parameterless constructor takes about 5 mins of coding effort. You add it to your post-build step and now you have a framework for whatever other static analyses you need to perform.</p>\n\n<p>The language, the compiler, the IDE, your brain - they're all tools. Use them!</p>\n"
},
{
"answer_id": 27047,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters\" rel=\"nofollow noreferrer\">type parameter constraint</a></p>\n<pre class=\"lang-csharp prettyprint-override\"><code>interface ITest<T> where T: new()\n{\n //...\n}\n\nclass Test: ITest<Test>\n{\n //...\n}\n</code></pre>\n"
},
{
"answer_id": 27049,
"author": "Landon Kuhn",
"author_id": 1785,
"author_profile": "https://Stackoverflow.com/users/1785",
"pm_score": 0,
"selected": false,
"text": "<p>No you can't do that. Maybe for your situation a factory interface would be helpful? Something like:</p>\n\n<pre><code>interface FooFactory {\n Foo createInstance();\n}\n</code></pre>\n\n<p>For every implementation of Foo you create an instance of FooFactory that knows how to create it.</p>\n"
},
{
"answer_id": 27058,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 0,
"selected": false,
"text": "<p>You do not need a parameterless constructor for the Activator to instantiate your class. You can have a parameterized constructor and pass all the parameters from the Activator. Check out <a href=\"http://msdn.microsoft.com/en-us/library/4b0ww1we.aspx\" rel=\"nofollow noreferrer\">MSDN on this</a>.</p>\n"
},
{
"answer_id": 27454,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/26903/how-can-you-require-a-constructor-with-no-parameters-for-types-implementing-an#27386\">Juan Manuel said:</a></p>\n\n<blockquote>\n <p>that's one of the reasons I don't understand why it cannot be a part of the contract in the interface</p>\n</blockquote>\n\n<p>It's an indirect mechanism. The generic allows you to \"cheat\" and send type information along with the interface. The critical thing to remember here is that the constraint isn't on the interface that you are working with directly. It's not a constraint on the interface itself, but on some other type that will \"ride along\" on the interface. This is the best explanation I can offer, I'm afraid.</p>\n\n<p>By way of illustration of this fact, I'll point out a hole that I have noticed in aku's code. It's possible to write a class that would compile fine but fail at runtime when you try to instantiate it:</p>\n\n<pre><code>public class Something : ITest<String>\n{\n private Something() { }\n}\n</code></pre>\n\n<p>Something derives from ITest<T>, but implements no parameterless constructor. It will compile fine, because String does implement a parameterless constructor. Again, the constraint is on T, and therefore String, rather than ITest or Something. Since the constraint on T is satisfied, this will compile. But it will fail at runtime.</p>\n\n<p>To prevent <strong>some</strong> instances of this problem, you need to add another constraint to T, as below:</p>\n\n<pre><code>public interface ITest<T>\n where T : ITest<T>, new()\n{\n}\n</code></pre>\n\n<p>Note the new constraint: T : ITest<T>. This constraint specifies that what you pass into the argument parameter of ITest<T> <strong>must</strong> also <strong>derive</strong> from ITest<T>.</p>\n\n<p>Even so this will not prevent <strong>all</strong> cases of the hole. The code below will compile fine, because A has a parameterless constructor. But since B's parameterless constructor is private, instantiating B with your process will fail at runtime.</p>\n\n<pre><code>public class A : ITest<A>\n{\n}\n\npublic class B : ITest<A>\n{\n private B() { }\n}\n</code></pre>\n"
},
{
"answer_id": 36919,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "<p>Call a RegisterType method with the type, and constrain it using generics. Then, instead of walking assemblies to find ITest implementors, just store them and create from there.</p>\n\n<pre><code>void RegisterType<T>() where T:ITest, new() {\n}\n</code></pre>\n"
},
{
"answer_id": 68357,
"author": "munificent",
"author_id": 9457,
"author_profile": "https://Stackoverflow.com/users/9457",
"pm_score": 2,
"selected": false,
"text": "<p>So you need a <em>thing</em> that can create instances of an unknown type that implements an interface. You've got basically three options: a factory object, a Type object, or a delegate. Here's the givens:</p>\n\n<pre><code>public interface IInterface\n{\n void DoSomething();\n}\n\npublic class Foo : IInterface\n{\n public void DoSomething() { /* whatever */ }\n}\n</code></pre>\n\n<p>Using Type is pretty ugly, but makes sense in some scenarios:</p>\n\n<pre><code>public IInterface CreateUsingType(Type thingThatCreates)\n{\n ConstructorInfo constructor = thingThatCreates.GetConstructor(Type.EmptyTypes);\n return (IInterface)constructor.Invoke(new object[0]);\n}\n\npublic void Test()\n{\n IInterface thing = CreateUsingType(typeof(Foo));\n}\n</code></pre>\n\n<p>The biggest problem with it, is that at compile time, you have no guarantee that Foo actually <em>has</em> a default constructor. Also, reflection is a bit slow if this happens to be performance critical code.</p>\n\n<p>The most common solution is to use a factory:</p>\n\n<pre><code>public interface IFactory\n{\n IInterface Create();\n}\n\npublic class Factory<T> where T : IInterface, new()\n{\n public IInterface Create() { return new T(); }\n}\n\npublic IInterface CreateUsingFactory(IFactory factory)\n{\n return factory.Create();\n}\n\npublic void Test()\n{\n IInterface thing = CreateUsingFactory(new Factory<Foo>());\n}\n</code></pre>\n\n<p>In the above, IFactory is what really matters. Factory is just a convenience class for classes that <em>do</em> provide a default constructor. This is the simplest and often best solution.</p>\n\n<p>The third currently-uncommon-but-likely-to-become-more-common solution is using a delegate:</p>\n\n<pre><code>public IInterface CreateUsingDelegate(Func<IInterface> createCallback)\n{\n return createCallback();\n}\n\npublic void Test()\n{\n IInterface thing = CreateUsingDelegate(() => new Foo());\n}\n</code></pre>\n\n<p>The advantage here is that the code is short and simple, can work with <em>any</em> method of construction, and (with closures) lets you easily pass along additional data needed to construct the objects.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | Is there a way?
I need all types that implement a specific interface to have a parameterless constructor, can it be done?
I am developing the base code for other developers in my company to use in a specific project.
There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).
The interface will be internal to the assembly
If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration... | [Juan Manuel said:](https://stackoverflow.com/questions/26903/how-can-you-require-a-constructor-with-no-parameters-for-types-implementing-an#27386)
>
> that's one of the reasons I don't understand why it cannot be a part of the contract in the interface
>
>
>
It's an indirect mechanism. The generic allows you to "cheat" and send type information along with the interface. The critical thing to remember here is that the constraint isn't on the interface that you are working with directly. It's not a constraint on the interface itself, but on some other type that will "ride along" on the interface. This is the best explanation I can offer, I'm afraid.
By way of illustration of this fact, I'll point out a hole that I have noticed in aku's code. It's possible to write a class that would compile fine but fail at runtime when you try to instantiate it:
```
public class Something : ITest<String>
{
private Something() { }
}
```
Something derives from ITest<T>, but implements no parameterless constructor. It will compile fine, because String does implement a parameterless constructor. Again, the constraint is on T, and therefore String, rather than ITest or Something. Since the constraint on T is satisfied, this will compile. But it will fail at runtime.
To prevent **some** instances of this problem, you need to add another constraint to T, as below:
```
public interface ITest<T>
where T : ITest<T>, new()
{
}
```
Note the new constraint: T : ITest<T>. This constraint specifies that what you pass into the argument parameter of ITest<T> **must** also **derive** from ITest<T>.
Even so this will not prevent **all** cases of the hole. The code below will compile fine, because A has a parameterless constructor. But since B's parameterless constructor is private, instantiating B with your process will fail at runtime.
```
public class A : ITest<A>
{
}
public class B : ITest<A>
{
private B() { }
}
``` |
26,947 | <p>What built-in PHP functions are useful for web scraping? What are some good resources (web or print) for getting up to speed on web scraping with PHP?</p>
| [
{
"answer_id": 26951,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": -1,
"selected": false,
"text": "<p>The curl library allows you to download web pages. You should look into regular expressions for doing the scraping.</p>\n"
},
{
"answer_id": 26955,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p><code>file_get_contents()</code> can take a remote URL and give you the source. You can then use regular expressions (with the Perl-compatible functions) to grab what you need.</p>\n\n<p>Out of curiosity, what are you trying to scrape?</p>\n"
},
{
"answer_id": 26972,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 0,
"selected": false,
"text": "<p>I'd either use libcurl or Perl's LWP (libwww for perl). Is there a libwww for php?</p>\n"
},
{
"answer_id": 103554,
"author": "tyshock",
"author_id": 16448,
"author_profile": "https://Stackoverflow.com/users/16448",
"pm_score": 6,
"selected": false,
"text": "<p>Scraping generally encompasses 3 steps: </p>\n\n<ul>\n<li>first you GET or POST your request\nto a specified URL </li>\n<li>next you receive\n the html that is returned as the\n response</li>\n<li>finally you parse out of\n that html the text you'd like to\n scrape.</li>\n</ul>\n\n<p>To accomplish steps 1 and 2, below is a simple php class which uses Curl to fetch webpages using either GET or POST. After you get the HTML back, you just use Regular Expressions to accomplish step 3 by parsing out the text you'd like to scrape.</p>\n\n<p>For regular expressions, my favorite tutorial site is the following:\n<a href=\"http://www.regular-expressions.info/\" rel=\"nofollow noreferrer\">Regular Expressions Tutorial</a></p>\n\n<p>My Favorite program for working with RegExs is <a href=\"http://www.regexbuddy.com/\" rel=\"nofollow noreferrer\">Regex Buddy</a>. I would advise you to try the demo of that product even if you have no intention of buying it. It is an invaluable tool and will even generate code for your regexs you make in your language of choice (including php).</p>\n\n<p>Usage:\n<pre><code></p>\n\n<p>$curl = new Curl();\n$html = $curl->get(\"<a href=\"http://www.google.com\" rel=\"nofollow noreferrer\">http://www.google.com</a>\");</p>\n\n<p>// now, do your regex work against $html\n</pre></code></p>\n\n<p>PHP Class:</p>\n\n<pre><code>\n\n<?php\n\nclass Curl\n{ \n\n public $cookieJar = \"\";\n\n public function __construct($cookieJarFile = 'cookies.txt') {\n $this->cookieJar = $cookieJarFile;\n }\n\n function setup()\n {\n\n\n $header = array();\n $header[0] = \"Accept: text/xml,application/xml,application/xhtml+xml,\";\n $header[0] .= \"text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\";\n $header[] = \"Cache-Control: max-age=0\";\n $header[] = \"Connection: keep-alive\";\n $header[] = \"Keep-Alive: 300\";\n $header[] = \"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\";\n $header[] = \"Accept-Language: en-us,en;q=0.5\";\n $header[] = \"Pragma: \"; // browsers keep this blank.\n\n\n curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');\n curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);\n curl_setopt($this->curl,CURLOPT_COOKIEJAR, $this->cookieJar); \n curl_setopt($this->curl,CURLOPT_COOKIEFILE, $this->cookieJar);\n curl_setopt($this->curl,CURLOPT_AUTOREFERER, true);\n curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION, true);\n curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true); \n }\n\n\n function get($url)\n { \n $this->curl = curl_init($url);\n $this->setup();\n\n return $this->request();\n }\n\n function getAll($reg,$str)\n {\n preg_match_all($reg,$str,$matches);\n return $matches[1];\n }\n\n function postForm($url, $fields, $referer='')\n {\n $this->curl = curl_init($url);\n $this->setup();\n curl_setopt($this->curl, CURLOPT_URL, $url);\n curl_setopt($this->curl, CURLOPT_POST, 1);\n curl_setopt($this->curl, CURLOPT_REFERER, $referer);\n curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);\n return $this->request();\n }\n\n function getInfo($info)\n {\n $info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);\n return $info;\n }\n\n function request()\n {\n return curl_exec($this->curl);\n }\n}\n\n?>\n</code>\n</pre>\n"
},
{
"answer_id": 105929,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "<p>If you need something that is easy to maintain, rather than fast to execute, it could help to use a scriptable browser, such as <a href=\"http://simpletest.org/en/browser_documentation.html\" rel=\"nofollow noreferrer\">SimpleTest's</a>.</p>\n"
},
{
"answer_id": 1962728,
"author": "Sarfraz",
"author_id": 139459,
"author_profile": "https://Stackoverflow.com/users/139459",
"pm_score": 0,
"selected": false,
"text": "<p>Scraper class from my framework:</p>\n\n<pre><code><?php\n\n/*\n Example:\n\n $site = $this->load->cls('scraper', 'http://www.anysite.com');\n $excss = $site->getExternalCSS();\n $incss = $site->getInternalCSS();\n $ids = $site->getIds();\n $classes = $site->getClasses();\n $spans = $site->getSpans(); \n\n print '<pre>';\n print_r($excss);\n print_r($incss);\n print_r($ids);\n print_r($classes);\n print_r($spans); \n\n*/\n\nclass scraper\n{\n private $url = '';\n\n public function __construct($url)\n {\n $this->url = file_get_contents(\"$url\");\n }\n\n public function getInternalCSS()\n {\n $tmp = preg_match_all('/(style=\")(.*?)(\")/is', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n public function getExternalCSS()\n {\n $tmp = preg_match_all('/(href=\")(\\w.*\\.css)\"/i', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n public function getIds()\n {\n $tmp = preg_match_all('/(id=\"(\\w*)\")/is', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n public function getClasses()\n {\n $tmp = preg_match_all('/(class=\"(\\w*)\")/is', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n public function getSpans(){\n $tmp = preg_match_all('/(<span>)(.*)(<\\/span>)/', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 3075685,
"author": "adiian",
"author_id": 268856,
"author_profile": "https://Stackoverflow.com/users/268856",
"pm_score": 1,
"selected": false,
"text": "<p>here is another one: a simple <a href=\"http://php-html.net/tutorials/how-to-write-a-simple-scrapper-in-php-without-regex/\" rel=\"nofollow noreferrer\">PHP Scraper without Regex</a>.</p>\n"
},
{
"answer_id": 3784264,
"author": "Joe Niland",
"author_id": 366965,
"author_profile": "https://Stackoverflow.com/users/366965",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://scraperwiki.com/\" rel=\"noreferrer\">ScraperWiki</a> is a pretty interesting project.\nHelps you build scrapers online in Python, Ruby or PHP - i was able to get a simple attempt up in a few minutes.</p>\n"
},
{
"answer_id": 10763495,
"author": "Salman von Abbas",
"author_id": 362006,
"author_profile": "https://Stackoverflow.com/users/362006",
"pm_score": 4,
"selected": false,
"text": "<p>I recommend <a href=\"https://github.com/fabpot/Goutte\" rel=\"noreferrer\">Goutte, a simple PHP Web Scraper</a>.</p>\n\n<h3>Example Usage:-</h3>\n\n<p>Create a Goutte Client instance (which extends\n<code>Symfony\\Component\\BrowserKit\\Client</code>):</p>\n\n<pre><code>use Goutte\\Client;\n\n$client = new Client();\n</code></pre>\n\n<p>Make requests with the <code>request()</code> method:</p>\n\n<pre><code>$crawler = $client->request('GET', 'http://www.symfony-project.org/');\n</code></pre>\n\n<p>The <code>request</code> method returns a <code>Crawler</code> object\n(<code>Symfony\\Component\\DomCrawler\\Crawler</code>).</p>\n\n<p>Click on links:</p>\n\n<pre><code>$link = $crawler->selectLink('Plugins')->link();\n$crawler = $client->click($link);\n</code></pre>\n\n<p>Submit forms:</p>\n\n<pre><code>$form = $crawler->selectButton('sign in')->form();\n$crawler = $client->submit($form, array('signin[username]' => 'fabien', 'signin[password]' => 'xxxxxx'));\n</code></pre>\n\n<p>Extract data:</p>\n\n<pre><code>$nodes = $crawler->filter('.error_list');\n\nif ($nodes->count())\n{\n die(sprintf(\"Authentification error: %s\\n\", $nodes->text()));\n}\n\nprintf(\"Nb tasks: %d\\n\", $crawler->filter('#nb_tasks')->text());\n</code></pre>\n"
},
{
"answer_id": 28095262,
"author": "PHP Addict",
"author_id": 4420216,
"author_profile": "https://Stackoverflow.com/users/4420216",
"pm_score": 2,
"selected": false,
"text": "<p>Scraping can be pretty complex, depending on what you want to do. Have a read of this tutorial series on <a href=\"http://php-addict.com/write-basic-scraper-php-tutorial-1/\" rel=\"nofollow\">The Basics Of Writing A Scraper In PHP</a> and see if you can get to grips with it.</p>\n\n<p>You can use similar methods to automate form sign ups, logins, even fake clicking on Ads! The main limitations with using CURL though are that it doesn't support using javascript, so if you are trying to scrape a site that uses AJAX for pagination for example it can become a little tricky...but again there are ways around that!</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2052/"
] | What built-in PHP functions are useful for web scraping? What are some good resources (web or print) for getting up to speed on web scraping with PHP? | Scraping generally encompasses 3 steps:
* first you GET or POST your request
to a specified URL
* next you receive
the html that is returned as the
response
* finally you parse out of
that html the text you'd like to
scrape.
To accomplish steps 1 and 2, below is a simple php class which uses Curl to fetch webpages using either GET or POST. After you get the HTML back, you just use Regular Expressions to accomplish step 3 by parsing out the text you'd like to scrape.
For regular expressions, my favorite tutorial site is the following:
[Regular Expressions Tutorial](http://www.regular-expressions.info/)
My Favorite program for working with RegExs is [Regex Buddy](http://www.regexbuddy.com/). I would advise you to try the demo of that product even if you have no intention of buying it. It is an invaluable tool and will even generate code for your regexs you make in your language of choice (including php).
Usage:
$curl = new Curl();
$html = $curl->get("<http://www.google.com>");
// now, do your regex work against $html
PHP Class:
```
<?php
class Curl
{
public $cookieJar = "";
public function __construct($cookieJarFile = 'cookies.txt') {
$this->cookieJar = $cookieJarFile;
}
function setup()
{
$header = array();
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($this->curl,CURLOPT_COOKIEJAR, $this->cookieJar);
curl_setopt($this->curl,CURLOPT_COOKIEFILE, $this->cookieJar);
curl_setopt($this->curl,CURLOPT_AUTOREFERER, true);
curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true);
}
function get($url)
{
$this->curl = curl_init($url);
$this->setup();
return $this->request();
}
function getAll($reg,$str)
{
preg_match_all($reg,$str,$matches);
return $matches[1];
}
function postForm($url, $fields, $referer='')
{
$this->curl = curl_init($url);
$this->setup();
curl_setopt($this->curl, CURLOPT_URL, $url);
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_REFERER, $referer);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);
return $this->request();
}
function getInfo($info)
{
$info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);
return $info;
}
function request()
{
return curl_exec($this->curl);
}
}
?>
``` |
27,020 | <p>I have an Excel Spreadsheet like this</p>
<pre>
id | data for id
| more data for id
id | data for id
id | data for id
| more data for id
| even more data for id
id | data for id
| more data for id
id | data for id
id | data for id
| more data for id
</pre>
<p>Now I want to group the data of one id by alternating the background color of the rows</p>
<pre>
var color = white
for each row
if the first cell is not empty and color is white
set color to green
if the first cell is not empty and color is green
set color to white
set background of row to color
</pre>
<p>Can anyone help me with a macro or some VBA code</p>
<p>Thanks</p>
| [
{
"answer_id": 27043,
"author": "Daniel Pollard",
"author_id": 2758,
"author_profile": "https://Stackoverflow.com/users/2758",
"pm_score": 0,
"selected": false,
"text": "<p>If you select the Conditional Formatting menu option under the Format menu item, you will be given a dialog that lets you construct some logic to apply to that cell.</p>\n\n<p>Your logic might not be the same as your code above, it might look more like:</p>\n\n<p>Cell Value is | equal to | | and | White .... Then choose the color.</p>\n\n<p>You can select the add button and make the condition as large as you need.</p>\n"
},
{
"answer_id": 27069,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 1,
"selected": false,
"text": "<p>Do you have to use code?\nif the table is static, then why not use the auto formatting capability?</p>\n\n<p><img src=\"https://i.stack.imgur.com/7gJRz.jpg\" alt=\"enter image description here\"></p>\n\n<p>It may also help if you \"merge cells\" of the same data. so maybe if you merge the cells of the \"data, more data, even more data\" into one cell, you can more easily deal with classic \"each row is a row\" case.</p>\n"
},
{
"answer_id": 27139,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 3,
"selected": true,
"text": "<p>I think this does what you are looking for. Flips color when the cell in column A changes value. Runs until there is no value in column B.</p>\n\n<pre><code>Public Sub HighLightRows()\n Dim i As Integer\n i = 1\n Dim c As Integer\n c = 3 'red\n\n Do While (Cells(i, 2) <> \"\")\n If (Cells(i, 1) <> \"\") Then 'check for new ID\n If c = 3 Then\n c = 4 'green\n Else\n c = 3 'red\n End If\n End If\n\n Rows(Trim(Str(i)) + \":\" + Trim(Str(i))).Interior.ColorIndex = c\n i = i + 1\n Loop\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 6768304,
"author": "Adriano P",
"author_id": 276311,
"author_profile": "https://Stackoverflow.com/users/276311",
"pm_score": 5,
"selected": false,
"text": "<p>I use this formula to get the input for a conditional formatting:</p>\n\n<pre><code>=IF(B2=B1,E1,1-E1)) [content of cell E2]\n</code></pre>\n\n<p>Where column B contains the item that needs to be grouped and E is an auxiliary column. Every time that the upper cell (B1 on this case) is the same as the current one (B2), the upper row content from column E is returned. Otherwise, it will return 1 minus that content (that is, the outupt will be 0 or 1, depending on the value of the upper cell).</p>\n\n<p><img src=\"https://i.stack.imgur.com/H6WP0.png\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/sE57q.png\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/4hadL.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 16961839,
"author": "Laurent S.",
"author_id": 2187273,
"author_profile": "https://Stackoverflow.com/users/2187273",
"pm_score": 2,
"selected": false,
"text": "<p>Based on Jason Z's answer, which from my tests seems to be wrong (at least on Excel 2010), here's a bit of code that happens to work for me :</p>\n\n<pre><code>Public Sub HighLightRows()\n Dim i As Integer\n i = 2 'start at 2, cause there's nothing to compare the first row with\n Dim c As Integer\n c = 2 'Color 1. Check http://dmcritchie.mvps.org/excel/colors.htm for color indexes\n\n Do While (Cells(i, 1) <> \"\")\n If (Cells(i, 1) <> Cells(i - 1, 1)) Then 'check for different value in cell A (index=1)\n If c = 2 Then\n c = 34 'color 2\n Else\n c = 2 'color 1\n End If\n End If\n\n Rows(Trim(Str(i)) + \":\" + Trim(Str(i))).Interior.ColorIndex = c\n i = i + 1\n Loop\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 28683156,
"author": "KyleF",
"author_id": 4598660,
"author_profile": "https://Stackoverflow.com/users/4598660",
"pm_score": 1,
"selected": false,
"text": "<p>I'm barrowing this and tried to modify it for my use. I have order numbers in column a and some orders take multiple rows. Just want to alternate the white and gray per order number. What I have here alternates each row.</p>\n\n<p><code>\nChangeBackgroundColor()\n' ChangeBackgroundColor Macro\n'\n' Keyboard Shortcut: Ctrl+Shift+B\nDim a As Integer\n a = 1\n Dim c As Integer\n c = 15 'gray\n Do While (Cells(a, 2) <> \"\")\n If (Cells(a, 1) <> \"\") Then 'check for new ID\n If c = 15 Then\n c = 2 'white\n Else\n c = 15 'gray\n End If\n End If\n Rows(Trim(Str(a)) + \":\" + Trim(Str(a))).Interior.ColorIndex = c\n a = a + 1\n Loop</p>\n\n<p>End Sub</code></p>\n"
},
{
"answer_id": 30895802,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 0,
"selected": false,
"text": "<p>I have reworked Bartdude's answer, for Light Grey / White based upon a configurable column, using RGB values. A boolean var is flipped when the value changes and this is used to index the colours array via the integer values of True and False. Works for me on 2010. Call the sub with the sheet number.</p>\n\n<pre><code>Public Sub HighLightRows(intSheet As Integer)\n Dim intRow As Integer: intRow = 2 ' start at 2, cause there's nothing to compare the first row with\n Dim intCol As Integer: intCol = 1 ' define the column with changing values\n Dim Colr1 As Boolean: Colr1 = True ' Will flip True/False; adding 2 gives 1 or 2\n Dim lngColors(2 + True To 2 + False) As Long ' Indexes : 1 and 2\n ' True = -1, array index 1. False = 0, array index 2.\n lngColors(2 + False) = RGB(235, 235, 235) ' lngColors(2) = light grey\n lngColors(2 + True) = RGB(255, 255, 255) ' lngColors(1) = white\n\n Do While (Sheets(intSheet).Cells(intRow, 1) <> \"\")\n 'check for different value in intCol, flip the boolean if it's different\n If (Sheets(intSheet).Cells(intRow, intCol) <> Sheets(intSheet).Cells(intRow - 1, intCol)) Then Colr1 = Not Colr1\n Sheets(intSheet).Rows(intRow).Interior.Color = lngColors(2 + Colr1) ' one colour or the other\n ' Optional : retain borders (these no longer show through when interior colour is changed) by specifically setting them\n With Sheets(intSheet).Rows(intRow).Borders\n .LineStyle = xlContinuous\n .Weight = xlThin\n .Color = RGB(220, 220, 220)\n End With\n intRow = intRow + 1\n Loop\nEnd Sub\n</code></pre>\n\n<p>Optional bonus : for SQL data, colour any NULL values with the same yellow as used in SSMS</p>\n\n<pre><code>Public Sub HighLightNULLs(intSheet As Integer)\n Dim intRow As Integer: intRow = 2 ' start at 2 to avoid the headings\n Dim intCol As Integer\n Dim lngColor As Long: lngColor = RGB(255, 255, 225) ' pale yellow\n\n For intRow = intRow To Sheets(intSheet).UsedRange.Rows.Count\n For intCol = 1 To Sheets(intSheet).UsedRange.Columns.Count\n If Sheets(intSheet).Cells(intRow, intCol) = \"NULL\" Then Sheets(intSheet).Cells(intRow, intCol).Interior.Color = lngColor\n Next intCol\n Next intRow\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 34124537,
"author": "GONeale",
"author_id": 41211,
"author_profile": "https://Stackoverflow.com/users/41211",
"pm_score": -1,
"selected": false,
"text": "<p>I use this rule in Excel to format alternating rows:</p>\n\n<ol>\n<li>Highlight the rows you wish to apply an alternating style to.</li>\n<li>Press \"Conditional Formatting\" -> New Rule</li>\n<li>Select \"Use a formula to determine which cells to format\" (last entry)</li>\n<li>Enter rule in format value: <strong><code>=MOD(ROW(),2)=0</code></strong></li>\n<li>Press \"Format\", make required formatting for alternating rows, eg. Fill -> Color.</li>\n<li>Press OK, Press OK.</li>\n</ol>\n\n<p>If you wish to format alternating columns instead, use <strong><code>=MOD(COLUMN(),2)=0</code></strong></p>\n\n<p>Voila!</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2798/"
] | I have an Excel Spreadsheet like this
```
id | data for id
| more data for id
id | data for id
id | data for id
| more data for id
| even more data for id
id | data for id
| more data for id
id | data for id
id | data for id
| more data for id
```
Now I want to group the data of one id by alternating the background color of the rows
```
var color = white
for each row
if the first cell is not empty and color is white
set color to green
if the first cell is not empty and color is green
set color to white
set background of row to color
```
Can anyone help me with a macro or some VBA code
Thanks | I think this does what you are looking for. Flips color when the cell in column A changes value. Runs until there is no value in column B.
```
Public Sub HighLightRows()
Dim i As Integer
i = 1
Dim c As Integer
c = 3 'red
Do While (Cells(i, 2) <> "")
If (Cells(i, 1) <> "") Then 'check for new ID
If c = 3 Then
c = 4 'green
Else
c = 3 'red
End If
End If
Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.ColorIndex = c
i = i + 1
Loop
End Sub
``` |
27,030 | <p>I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?</p>
| [
{
"answer_id": 27212,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 7,
"selected": true,
"text": "<p>EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.</p>\n\n<p>To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply <a href=\"https://github.com/douglascrockford/JSON-js/blob/master/json2.js\" rel=\"noreferrer\">serialize the two arrays to JSON</a> and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to <em>each</em> of the objects within the arrays as well to see which ones were different.</p>\n\n<p>Another option is to use a library which has some nice facilities for comparing objects - I use and recommend <a href=\"http://www.mochikit.com/\" rel=\"noreferrer\"><strong>MochiKit</strong></a>.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong> <a href=\"https://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932\">The answer kamens gave</a> deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).</p>\n\n<p>Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:</p>\n\n<pre><code>function objectsAreSame(x, y) {\n var objectsAreSame = true;\n for(var propertyName in x) {\n if(x[propertyName] !== y[propertyName]) {\n objectsAreSame = false;\n break;\n }\n }\n return objectsAreSame;\n}\n</code></pre>\n\n<p>The assumption is that both objects have the same exact list of properties.</p>\n\n<p>Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)</p>\n"
},
{
"answer_id": 27932,
"author": "kamens",
"author_id": 1335,
"author_profile": "https://Stackoverflow.com/users/1335",
"pm_score": 5,
"selected": false,
"text": "<p>Honestly, with 8 objects max and 8 properties max per object, your best bet is to just traverse each object and make the comparisons directly. It'll be fast and it'll be easy.</p>\n\n<p>If you're going to be using these types of comparisons often, then I agree with Jason about JSON serialization...but otherwise there's no need to slow down your app with a new library or JSON serialization code.</p>\n"
},
{
"answer_id": 649465,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>objectsAreSame</code> function mentioned in @JasonBunting's answer works fine for me. However, there's a little problem: If <code>x[propertyName]</code> and <code>y[propertyName]</code> are objects (<code>typeof x[propertyName] == 'object'</code>), you'll need to call the function recursively in order to compare them.</p>\n"
},
{
"answer_id": 3746944,
"author": "Yuval",
"author_id": 404861,
"author_profile": "https://Stackoverflow.com/users/404861",
"pm_score": 4,
"selected": false,
"text": "<p>I have worked a bit on a simple algorithm to compare contents of two objects and return an intelligible list of difference. Thought I would share. It borrows some ideas for jQuery, namely the <code>map</code> function implementation and the object and array type checking. </p>\n\n<p>It returns a list of \"diff objects\", which are arrays with the diff info. It's very simple.</p>\n\n<p>Here it is: </p>\n\n<pre><code>// compare contents of two objects and return a list of differences\n// returns an array where each element is also an array in the form:\n// [accessor, diffType, leftValue, rightValue ]\n//\n// diffType is one of the following:\n// value: when primitive values at that index are different\n// undefined: when values in that index exist in one object but don't in \n// another; one of the values is always undefined\n// null: when a value in that index is null or undefined; values are\n// expressed as boolean values, indicated wheter they were nulls\n// type: when values in that index are of different types; values are \n// expressed as types\n// length: when arrays in that index are of different length; values are\n// the lengths of the arrays\n//\n\nfunction DiffObjects(o1, o2) {\n // choose a map() impl.\n // you may use $.map from jQuery if you wish\n var map = Array.prototype.map?\n function(a) { return Array.prototype.map.apply(a, Array.prototype.slice.call(arguments, 1)); } :\n function(a, f) { \n var ret = new Array(a.length), value;\n for ( var i = 0, length = a.length; i < length; i++ ) \n ret[i] = f(a[i], i);\n return ret.concat();\n };\n\n // shorthand for push impl.\n var push = Array.prototype.push;\n\n // check for null/undefined values\n if ((o1 == null) || (o2 == null)) {\n if (o1 != o2)\n return [[\"\", \"null\", o1!=null, o2!=null]];\n\n return undefined; // both null\n }\n // compare types\n if ((o1.constructor != o2.constructor) ||\n (typeof o1 != typeof o2)) {\n return [[\"\", \"type\", Object.prototype.toString.call(o1), Object.prototype.toString.call(o2) ]]; // different type\n\n }\n\n // compare arrays\n if (Object.prototype.toString.call(o1) == \"[object Array]\") {\n if (o1.length != o2.length) { \n return [[\"\", \"length\", o1.length, o2.length]]; // different length\n }\n var diff =[];\n for (var i=0; i<o1.length; i++) {\n // per element nested diff\n var innerDiff = DiffObjects(o1[i], o2[i]);\n if (innerDiff) { // o1[i] != o2[i]\n // merge diff array into parent's while including parent object name ([i])\n push.apply(diff, map(innerDiff, function(o, j) { o[0]=\"[\" + i + \"]\" + o[0]; return o; }));\n }\n }\n // if any differences were found, return them\n if (diff.length)\n return diff;\n // return nothing if arrays equal\n return undefined;\n }\n\n // compare object trees\n if (Object.prototype.toString.call(o1) == \"[object Object]\") {\n var diff =[];\n // check all props in o1\n for (var prop in o1) {\n // the double check in o1 is because in V8 objects remember keys set to undefined \n if ((typeof o2[prop] == \"undefined\") && (typeof o1[prop] != \"undefined\")) {\n // prop exists in o1 but not in o2\n diff.push([\"[\" + prop + \"]\", \"undefined\", o1[prop], undefined]); // prop exists in o1 but not in o2\n\n }\n else {\n // per element nested diff\n var innerDiff = DiffObjects(o1[prop], o2[prop]);\n if (innerDiff) { // o1[prop] != o2[prop]\n // merge diff array into parent's while including parent object name ([prop])\n push.apply(diff, map(innerDiff, function(o, j) { o[0]=\"[\" + prop + \"]\" + o[0]; return o; }));\n }\n\n }\n }\n for (var prop in o2) {\n // the double check in o2 is because in V8 objects remember keys set to undefined \n if ((typeof o1[prop] == \"undefined\") && (typeof o2[prop] != \"undefined\")) {\n // prop exists in o2 but not in o1\n diff.push([\"[\" + prop + \"]\", \"undefined\", undefined, o2[prop]]); // prop exists in o2 but not in o1\n\n }\n }\n // if any differences were found, return them\n if (diff.length)\n return diff;\n // return nothing if objects equal\n return undefined;\n }\n // if same type and not null or objects or arrays\n // perform primitive value comparison\n if (o1 != o2)\n return [[\"\", \"value\", o1, o2]];\n\n // return nothing if values are equal\n return undefined;\n}\n</code></pre>\n"
},
{
"answer_id": 6074070,
"author": "jwood",
"author_id": 346392,
"author_profile": "https://Stackoverflow.com/users/346392",
"pm_score": 4,
"selected": false,
"text": "<p>I know this is an old question and the answers provided work fine ... but this is a bit shorter and doesn't require any additional libraries ( i.e. JSON ):</p>\n\n<pre><code>function arraysAreEqual(ary1,ary2){\n return (ary1.join('') == ary2.join(''));\n}\n</code></pre>\n"
},
{
"answer_id": 25237317,
"author": "Keshav Kalra",
"author_id": 1746436,
"author_profile": "https://Stackoverflow.com/users/1746436",
"pm_score": 1,
"selected": false,
"text": "<p>Please try this one:</p>\n\n<pre><code>function used_to_compare_two_arrays(a, b)\n{\n // This block will make the array of indexed that array b contains a elements\n var c = a.filter(function(value, index, obj) {\n return b.indexOf(value) > -1;\n });\n\n // This is used for making comparison that both have same length if no condition go wrong \n if (c.length !== a.length) {\n return 0;\n } else{\n return 1;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 42904039,
"author": "Maxime Pacary",
"author_id": 488666,
"author_profile": "https://Stackoverflow.com/users/488666",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my attempt, using <a href=\"https://nodejs.org/api/assert.html\" rel=\"nofollow noreferrer\"><strong>Node's assert module</strong></a> + npm package <a href=\"https://www.npmjs.com/package/object-hash\" rel=\"nofollow noreferrer\"><strong>object-hash</strong></a>.</p>\n\n<p>I suppose that you would like to check if two arrays contain the same objects, even if those objects are ordered differently between the two arrays.</p>\n\n<pre><code>var assert = require('assert');\nvar hash = require('object-hash');\n\nvar obj1 = {a: 1, b: 2, c: 333},\n obj2 = {b: 2, a: 1, c: 444},\n obj3 = {b: \"AAA\", c: 555},\n obj4 = {c: 555, b: \"AAA\"};\n\nvar array1 = [obj1, obj2, obj3, obj4];\nvar array2 = [obj3, obj2, obj4, obj1]; // [obj3, obj3, obj2, obj1] should work as well\n\n// calling assert.deepEquals(array1, array2) at this point FAILS (throws an AssertionError)\n// even if array1 and array2 contain the same objects in different order,\n// because array1[0].c !== array2[0].c\n\n// sort objects in arrays by their hashes, so that if the arrays are identical,\n// their objects can be compared in the same order, one by one\nvar array1 = sortArrayOnHash(array1);\nvar array2 = sortArrayOnHash(array2);\n\n// then, this should output \"PASS\"\ntry {\n assert.deepEqual(array1, array2);\n console.log(\"PASS\");\n} catch (e) {\n console.log(\"FAIL\");\n console.log(e);\n}\n\n// You could define as well something like Array.prototype.sortOnHash()...\nfunction sortArrayOnHash(array) {\n return array.sort(function(a, b) {\n return hash(a) > hash(b);\n });\n}\n</code></pre>\n"
},
{
"answer_id": 52842903,
"author": "Sanjay Verma",
"author_id": 10515006,
"author_profile": "https://Stackoverflow.com/users/10515006",
"pm_score": 4,
"selected": false,
"text": "<p>I tried <code>JSON.stringify()</code> and worked for me.</p>\n\n<pre><code>let array1 = [1,2,{value:'alpha'}] , array2 = [{value:'alpha'},'music',3,4];\n\nJSON.stringify(array1) // \"[1,2,{\"value\":\"alpha\"}]\"\n\nJSON.stringify(array2) // \"[{\"value\":\"alpha\"},\"music\",3,4]\"\n\nJSON.stringify(array1) === JSON.stringify(array2); // false\n</code></pre>\n"
},
{
"answer_id": 54031184,
"author": "Henry Sellars",
"author_id": 9643152,
"author_profile": "https://Stackoverflow.com/users/9643152",
"pm_score": 0,
"selected": false,
"text": "<p>using <code>_.some</code> from lodash: <a href=\"https://lodash.com/docs/4.17.11#some\" rel=\"nofollow noreferrer\">https://lodash.com/docs/4.17.11#some</a></p>\n\n<pre><code>const array1AndArray2NotEqual = \n _.some(array1, (a1, idx) => a1.key1 !== array2[idx].key1 \n || a1.key2 !== array2[idx].key2 \n || a1.key3 !== array2[idx].key3);\n</code></pre>\n"
},
{
"answer_id": 55256318,
"author": "ttulka",
"author_id": 2190498,
"author_profile": "https://Stackoverflow.com/users/2190498",
"pm_score": 6,
"selected": false,
"text": "<p>As serialization doesn't work generally (only when the order of properties matches: <code>JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})</code>) you have to check the count of properties and compare each property as well:</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>const objectsEqual = (o1, o2) =>\r\n Object.keys(o1).length === Object.keys(o2).length \r\n && Object.keys(o1).every(p => o1[p] === o2[p]);\r\n\r\nconst obj1 = { name: 'John', age: 33};\r\nconst obj2 = { age: 33, name: 'John' };\r\nconst obj3 = { name: 'John', age: 45 };\r\n \r\nconsole.log(objectsEqual(obj1, obj2)); // true\r\nconsole.log(objectsEqual(obj1, obj3)); // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>If you need a deep comparison, you can call the function recursively:</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>const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };\r\nconst obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };\r\nconst obj3 = { name: 'John', age: 33 };\r\n\r\nconst objectsEqual = (o1, o2) => \r\n typeof o1 === 'object' && Object.keys(o1).length > 0 \r\n ? Object.keys(o1).length === Object.keys(o2).length \r\n && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))\r\n : o1 === o2;\r\n \r\nconsole.log(objectsEqual(obj1, obj2)); // true\r\nconsole.log(objectsEqual(obj1, obj3)); // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Then it's easy to use this function to compare objects in arrays:</p>\n\n<pre><code>const arr1 = [obj1, obj1];\nconst arr2 = [obj1, obj2];\nconst arr3 = [obj1, obj3];\n\nconst arraysEqual = (a1, a2) => \n a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));\n\nconsole.log(arraysEqual(arr1, arr2)); // true\nconsole.log(arraysEqual(arr1, arr3)); // false\n</code></pre>\n"
},
{
"answer_id": 65966136,
"author": "Flash Noob",
"author_id": 12106367,
"author_profile": "https://Stackoverflow.com/users/12106367",
"pm_score": -1,
"selected": false,
"text": "<p>comparing with json is pretty bad. try this package to compare nested arrays and get the difference.</p>\n<blockquote>\n<p><a href=\"https://www.npmjs.com/package/deep-object-diff\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/deep-object-diff</a></p>\n</blockquote>\n"
},
{
"answer_id": 66147209,
"author": "Wolfram",
"author_id": 12634461,
"author_profile": "https://Stackoverflow.com/users/12634461",
"pm_score": 3,
"selected": false,
"text": "<p>There is a optimized code for case when function needs to equals to empty arrays (and returning false in that case)</p>\n<pre><code>const objectsEqual = (o1, o2) => {\n if (o2 === null && o1 !== null) return false;\n return o1 !== null && typeof o1 === 'object' && Object.keys(o1).length > 0 ?\n Object.keys(o1).length === Object.keys(o2).length && \n Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))\n : (o1 !== null && Array.isArray(o1) && Array.isArray(o2) && !o1.length && \n !o2.length) ? true : o1 === o2;\n}\n</code></pre>\n"
},
{
"answer_id": 66199056,
"author": "Vladimir Malikov",
"author_id": 14929085,
"author_profile": "https://Stackoverflow.com/users/14929085",
"pm_score": 0,
"selected": false,
"text": "<p>There`s my solution. It will compare arrays which also have objects and arrays. Elements can be stay in any positions.\nExample:</p>\n<pre><code>const array1 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];\nconst array2 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];\n\nconst arraysCompare = (a1, a2) => {\n if (a1.length !== a2.length) return false;\n const objectIteration = (object) => {\n const result = [];\n const objectReduce = (obj) => {\n for (let i in obj) {\n if (typeof obj[i] !== 'object') {\n result.push(`${i}${obj[i]}`);\n } else {\n objectReduce(obj[i]);\n }\n }\n };\n objectReduce(object);\n return result;\n };\n const reduceArray1 = a1.map(item => {\n if (typeof item !== 'object') return item;\n return objectIteration(item).join('');\n });\n const reduceArray2 = a2.map(item => {\n if (typeof item !== 'object') return item;\n return objectIteration(item).join('');\n });\n const compare = reduceArray1.map(item => reduceArray2.includes(item));\n return compare.reduce((acc, item) => acc + Number(item)) === a1.length;\n};\n\nconsole.log(arraysCompare(array1, array2));\n</code></pre>\n"
},
{
"answer_id": 67489928,
"author": "Shawn W",
"author_id": 3621197,
"author_profile": "https://Stackoverflow.com/users/3621197",
"pm_score": 2,
"selected": false,
"text": "<p>My practice implementation with sorting, tested and working.</p>\n<pre><code>const obj1 = { name: 'John', age: 33};\nconst obj2 = { age: 33, name: 'John' };\nconst obj3 = { name: 'John', age: 45 };\n\nconst equalObjs = ( obj1, obj2 ) => {\nlet keyExist = false;\nfor ( const [key, value] of Object.entries(obj1) ) {\n // Search each key in reference object and attach a callback function to \n // compare the two object keys\n if( Object.keys(obj2).some( ( e ) => e == key ) ) {\n keyExist = true;\n }\n}\n\nreturn keyExist;\n\n}\n\n\nconsole.info( equalObjs( obj1, obj2 ) );\n</code></pre>\n<p>Compare your arrays</p>\n<pre><code>// Sort Arrays\n var arr1 = arr1.sort(( a, b ) => {\n var fa = Object.keys(a);\n var fb = Object.keys(b);\n\n if (fa < fb) {\n return -1;\n }\n if (fa > fb) {\n return 1;\n }\n return 0;\n});\n\nvar arr2 = arr2.sort(( a, b ) => {\n var fa = Object.keys(a);\n var fb = Object.keys(b);\n\n if (fa < fb) {\n return -1;\n }\n if (fa > fb) {\n return 1;\n }\n return 0;\n});\n\nconst equalArrays = ( arr1, arr2 ) => {\n // If the arrays are different length we an eliminate immediately\n if( arr1.length !== arr2.length ) {\n return false;\n } else if ( arr1.every(( obj, index ) => equalObjs( obj, arr2[index] ) ) ) {\n return true;\n } else { \n return false;\n }\n }\n\n console.info( equalArrays( arr1, arr2 ) );\n</code></pre>\n"
},
{
"answer_id": 69896160,
"author": "i6f70",
"author_id": 11617744,
"author_profile": "https://Stackoverflow.com/users/11617744",
"pm_score": 2,
"selected": false,
"text": "<p>I am sharing my compare function implementation as it might be helpful for others:</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-js lang-js prettyprint-override\"><code> /*\n null AND null // true\n undefined AND undefined // true\n null AND undefined // false\n [] AND [] // true\n [1, 2, 'test'] AND ['test', 2, 1] // true\n [1, 2, 'test'] AND ['test', 2, 3] // false\n [undefined, 2, 'test'] AND ['test', 2, 1] // false\n [undefined, 2, 'test'] AND ['test', 2, undefined] // true\n [[1, 2], 'test'] AND ['test', [2, 1]] // true\n [1, 'test'] AND ['test', [2, 1]] // false\n [[2, 1], 'test'] AND ['test', [2, 1]] // true\n [[2, 1], 'test'] AND ['test', [2, 3]] // false\n [[[3, 4], 2], 'test'] AND ['test', [2, [3, 4]]] // true\n [[[3, 4], 2], 'test'] AND ['test', [2, [5, 4]]] // false\n [{x: 1, y: 2}, 'test'] AND ['test', {x: 1, y: 2}] // true\n 1 AND 1 // true\n {test: 1} AND ['test', 2, 1] // false\n {test: 1} AND {test: 1} // true\n {test: 1} AND {test: 2} // false\n {test: [1, 2]} AND {test: [1, 2]} // true\n {test: [1, 2]} AND {test: [1]} // false\n {test: [1, 2], x: 1} AND {test: [1, 2], x: 2} // false\n {test: [1, { z: 5 }], x: 1} AND {x: 1, test: [1, { z: 5}]} // true\n {test: [1, { z: 5 }], x: 1} AND {x: 1, test: [1, { z: 6}]} // false\n */\n function is_equal(x, y) {\n const\n arr1 = x,\n arr2 = y,\n is_objects_equal = function (obj_x, obj_y) {\n if (!(\n typeof obj_x === 'object' &&\n Object.keys(obj_x).length > 0\n ))\n return obj_x === obj_y;\n\n return Object.keys(obj_x).length === Object.keys(obj_y).length &&\n Object.keys(obj_x).every(p => is_objects_equal(obj_x[p], obj_y[p]));\n }\n ;\n\n if (!( Array.isArray(arr1) && Array.isArray(arr2) ))\n return (\n arr1 && typeof arr1 === 'object' &&\n arr2 && typeof arr2 === 'object'\n )\n ? is_objects_equal(arr1, arr2)\n : arr1 === arr2;\n\n if (arr1.length !== arr2.length)\n return false;\n\n for (const idx_1 of arr1.keys())\n for (const idx_2 of arr2.keys())\n if (\n (\n Array.isArray(arr1[idx_1]) &&\n this.is_equal(arr1[idx_1], arr2[idx_2])\n ) ||\n is_objects_equal(arr1[idx_1], arr2[idx_2])\n )\n {\n arr2.splice(idx_2, 1);\n break;\n }\n\n return !arr2.length;\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 70286558,
"author": "Mr.P",
"author_id": 3257387,
"author_profile": "https://Stackoverflow.com/users/3257387",
"pm_score": 1,
"selected": false,
"text": "<p>not sure about the performance ... will have to test on big objects .. however, this works great for me.. the advantage it has compared to the other solutions is, the objects/array do not have to be in the same order ....</p>\n<p>it practically takes the first object in the first array, and scans the second array for every objects .. if it's a match, it will proceed to another</p>\n<p>there is absolutely a way for optimization but it's working :)</p>\n<p>thx to <a href=\"https://stackoverflow.com/a/55256318/3257387\">@ttulka</a> I got inspired by his work ... just worked on it a little bit</p>\n<pre><code>const objectsEqual = (o1, o2) => {\n let match = false\n if(typeof o1 === 'object' && Object.keys(o1).length > 0) {\n match = (Object.keys(o1).length === Object.keys(o2).length && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p])))\n }else {\n match = (o1 === o2)\n }\n return match\n}\n\nconst arraysEqual = (a1, a2) => {\n let finalMatch = []\n let itemFound = []\n \n if(a1.length === a2.length) {\n finalMatch = []\n a1.forEach( i1 => {\n itemFound = []\n a2.forEach( i2 => { \n itemFound.push(objectsEqual(i1, i2)) \n })\n finalMatch.push(itemFound.some( i => i === true)) \n }) \n } \n return finalMatch.every(i => i === true)\n}\n\nconst ar1 = [\n { id: 1, name: "Johnny", data: { body: "Some text"}},\n { id: 2, name: "Jimmy"}\n]\nconst ar2 = [\n {name: "Jimmy", id: 2},\n {name: "Johnny", data: { body: "Some text"}, id: 1}\n]\n\n\nconsole.log("Match:",arraysEqual(ar1, ar2))\n</code></pre>\n<p>jsfiddle: <a href=\"https://jsfiddle.net/x1pubs6q/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/x1pubs6q/</a></p>\n<p>or just use lodash :))))</p>\n<pre><code>const _ = require('lodash')\n\nconst isArrayEqual = (x, y) => {\n return _.isEmpty(_.xorWith(x, y, _.isEqual));\n};\n</code></pre>\n"
},
{
"answer_id": 72691567,
"author": "Oussama Filani",
"author_id": 9012478,
"author_profile": "https://Stackoverflow.com/users/9012478",
"pm_score": 0,
"selected": false,
"text": "<p>This is work for me to compare two array of objects without taking into consideration the order of the items</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-js lang-js prettyprint-override\"><code>const collection1 = [\n { id: \"1\", name: \"item 1\", subtitle: \"This is a subtitle\", parentId: \"1\" },\n { id: \"2\", name: \"item 2\", parentId: \"1\" },\n { id: \"3\", name: \"item 3\", parentId: \"1\" },\n]\nconst collection2 = [\n { id: \"3\", name: \"item 3\", parentId: \"1\" },\n { id: \"2\", name: \"item 2\", parentId: \"1\" },\n { id: \"1\", name: \"item 1\", subtitle: \"This is a subtitle\", parentId: \"1\" },\n]\n\n\nconst contains = (arr, obj) => {\n let i = arr.length;\n while (i--) {\n if (JSON.stringify(arr[i]) === JSON.stringify(obj)) {\n return true;\n }\n }\n return false;\n}\n\nconst isEqual = (obj1, obj2) => {\n let n = 0\n if (obj1.length !== obj2.length) {\n return false;\n }\n for (let i = 0; i < obj1.length; i++) {\n if (contains(obj2, obj1[i])) {\n n++\n }\n }\n return n === obj1.length\n}\n\nconsole.log(isEqual(collection1,collection2))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>if you take into consideration the order of the items use built in function in lodash <a href=\"https://docs-lodash.com/v4/is-equal/\" rel=\"nofollow noreferrer\">isEqual</a></p>\n"
},
{
"answer_id": 72846327,
"author": "C-lio Garcia",
"author_id": 2638849,
"author_profile": "https://Stackoverflow.com/users/2638849",
"pm_score": -1,
"selected": false,
"text": "<p>If you stringify them...</p>\n<pre><code>type AB = {\n nome: string;\n}\n\nconst a: AB[] = [{ nome: 'Célio' }];\nconst b: AB[] = [{ nome: 'Célio' }];\n\nconsole.log(a === b); // false\nconsole.log(JSON.stringify(a) === JSON.stringify(b)); // true\n\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2176/"
] | I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts? | EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply [serialize the two arrays to JSON](https://github.com/douglascrockford/JSON-js/blob/master/json2.js) and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to *each* of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend [**MochiKit**](http://www.mochikit.com/).
---
**EDIT:** [The answer kamens gave](https://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932) deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).
Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
```
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
```
The assumption is that both objects have the same exact list of properties.
Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :) |
27,034 | <p>My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled:</p>
<pre><code>var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings");
shareProxiesPref.disabled = proxyTypePref.value != 1;
</code></pre>
<p>Isn't it better to do an if on <code>proxyTypePref.value</code>, and then declare the var inside the result, only if you need it?</p>
<p>(Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.)</p>
<hr>
<p><strong>UPDATE:</strong></p>
<p>The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here:</p>
<p><a href="http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js" rel="nofollow noreferrer">http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js</a></p>
<p>Basically, when you look at the <strong>Connect</strong> preferences window in Firefox, clicking the proxy <strong>modes</strong> (radio buttons), causes various form elements to enable|disable.</p>
| [
{
"answer_id": 27039,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>(Incidentally, I also found this form very hard to read in comparison to the normal usage.</p>\n</blockquote>\n\n<p>Not necessarily, although that was my first thought, too. A code should always emphasize its function, especially if it has side effects. If the writer's intention was to emphasize the assignment to <code>sharedProxiesPref.disabled</code> then hey, roll with it. On the other hand, it could have been clearer that the action taking place here is to disable the object, in which case the conditional block would have been better.</p>\n"
},
{
"answer_id": 27098,
"author": "pottedmeat",
"author_id": 2120,
"author_profile": "https://Stackoverflow.com/users/2120",
"pm_score": 3,
"selected": true,
"text": "<p>It depends on the context of this code. If it's running on page load, then it would be better to put this code in an if block.</p>\n\n<p>But, if this is part of a validation function, and the field switches between enabled and disabled throughout the life of the page, then this code sort of makes sense.</p>\n\n<p>It's important to remember that setting disabled to false also alters page state.</p>\n"
},
{
"answer_id": 27319,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>It's hard to say what's better to do without more context.</p>\n\n<p>If this code being executed every time that proxyTypePref changes, then you're always going to need set <code>shareProxiesPref.disabled</code>.</p>\n\n<p>I would agree than an if statement would be a bit more readable than the current code.</p>\n\n<blockquote>\n <p>Isn't it better to do an if on <code>proxyTypePref.value</code>, and then declare the var inside the result, only if you need it?</p>\n</blockquote>\n\n<p>If you're talking strictly about variable declaration, then it doesn't matter whether or not you put it inside an if statement. Any Javascript variable declared inside a function is in scope for the entire function, regardless of where it is declared.</p>\n\n<p>If you're talking about the execution of <code>document.getElementById</code>, then yes, it is much better to not make that call if you don't have to.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled:
```
var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings");
shareProxiesPref.disabled = proxyTypePref.value != 1;
```
Isn't it better to do an if on `proxyTypePref.value`, and then declare the var inside the result, only if you need it?
(Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.)
---
**UPDATE:**
The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here:
<http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js>
Basically, when you look at the **Connect** preferences window in Firefox, clicking the proxy **modes** (radio buttons), causes various form elements to enable|disable. | It depends on the context of this code. If it's running on page load, then it would be better to put this code in an if block.
But, if this is part of a validation function, and the field switches between enabled and disabled throughout the life of the page, then this code sort of makes sense.
It's important to remember that setting disabled to false also alters page state. |
27,044 | <p>I'm accessing an Ubuntu machine using PuTTY, and using gcc.</p>
<p>The default <code>LANG</code> environment variable on this machine is set to <code>en_NZ.UTF-8</code>, which causes GCC to think PuTTY is capable of displaying UTF-8 text, which it doesn't seem to be.
Maybe it's my font, I don't know - it does this:</p>
<pre><code>foo.c:1: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â at end of input
</code></pre>
<p>If I set it with <code>export LANG=en_NZ</code>, then this causes GCC to behave correctly, I get:</p>
<pre><code>foo.c:1: error: expected '=', ',', ';', 'asm' or '__attribute__' at end of input
</code></pre>
<p>but this then causes everything else to go wrong. For example</p>
<pre><code>man foo
man: can't set the locale; make sure $LC_* and $LANG are correct
</code></pre>
<p>I've trawled Google and I can't for the life of me find out what I have to put in there for it to just use ASCII. <code>en_NZ.ASCII</code> doesn't work, nor do any of the other things I can find.</p>
<p>Thanks</p>
| [
{
"answer_id": 27051,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "<p><code>LANG=en_NZ</code> is correct. However, you must make locale files for <code>en_NZ</code>.</p>\n\n<p>For Ubuntu, edit <code>/var/lib/locales/supported.d/local</code> and add <code>en_NZ ISO-8859-1</code> to the file. If your system is another distribution (including Debian), the location will be different. Look at <code>/usr/sbin/locale-gen</code> and see where it stores this info.</p>\n\n<p>Afterwards, run <code>locale-gen</code> to create the <code>en_NZ</code> locale file. Hope this helps!</p>\n"
},
{
"answer_id": 27053,
"author": "Cebjyre",
"author_id": 1612,
"author_profile": "https://Stackoverflow.com/users/1612",
"pm_score": 2,
"selected": false,
"text": "<p>Putty can display utf - I think it is in appearance -> translation (or something, I don't have access to it right now).</p>\n"
},
{
"answer_id": 1419312,
"author": "drewr",
"author_id": 3227,
"author_profile": "https://Stackoverflow.com/users/3227",
"pm_score": 0,
"selected": false,
"text": "<p>For Debian 5.0 Lenny:</p>\n\n<pre><code>aptitude install locales\n</code></pre>\n\n<p>If that's already installed:</p>\n\n<pre><code>dpkg-reconfigure locales\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I'm accessing an Ubuntu machine using PuTTY, and using gcc.
The default `LANG` environment variable on this machine is set to `en_NZ.UTF-8`, which causes GCC to think PuTTY is capable of displaying UTF-8 text, which it doesn't seem to be.
Maybe it's my font, I don't know - it does this:
```
foo.c:1: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â at end of input
```
If I set it with `export LANG=en_NZ`, then this causes GCC to behave correctly, I get:
```
foo.c:1: error: expected '=', ',', ';', 'asm' or '__attribute__' at end of input
```
but this then causes everything else to go wrong. For example
```
man foo
man: can't set the locale; make sure $LC_* and $LANG are correct
```
I've trawled Google and I can't for the life of me find out what I have to put in there for it to just use ASCII. `en_NZ.ASCII` doesn't work, nor do any of the other things I can find.
Thanks | `LANG=en_NZ` is correct. However, you must make locale files for `en_NZ`.
For Ubuntu, edit `/var/lib/locales/supported.d/local` and add `en_NZ ISO-8859-1` to the file. If your system is another distribution (including Debian), the location will be different. Look at `/usr/sbin/locale-gen` and see where it stores this info.
Afterwards, run `locale-gen` to create the `en_NZ` locale file. Hope this helps! |
27,065 | <p>Do any of you know of a tool that will search for .class files and then display their compiled versions?</p>
<p>I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).</p>
| [
{
"answer_id": 27123,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 6,
"selected": false,
"text": "<p>It is easy enough to read the <a href=\"http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.1\" rel=\"noreferrer\">class file signature</a> and get these values without a 3rd party API. All you need to do is read the first 8 bytes.</p>\n\n<pre><code>ClassFile {\n u4 magic;\n u2 minor_version;\n u2 major_version;\n</code></pre>\n\n<p>For class file version 51.0 (Java 7), the opening bytes are:</p>\n\n<pre><code>CA FE BA BE 00 00 00 33\n</code></pre>\n\n<p>...where 0xCAFEBABE are the magic bytes, 0x0000 is the minor version and 0x0033 is the major version.</p>\n\n<pre><code>import java.io.*;\n\npublic class Demo {\n public static void main(String[] args) throws IOException {\n ClassLoader loader = Demo.class.getClassLoader();\n try (InputStream in = loader.getResourceAsStream(\"Demo.class\");\n DataInputStream data = new DataInputStream(in)) {\n if (0xCAFEBABE != data.readInt()) {\n throw new IOException(\"invalid header\");\n }\n int minor = data.readUnsignedShort();\n int major = data.readUnsignedShort();\n System.out.println(major + \".\" + minor);\n }\n }\n}\n</code></pre>\n\n<p>Walking directories (<a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/File.html\" rel=\"noreferrer\">File</a>) and archives (<a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/jar/JarFile.html\" rel=\"noreferrer\">JarFile</a>) looking for class files is trivial.</p>\n\n<p>Oracle's <a href=\"https://blogs.oracle.com/darcy/\" rel=\"noreferrer\">Joe Darcy's blog</a> lists the <a href=\"https://blogs.oracle.com/darcy/entry/source_target_class_file_version\" rel=\"noreferrer\">class version to JDK version mappings</a> up to Java 7:</p>\n\n<pre><code>Target Major.minor Hex\n1.1 45.3 0x2D\n1.2 46.0 0x2E\n1.3 47.0 0x2F\n1.4 48.0 0x30\n5 (1.5) 49.0 0x31\n6 (1.6) 50.0 0x32\n7 (1.7) 51.0 0x33\n8 (1.8) 52.0 0x34\n9 53.0 0x35\n</code></pre>\n"
},
{
"answer_id": 27505,
"author": "staffan",
"author_id": 988,
"author_profile": "https://Stackoverflow.com/users/988",
"pm_score": 8,
"selected": true,
"text": "<p>Use the <a href=\"http://java.sun.com/javase/6/docs/technotes/tools/solaris/javap.html\" rel=\"noreferrer\">javap</a> tool that comes with the JDK. The <code>-verbose</code> option will print the version number of the class file.</p>\n\n<pre><code>> javap -verbose MyClass\nCompiled from \"MyClass.java\"\npublic class MyClass\n SourceFile: \"MyClass.java\"\n minor version: 0\n major version: 46\n...\n</code></pre>\n\n<p>To only show the version:</p>\n\n<pre><code>WINDOWS> javap -verbose MyClass | find \"version\"\nLINUX > javap -verbose MyClass | grep version\n</code></pre>\n"
},
{
"answer_id": 27904,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 3,
"selected": false,
"text": "<p>If you are on a unix system you could just do a </p>\n\n<pre><code>find /target-folder -name \\*.class | xargs file | grep \"version 50\\.0\"\n</code></pre>\n\n<p>(my version of file says \"compiled Java class data, version 50.0\" for java6 classes).</p>\n"
},
{
"answer_id": 6609249,
"author": "phunehehe",
"author_id": 168034,
"author_profile": "https://Stackoverflow.com/users/168034",
"pm_score": 5,
"selected": false,
"text": "<p>On Unix-like</p>\n\n<pre>file /path/to/Thing.class</pre>\n\n<p>Will give the file type and version as well. Here is what the output looks like:</p>\n\n<blockquote>\n <p>compiled Java class data, version 49.0</p>\n</blockquote>\n"
},
{
"answer_id": 25201428,
"author": "igo",
"author_id": 1795220,
"author_profile": "https://Stackoverflow.com/users/1795220",
"pm_score": 3,
"selected": false,
"text": "<p>Yet another java version check</p>\n\n<pre><code>od -t d -j 7 -N 1 ApplicationContextProvider.class | head -1 | awk '{print \"Java\", $2 - 44}'\n</code></pre>\n"
},
{
"answer_id": 35080304,
"author": "PbxMan",
"author_id": 1652451,
"author_profile": "https://Stackoverflow.com/users/1652451",
"pm_score": 3,
"selected": false,
"text": "<p>In eclipse if you don't have sources attached. Mind the first line after the attach source button.</p>\n\n<p>// Compiled from CDestinoLog.java (<strong>version 1.5 : 49.0, super bit</strong>)</p>\n\n<p><a href=\"https://i.stack.imgur.com/Mku2A.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Mku2A.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 37256401,
"author": "Radoslav Kastiel",
"author_id": 6341080,
"author_profile": "https://Stackoverflow.com/users/6341080",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe this helps somebody, too. Looks there is more easy way to get JAVA version used to compile/build .class. This way is useful to application/class self check on JAVA version.</p>\n\n<p>I have gone through JDK library and found this useful constant:\n<em>com.sun.deploy.config.BuiltInProperties.CURRENT_VERSION</em>.\nI do not know since when it is in JAVA JDK.</p>\n\n<p>Trying this piece of code for several version constants I get result below:</p>\n\n<p><strong>src:</strong></p>\n\n<pre><code>System.out.println(\"JAVA DEV ver.: \" + com.sun.deploy.config.BuiltInProperties.CURRENT_VERSION);\nSystem.out.println(\"JAVA RUN v. X.Y: \" + System.getProperty(\"java.specification.version\") );\nSystem.out.println(\"JAVA RUN v. W.X.Y.Z: \" + com.sun.deploy.config.Config.getJavaVersion() ); //_javaVersionProperty\nSystem.out.println(\"JAVA RUN full ver.: \" + System.getProperty(\"java.runtime.version\") + \" (may return unknown)\" );\nSystem.out.println(\"JAVA RUN type: \" + com.sun.deploy.config.Config.getJavaRuntimeNameProperty() );\n</code></pre>\n\n<p><strong>output:</strong></p>\n\n<pre><code>JAVA DEV ver.: 1.8.0_77\nJAVA RUN v. X.Y: 1.8\nJAVA RUN v. W.X.Y.Z: 1.8.0_91\nJAVA RUN full ver.: 1.8.0_91-b14 (may return unknown)\nJAVA RUN type: Java(TM) SE Runtime Environment\n</code></pre>\n\n<p>In class bytecode there is really stored constant - see red marked part of Main.call - <a href=\"https://i.stack.imgur.com/u9ocW.png\" rel=\"nofollow noreferrer\">constant stored in .class bytecode</a></p>\n\n<p>Constant is in class used for checking if JAVA version is out of date (see <a href=\"https://stackoverflow.com/questions/20524800/how-java-checks-that-is-out-of-date\">How Java checks that is out of date</a>)...</p>\n"
},
{
"answer_id": 58642950,
"author": "Marinos An",
"author_id": 1555615,
"author_profile": "https://Stackoverflow.com/users/1555615",
"pm_score": 2,
"selected": false,
"text": "<p>A java-based solution using version <a href=\"https://en.wikipedia.org/wiki/Java_class_file#General_layout\" rel=\"nofollow noreferrer\">magic numbers</a>. Below it is used by the program itself to detect its bytecode version.</p>\n\n<pre><code>import java.io.IOException;\nimport java.io.InputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.binary.Hex;\nimport org.apache.commons.io.IOUtils;\npublic class Main {\n public static void main(String[] args) throws DecoderException, IOException {\n Class clazz = Main.class;\n Map<String,String> versionMapping = new HashMap();\n versionMapping.put(\"002D\",\"1.1\");\n versionMapping.put(\"002E\",\"1.2\");\n versionMapping.put(\"002F\",\"1.3\");\n versionMapping.put(\"0030\",\"1.4\");\n versionMapping.put(\"0031\",\"5.0\");\n versionMapping.put(\"0032\",\"6.0\");\n versionMapping.put(\"0033\",\"7\");\n versionMapping.put(\"0034\",\"8\");\n versionMapping.put(\"0035\",\"9\");\n versionMapping.put(\"0036\",\"10\");\n versionMapping.put(\"0037\",\"11\");\n versionMapping.put(\"0038\",\"12\");\n versionMapping.put(\"0039\",\"13\");\n versionMapping.put(\"003A\",\"14\");\n\n InputStream stream = clazz.getClassLoader()\n .getResourceAsStream(clazz.getName().replace(\".\", \"/\") + \".class\");\n byte[] classBytes = IOUtils.toByteArray(stream);\n String versionInHexString = \n Hex.encodeHexString(new byte[]{classBytes[6],classBytes[7]});\n System.out.println(\"bytecode version: \"+versionMapping.get(versionInHexString));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 63204108,
"author": "DuncG",
"author_id": 4712734,
"author_profile": "https://Stackoverflow.com/users/4712734",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way is to scan a class file using many of the answers here which read the class file magic bytes.</p>\n<p>However some code is packaged in jars or other archive formats like WAR and EAR, some of which contain other archives or class files, plus you now have multi-release JAR files - see <a href=\"https://openjdk.java.net/jeps/238\" rel=\"nofollow noreferrer\">JEP-238</a> which use different JDK compilers per JAR.</p>\n<p>This program scans classes from a list of files + folders and prints summary of java class file versions for each component including each JAR within WAR/EARs:</p>\n<pre><code>public static void main(String[] args) throws IOException {\n var files = Arrays.stream(args).map(Path::of).collect(Collectors.toList());\n ShowClassVersions v = new ShowClassVersions();\n for (var f : files) {\n v.scan(f);\n }\n v.print();\n}\n</code></pre>\n<p>Example output from a scan:</p>\n<pre><code>Version: 49.0 ~ JDK-5\n C:\\jars\\junit-platform-console-standalone-1.7.1.jar\nVersion: 50.0 ~ JDK-6\n C:\\jars\\junit-platform-console-standalone-1.7.1.jar\nVersion: 52.0 ~ JDK-8\n C:\\java\\apache-tomcat-10.0.12\\lib\\catalina.jar\n C:\\jars\\junit-platform-console-standalone-1.7.1.jar\nVersion: 53.0 ~ JDK-9\n C:\\java\\apache-tomcat-10.0.12\\lib\\catalina.jar\n C:\\jars\\junit-platform-console-standalone-1.7.1.jar\n</code></pre>\n<p>The scanner:</p>\n<pre><code>public class ShowClassVersions {\n private TreeMap<String, ArrayList<String>> vers = new TreeMap<>();\n private static final byte[] CLASS_MAGIC = new byte[] { (byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe };\n private final byte[] bytes = new byte[8];\n\n private String versionOfClass(InputStream in) throws IOException {\n int c = in.readNBytes(bytes, 0, bytes.length);\n if (c == bytes.length && Arrays.mismatch(bytes, CLASS_MAGIC) == CLASS_MAGIC.length) {\n int minorVersion = (bytes[4] << 8) + (bytes[4] << 0);\n int majorVersion = (bytes[6] << 8) + (bytes[7] << 0);\n return ""+ majorVersion + "." + minorVersion;\n }\n return "Unknown";\n }\n\n private Matcher classes = Pattern.compile("\\\\.(class|ear|war|jar)$").matcher("");\n\n // This code scans any path (dir or file):\n public void scan(Path f) throws IOException {\n try (var stream = Files.find(f, Integer.MAX_VALUE,\n (p, a) -> a.isRegularFile() && classes.reset(p.toString()).find())) {\n stream.forEach(this::scanFile);\n }\n }\n\n private void scanFile(Path f) {\n String fn = f.getFileName().toString();\n try {\n if (fn.endsWith(".ear") || fn.endsWith(".war") || fn.endsWith(".jar"))\n scanArchive(f);\n else if (fn.endsWith(".class"))\n store(f.toAbsolutePath().toString(), versionOfClass(f));\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n private void scanArchive(Path p) throws IOException {\n try (InputStream in = Files.newInputStream(p)) {\n scanArchive(p.toAbsolutePath().toString(), Files.newInputStream(p));\n }\n }\n\n private void scanArchive(String desc, InputStream in) throws IOException {\n HashSet<String> versions = new HashSet<>();\n ZipInputStream zip = new ZipInputStream(in);\n for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {\n String name = entry.getName();\n // There could be different compiler versions per class in one jar\n if (name.endsWith(".class")) {\n versions.add(versionOfClass(zip));\n } else if (name.endsWith(".jar") || name.endsWith(".war")) {\n scanArchive(desc + " => " + name, zip);\n }\n }\n if (versions.size() > 1)\n System.out.println("Warn: "+desc+" contains multiple versions: "+versions);\n\n for (String version : versions)\n store(desc, version);\n }\n\n private String versionOfClass(Path p) throws IOException {\n try (InputStream in = Files.newInputStream(p)) {\n return versionOfClass(in);\n }\n }\n\n private void store(String path, String jdkVer) {\n vers.computeIfAbsent(jdkVer, k -> new ArrayList<>()).add(path);\n }\n\n // Could add a mapping table for JDK names, this guesses based on (JDK17 = 61.0)\n public void print() {\n for (var ver : vers.keySet()) {\n System.out.println("Version: " + ver + " ~ " +jdkOf(ver));\n for (var p : vers.get(ver)) {\n System.out.println(" " + p);\n }\n }\n }\n\n private static String jdkOf(String ver) {\n try {\n return "JDK-"+((int)Float.parseFloat(ver)-44);\n }\n catch(NumberFormatException nfe)\n {\n return "JDK-??";\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 70299029,
"author": "BaiJiFeiLong",
"author_id": 5254103,
"author_profile": "https://Stackoverflow.com/users/5254103",
"pm_score": 2,
"selected": false,
"text": "<h1>Read the 8th byte to decimal:</h1>\n<p>Unix-like: <code>hexdump -s 7 -n 1 -e '"%d"' Main.class</code></p>\n<p>Windows: <code>busybox.exe hexdump -s 7 -n 1 -e '"%d"' Main.class</code></p>\n<h2>Output example:</h2>\n<p><code>55</code></p>\n<h2>Explain:</h2>\n<ul>\n<li><code>-s 7</code> Offset 7</li>\n<li><code>-n 1</code> Limit 1</li>\n<li><code>-e '"%d"'</code> Print as decimal</li>\n</ul>\n<h2>Version map:</h2>\n<pre><code>JDK 1.1 = 45 (0x2D hex)\nJDK 1.2 = 46 (0x2E hex)\nJDK 1.3 = 47 (0x2F hex)\nJDK 1.4 = 48 (0x30 hex)\nJava SE 5.0 = 49 (0x31 hex)\nJava SE 6.0 = 50 (0x32 hex)\nJava SE 7 = 51 (0x33 hex)\nJava SE 8 = 52 (0x34 hex)\nJava SE 9 = 53 (0x35 hex)\nJava SE 10 = 54 (0x36 hex)\nJava SE 11 = 55 (0x37 hex)\nJava SE 12 = 56 (0x38 hex)\nJava SE 13 = 57 (0x39 hex)\nJava SE 14 = 58 (0x3A hex)\nJava SE 15 = 59 (0x3B hex)\nJava SE 16 = 60 (0x3C hex)\nJava SE 17 = 61 (0x3D hex)\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | Do any of you know of a tool that will search for .class files and then display their compiled versions?
I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason). | Use the [javap](http://java.sun.com/javase/6/docs/technotes/tools/solaris/javap.html) tool that comes with the JDK. The `-verbose` option will print the version number of the class file.
```
> javap -verbose MyClass
Compiled from "MyClass.java"
public class MyClass
SourceFile: "MyClass.java"
minor version: 0
major version: 46
...
```
To only show the version:
```
WINDOWS> javap -verbose MyClass | find "version"
LINUX > javap -verbose MyClass | grep version
``` |
27,071 | <p>I have an old C library with a function that takes a void**:</p>
<pre><code>oldFunction(void** pStuff);
</code></pre>
<p>I'm trying to call this function from managed C++ (m_pStuff is a member of the parent ref class of type void*):</p>
<pre><code>oldFunction( static_cast<sqlite3**>( &m_pStuff ) );
</code></pre>
<p>This gives me the following error from Visual Studio:</p>
<blockquote>
<p>error C2440: 'static_cast' : cannot convert from 'cli::interior_ptr' to 'void **'</p>
</blockquote>
<p>I'm guessing the compiler is converting the void* member pointer to a cli::interior_ptr behind my back.</p>
<p>Any advice on how to do this?</p>
| [
{
"answer_id": 27326,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 2,
"selected": true,
"text": "<p>EDIT: Fixed answer, see below.</p>\n\n<p>Really you need to know what oldFunction is going to be doing with pStuff. If pStuff is a pointer to some unmanaged data you can try wrapping the definition of m_pStuff with:</p>\n\n<pre><code>#pragma unmanaged\n\nvoid* m_pStuff\n\n#pragma managed\n</code></pre>\n\n<p>This will make the pointer unmanaged which can then be passed into unmanaged functions. Of course you will not be able to assign any managed objects to this pointer directly. </p>\n\n<p>Fundamentally unmanaged and managed pointers are not the same and can't be converted without some sort of glue code that copies the underlying data. Basically managed pointers point to the managed heap and since this is garbage collected the actual memory address they point to can change over time. Unmanaged pointers do not change the memory address without you explicitly doing so. </p>\n\n<p>Scratch that, you can't define unmanaged / managed inside a class definition. But this test code seems to work just fine:</p>\n\n<pre><code>// TestSol.cpp : main project file.\n\n#include \"stdafx.h\"\n\nusing namespace System;\n\n#pragma unmanaged\n\nvoid oldFunction(void** pStuff)\n{\n return;\n}\n\n#pragma managed\n\nref class Test\n{\npublic:\n void* m_test;\n\n};\n\nint main(array<System::String ^> ^args)\n{\n Console::WriteLine(L\"Hello World\");\n\n Test^ test = gcnew Test();\n void* pStuff = test->m_test;\n oldFunction(&pStuff);\n test->m_test = pStuff;\n\n return 0;\n}\n</code></pre>\n\n<p>Here I copy the pointer out of the managed object first and then pass that in by to the oldFunction. Then I copy the result (probably updated by oldFunction) back into the managed object. Since the managed object is on the managed heap, the compiler won't let you pass a reference to the pointer contained in that object as it may move when the garbage collector runs.</p>\n"
},
{
"answer_id": 28695,
"author": "Danielb",
"author_id": 39040,
"author_profile": "https://Stackoverflow.com/users/39040",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for the advice, the pointer is to an C style abstract structure which I think if I leave that structure exposed to the managed code is going to cause further pain due to its lack of defined structure. So what I think I will do is wrap the C library in C++ and then wrap the C++ wrapper with managed C++, which will prevent exposing those C structures to managed code.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39040/"
] | I have an old C library with a function that takes a void\*\*:
```
oldFunction(void** pStuff);
```
I'm trying to call this function from managed C++ (m\_pStuff is a member of the parent ref class of type void\*):
```
oldFunction( static_cast<sqlite3**>( &m_pStuff ) );
```
This gives me the following error from Visual Studio:
>
> error C2440: 'static\_cast' : cannot convert from 'cli::interior\_ptr' to 'void \*\*'
>
>
>
I'm guessing the compiler is converting the void\* member pointer to a cli::interior\_ptr behind my back.
Any advice on how to do this? | EDIT: Fixed answer, see below.
Really you need to know what oldFunction is going to be doing with pStuff. If pStuff is a pointer to some unmanaged data you can try wrapping the definition of m\_pStuff with:
```
#pragma unmanaged
void* m_pStuff
#pragma managed
```
This will make the pointer unmanaged which can then be passed into unmanaged functions. Of course you will not be able to assign any managed objects to this pointer directly.
Fundamentally unmanaged and managed pointers are not the same and can't be converted without some sort of glue code that copies the underlying data. Basically managed pointers point to the managed heap and since this is garbage collected the actual memory address they point to can change over time. Unmanaged pointers do not change the memory address without you explicitly doing so.
Scratch that, you can't define unmanaged / managed inside a class definition. But this test code seems to work just fine:
```
// TestSol.cpp : main project file.
#include "stdafx.h"
using namespace System;
#pragma unmanaged
void oldFunction(void** pStuff)
{
return;
}
#pragma managed
ref class Test
{
public:
void* m_test;
};
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
Test^ test = gcnew Test();
void* pStuff = test->m_test;
oldFunction(&pStuff);
test->m_test = pStuff;
return 0;
}
```
Here I copy the pointer out of the managed object first and then pass that in by to the oldFunction. Then I copy the result (probably updated by oldFunction) back into the managed object. Since the managed object is on the managed heap, the compiler won't let you pass a reference to the pointer contained in that object as it may move when the garbage collector runs. |
27,077 | <p>When I do:</p>
<pre><code>$ find /
</code></pre>
<p>It searches the entire system.<br>
How do I prevent that?</p>
<p>(This question comes from an "<a href="https://stackoverflow.com/questions/18836/why-doesnt-find-find-anything#26182">answer</a>" to another question.)</p>
| [
{
"answer_id": 27080,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <strong>-prune</strong> option.</p>\n"
},
{
"answer_id": 27084,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "<p>You might be better off using wildcards. For instance, if you want to find all ksh scripts in the current directory:</p>\n\n<pre><code>$ ls *.ksh\n</code></pre>\n"
},
{
"answer_id": 27089,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 3,
"selected": false,
"text": "<p>Consider:</p>\n\n<pre><code>-maxdepth n\n True if the depth of the current file into the tree is less than\n or equal to n.\n\n-mindepth n\n True if the depth of the current file into the tree is greater\n than or equal to n.\n</code></pre>\n"
},
{
"answer_id": 27161,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 0,
"selected": false,
"text": "<p>You may even do</p>\n\n<pre><code>echo /specific/dir/*.jpg\n</code></pre>\n\n<p>as it's your shell that expands the wildcard. Typing</p>\n\n<pre><code>ls *.jpg\n</code></pre>\n\n<p>is equivalent to typing</p>\n\n<pre><code>ls foo.jpg bar.jpg\n</code></pre>\n\n<p>given foo.jpg and bar.jpg are all the files that end with \".jpg\" in the current directory.</p>\n"
},
{
"answer_id": 28262,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 3,
"selected": true,
"text": "<p>G'day,</p>\n\n<p>Just wanted to expand on the suggestion from Jon to use -prune. It isn't the easiest of find options to use, for example to just search in the current directory the find command looks like:</p>\n\n<pre><code>find . \\( -type d ! -name . -prune \\) -o \\( <the bit you want to look for> \\)\n</code></pre>\n\n<p>this will stop find from descending into sub-directories within this directory.</p>\n\n<p>Basically, it says, \"prune anything that is a directory, whose name isn't \".\", i.e. current dir.\"</p>\n\n<p>The find command evals left to right for each item found in the current directory so after completion of the first element, i.e. the prune segment, it will then continue on with the matched item in your second -o (OR'd) expression.</p>\n\n<p>HTH.</p>\n\n<p>cheers,\nRob</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] | When I do:
```
$ find /
```
It searches the entire system.
How do I prevent that?
(This question comes from an "[answer](https://stackoverflow.com/questions/18836/why-doesnt-find-find-anything#26182)" to another question.) | G'day,
Just wanted to expand on the suggestion from Jon to use -prune. It isn't the easiest of find options to use, for example to just search in the current directory the find command looks like:
```
find . \( -type d ! -name . -prune \) -o \( <the bit you want to look for> \)
```
this will stop find from descending into sub-directories within this directory.
Basically, it says, "prune anything that is a directory, whose name isn't ".", i.e. current dir."
The find command evals left to right for each item found in the current directory so after completion of the first element, i.e. the prune segment, it will then continue on with the matched item in your second -o (OR'd) expression.
HTH.
cheers,
Rob |
27,078 | <p>I am debugging my ASP.NET application on my Windows XP box with a virtual directory set up in IIS (5.1).</p>
<p>I am also running <strong>VirtualPC</strong> with XP and IE6 for testing purposes. When I connect to my real machine from the virtual machine, I enter the URL: <a href="http://machinename/projectname" rel="nofollow noreferrer">http://machinename/projectname</a>.</p>
<p>I get a security popup to connect to my machine (which I expect), but the User name field is disabled. I cannot change it from machinename\Guest to machinename\username in order to connect.</p>
<p>How do I get this to enable so I can enter the correct credentials.</p>
| [
{
"answer_id": 27080,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <strong>-prune</strong> option.</p>\n"
},
{
"answer_id": 27084,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "<p>You might be better off using wildcards. For instance, if you want to find all ksh scripts in the current directory:</p>\n\n<pre><code>$ ls *.ksh\n</code></pre>\n"
},
{
"answer_id": 27089,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 3,
"selected": false,
"text": "<p>Consider:</p>\n\n<pre><code>-maxdepth n\n True if the depth of the current file into the tree is less than\n or equal to n.\n\n-mindepth n\n True if the depth of the current file into the tree is greater\n than or equal to n.\n</code></pre>\n"
},
{
"answer_id": 27161,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 0,
"selected": false,
"text": "<p>You may even do</p>\n\n<pre><code>echo /specific/dir/*.jpg\n</code></pre>\n\n<p>as it's your shell that expands the wildcard. Typing</p>\n\n<pre><code>ls *.jpg\n</code></pre>\n\n<p>is equivalent to typing</p>\n\n<pre><code>ls foo.jpg bar.jpg\n</code></pre>\n\n<p>given foo.jpg and bar.jpg are all the files that end with \".jpg\" in the current directory.</p>\n"
},
{
"answer_id": 28262,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 3,
"selected": true,
"text": "<p>G'day,</p>\n\n<p>Just wanted to expand on the suggestion from Jon to use -prune. It isn't the easiest of find options to use, for example to just search in the current directory the find command looks like:</p>\n\n<pre><code>find . \\( -type d ! -name . -prune \\) -o \\( <the bit you want to look for> \\)\n</code></pre>\n\n<p>this will stop find from descending into sub-directories within this directory.</p>\n\n<p>Basically, it says, \"prune anything that is a directory, whose name isn't \".\", i.e. current dir.\"</p>\n\n<p>The find command evals left to right for each item found in the current directory so after completion of the first element, i.e. the prune segment, it will then continue on with the matched item in your second -o (OR'd) expression.</p>\n\n<p>HTH.</p>\n\n<p>cheers,\nRob</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417/"
] | I am debugging my ASP.NET application on my Windows XP box with a virtual directory set up in IIS (5.1).
I am also running **VirtualPC** with XP and IE6 for testing purposes. When I connect to my real machine from the virtual machine, I enter the URL: <http://machinename/projectname>.
I get a security popup to connect to my machine (which I expect), but the User name field is disabled. I cannot change it from machinename\Guest to machinename\username in order to connect.
How do I get this to enable so I can enter the correct credentials. | G'day,
Just wanted to expand on the suggestion from Jon to use -prune. It isn't the easiest of find options to use, for example to just search in the current directory the find command looks like:
```
find . \( -type d ! -name . -prune \) -o \( <the bit you want to look for> \)
```
this will stop find from descending into sub-directories within this directory.
Basically, it says, "prune anything that is a directory, whose name isn't ".", i.e. current dir."
The find command evals left to right for each item found in the current directory so after completion of the first element, i.e. the prune segment, it will then continue on with the matched item in your second -o (OR'd) expression.
HTH.
cheers,
Rob |
27,095 | <p>I did this Just for kicks (so, not exactly a question, i can see the downmodding happening already) but, in lieu of Google's newfound <a href="http://www.google.com/search?hl=en&q=1999999999999999-1999999999999995&btnG=Search" rel="nofollow noreferrer">inability</a> to do <a href="http://www.google.com/search?hl=en&q=400000000000002-400000000000001&btnG=Search" rel="nofollow noreferrer">math</a> <a href="http://www.google.com/search?hl=en&q=10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001-10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&btnG=Search" rel="nofollow noreferrer">correctly</a> (check it! according to google 500,000,000,000,002 - 500,000,000,000,001 = 0), i figured i'd try the following in C to run a little theory.</p>
<pre><code>int main()
{
char* a = "399999999999999";
char* b = "399999999999998";
float da = atof(a);
float db = atof(b);
printf("%s - %s = %f\n", a, b, da-db);
a = "500000000000002";
b = "500000000000001";
da = atof(a);
db = atof(b);
printf("%s - %s = %f\n", a, b, da-db);
}
</code></pre>
<p>When you run this program, you get the following</p>
<pre><code> 399999999999999 - 399999999999998 = 0.000000
500000000000002 - 500000000000001 = 0.000000
</code></pre>
<p>It would seem like Google is using simple 32 bit floating precision (the error here), if you switch float for double in the above code, you fix the issue! Could this be it?</p>
<p>/mp</p>
| [
{
"answer_id": 27105,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<p>For more of this kind of silliness see this nice article pertaining to Windows calculator.</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2004/05/25/141253.aspx\" rel=\"nofollow noreferrer\">When you change the insides, nobody notices</a></p>\n\n<blockquote>\n <p>The innards of Calc - the arithmetic\n engine - was completely thrown away\n and rewritten from scratch. The\n standard IEEE floating point library\n was replaced with an\n arbitrary-precision arithmetic\n library. This was done after people\n kept writing ha-ha articles about how\n Calc couldn't do decimal arithmetic\n correctly, that for example computing\n 10.21 - 10.2 resulted in 0.0100000000000016.</p>\n</blockquote>\n"
},
{
"answer_id": 27545,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>It would seem like Google is using simple 32 bit floating precision (the error here), if you switch float for double in the above code, you fix the issue! Could this be it?</p>\n</blockquote>\n\n<p>No, you just defer the issue. doubles still exhibit the same issue, just with larger numbers.</p>\n"
},
{
"answer_id": 27552,
"author": "gil",
"author_id": 195,
"author_profile": "https://Stackoverflow.com/users/195",
"pm_score": 3,
"selected": true,
"text": "<p>in C#, try (double.maxvalue == (double.maxvalue - 100)) , you'll get true ...</p>\n\n<p>but thats what it is supposed to be:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems</a> </p>\n\n<p>thinking about it, you have 64 bit representing a number greater than 2^64 (double.maxvalue), so inaccuracy is expected. </p>\n"
},
{
"answer_id": 28443,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>@ebel</p>\n\n<blockquote>\n <p>thinking about it, you have 64 bit representing a number greater than 2^64 (double.maxvalue), so inaccuracy is expected. </p>\n</blockquote>\n\n<p>2^64 is not the maximum value of a double. 2^64 is the number of unique values that a double (or any other 64-bit type) can hold. <code>Double.MaxValue</code> is equal to 1.79769313486232e308.</p>\n\n<p>Inaccuracy with floating point numbers doesn't come from representing values larger than <code>Double.MaxValue</code> (which is impossible, excluding <code>Double.PositiveInfinity</code>). It comes from the fact that the desired range of values is simply too large to fit into the datatype. So we give up precision in exchange for a larger effective range. In essense, we are dropping significant digits in return for a larger exponent range.</p>\n\n<p>@DrPizza</p>\n\n<blockquote>\n <p>Not even; the IEEE encodings use multiple encodings for the same values. Specifically, NaN is represented by an exponent of all-bits-1, and then any non-zero value for the mantissa. As such, there are 252 NaNs for doubles, 223 NaNs for singles.</p>\n</blockquote>\n\n<p>True. I didn't account for duplicate encodings. There are actually 2<sup>52</sup>-1 NaNs for doubles and 2<sup>23</sup>-1 NaNs for singles, though. :p</p>\n"
},
{
"answer_id": 28625,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>2^64 is not the maximum value of a double. 2^64 is the number of unique values that a double (or any other 64-bit type) can hold. Double.MaxValue is equal to 1.79769313486232e308.</p>\n</blockquote>\n\n<p>Not even; the IEEE encodings use multiple encodings for the same values. Specifically, NaN is represented by an exponent of all-bits-1, and then <em>any</em> non-zero value for the mantissa. As such, there are 2<sup>52</sup> NaNs for doubles, 2<sup>23</sup> NaNs for singles.</p>\n"
},
{
"answer_id": 29039,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>True. I didn't account for duplicate encodings. There are actually 252-1 NaNs for doubles and 223-1 NaNs for singles, though. :p</p>\n</blockquote>\n\n<p>Doh, forgot to subtract the infinities.</p>\n"
},
{
"answer_id": 60138,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "<p>The rough estimate version of this issue that I learned is that 32-bit floats give you 5 digits of precision and 64-bit floats give you 15 digits of precision. This will of course vary depending on how the floats are encoded, but it's a pretty good starting point. </p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/27095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] | I did this Just for kicks (so, not exactly a question, i can see the downmodding happening already) but, in lieu of Google's newfound [inability](http://www.google.com/search?hl=en&q=1999999999999999-1999999999999995&btnG=Search) to do [math](http://www.google.com/search?hl=en&q=400000000000002-400000000000001&btnG=Search) [correctly](http://www.google.com/search?hl=en&q=10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001-10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&btnG=Search) (check it! according to google 500,000,000,000,002 - 500,000,000,000,001 = 0), i figured i'd try the following in C to run a little theory.
```
int main()
{
char* a = "399999999999999";
char* b = "399999999999998";
float da = atof(a);
float db = atof(b);
printf("%s - %s = %f\n", a, b, da-db);
a = "500000000000002";
b = "500000000000001";
da = atof(a);
db = atof(b);
printf("%s - %s = %f\n", a, b, da-db);
}
```
When you run this program, you get the following
```
399999999999999 - 399999999999998 = 0.000000
500000000000002 - 500000000000001 = 0.000000
```
It would seem like Google is using simple 32 bit floating precision (the error here), if you switch float for double in the above code, you fix the issue! Could this be it?
/mp | in C#, try (double.maxvalue == (double.maxvalue - 100)) , you'll get true ...
but thats what it is supposed to be:
<http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems>
thinking about it, you have 64 bit representing a number greater than 2^64 (double.maxvalue), so inaccuracy is expected. |
27,219 | <p>Given a select with multiple option's in jQuery. </p>
<pre><code>$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
.append("<option>John</option>") //Key = 32
.append("<option>Paul</option>") //Key = 423
</code></pre>
<p>How should the key be stored and retrieved?</p>
<p>The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).</p>
<p>Thanks</p>
<p>and in the spirit of TMTOWTDI.</p>
<pre><code>$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
$(this).append($("<option/>").val(value).text(text));
};
$select.append($option.val(1).text("Jason").clone())
.append("<option value=32>John</option>")
.append($("<option/>").val(423).text("Paul"))
.addOption("321","Lenny");
</code></pre>
| [
{
"answer_id": 27231,
"author": "Lucas Wilson-Richter",
"author_id": 1157,
"author_profile": "https://Stackoverflow.com/users/1157",
"pm_score": 3,
"selected": false,
"text": "<p>The HTML <code><option></code> tag has an attribute called \"value\", where you can store your key.</p>\n\n<p>e.g.:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><option value=1>Jason</option>\n</code></pre>\n\n<p>I don't know how this will play with jQuery (I don't use it), but I hope this is helpful nonetheless.</p>\n"
},
{
"answer_id": 27259,
"author": "Juan",
"author_id": 550,
"author_profile": "https://Stackoverflow.com/users/550",
"pm_score": 5,
"selected": true,
"text": "<p>Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ):</p>\n\n<pre><code>$select = $('<select id=\"mySelect\"></select>');\n$select.append('<option value=\"1\">Jason</option>') //Key = 1\n .append('<option value=\"32\">John</option>') //Key = 32\n .append('<option value=\"423\">Paul</option>') //Key = 423\n</code></pre>\n\n<p>jQuery lets you get the value using the val() method. Using it on the select tag you get the current selected option's value.</p>\n\n<pre><code>$( '#mySelect' ).val(); //Gets the value for the current selected option\n\n$( '#mySelect > option' ).each( function( index, option ) {\n option.val(); //The value for each individual option\n} );\n</code></pre>\n\n<p>Just in case, the .each method loops throught every element the query matched.</p>\n"
},
{
"answer_id": 27281,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using HTML5, you can use a <a href=\"http://ejohn.org/blog/html-5-data-attributes/\" rel=\"nofollow noreferrer\">custom data attribute</a>. It would look like this:</p>\n\n<pre><code>$select = $(\"<select></select>\");\n$select.append(\"<option data-key=\\\"1\\\">Jason</option>\") //Key = 1\n .append(\"<option data-key=\\\"32\\\">John</option>\") //Key = 32\n .append(\"<option data-key=\\\"423\\\">Paul</option>\") //Key = 423\n</code></pre>\n\n<p>Then to get the selected key you could do:</p>\n\n<pre><code>var key = $('select option:selected').attr('data-key');\n</code></pre>\n\n<p>Or if you are using XHTML, then you can create a custom namespace.</p>\n\n<p>Since you say the keys can repeat, using the value attribute is probably not an option since then you wouldn't be able to tell which of the different options with the same value was selected on the form post.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293/"
] | Given a select with multiple option's in jQuery.
```
$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
.append("<option>John</option>") //Key = 32
.append("<option>Paul</option>") //Key = 423
```
How should the key be stored and retrieved?
The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).
Thanks
and in the spirit of TMTOWTDI.
```
$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
$(this).append($("<option/>").val(value).text(text));
};
$select.append($option.val(1).text("Jason").clone())
.append("<option value=32>John</option>")
.append($("<option/>").val(423).text("Paul"))
.addOption("321","Lenny");
``` | Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ):
```
$select = $('<select id="mySelect"></select>');
$select.append('<option value="1">Jason</option>') //Key = 1
.append('<option value="32">John</option>') //Key = 32
.append('<option value="423">Paul</option>') //Key = 423
```
jQuery lets you get the value using the val() method. Using it on the select tag you get the current selected option's value.
```
$( '#mySelect' ).val(); //Gets the value for the current selected option
$( '#mySelect > option' ).each( function( index, option ) {
option.val(); //The value for each individual option
} );
```
Just in case, the .each method loops throught every element the query matched. |
27,220 | <p>I'm looking for a method, or a code snippet for converting std::string to LPCWSTR</p>
| [
{
"answer_id": 27291,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 4,
"selected": false,
"text": "<p>If you are in an ATL/MFC environment, You can use the ATL conversion macro:</p>\n\n<pre><code>#include <atlbase.h>\n#include <atlconv.h>\n\n. . .\n\nstring myStr(\"My string\");\nCA2W unicodeStr(myStr);\n</code></pre>\n\n<p>You can then use unicodeStr as an LPCWSTR. The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.</p>\n"
},
{
"answer_id": 4139684,
"author": "Benny Hilfiger",
"author_id": 502542,
"author_profile": "https://Stackoverflow.com/users/502542",
"pm_score": 7,
"selected": false,
"text": "<p>The solution is actually a lot easier than any of the other suggestions:</p>\n<pre><code>std::wstring stemp = std::wstring(s.begin(), s.end());\nLPCWSTR sw = stemp.c_str();\n</code></pre>\n<p>Best of all, it's platform independent.</p>\n"
},
{
"answer_id": 64532484,
"author": "Ashi",
"author_id": 592651,
"author_profile": "https://Stackoverflow.com/users/592651",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer using standard converters:</p>\n<pre><code>#include <codecvt>\n\nstd::string s = "Hi";\nstd::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;\nstd::wstring wide = converter.from_bytes(s);\nLPCWSTR result = wide.c_str();\n</code></pre>\n<p>Please find more details in this answer: <a href=\"https://stackoverflow.com/a/18597384/592651\">https://stackoverflow.com/a/18597384/592651</a></p>\n<hr />\n<p>Update 12/21/2020 : My answer was commented on by @Andreas H . I thought his comment is valuable, so I updated my answer accordingly:</p>\n<blockquote>\n<ol>\n<li><code>codecvt_utf8_utf16</code> is deprecated in C++17.</li>\n<li>Also the code implies that source encoding is UTF-8 which it usually isn't.</li>\n<li>In C++20 there is a separate type std::u8string for UTF-8 because of that.</li>\n</ol>\n</blockquote>\n<p>But it worked for me because I am still using an old version of C++ and it happened that my source encoding was UTF-8 .</p>\n"
},
{
"answer_id": 66507740,
"author": "Top-Master",
"author_id": 8740349,
"author_profile": "https://Stackoverflow.com/users/8740349",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>After knowing that, the C++11-standard has rules for <code>.c_str()</code> method (maybe <code>.data()</code> too), which allows us to use <code>const_cast</code>,</li>\n</ul>\n<blockquote>\n<p>(I mean, normally using <code>const_cast</code> may be dangerous)</p>\n</blockquote>\n<ul>\n<li>we can safely take "<code>const</code>" input parameter.</li>\n<li>Then finally, use "<code>const_cast</code>" instead of any unnecessary allocation and deletion.</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::wstring s2ws(const std::string &s, bool isUtf8 = true)\n{\n int len;\n int slength = (int)s.length() + 1;\n len = MultiByteToWideChar(isUtf8 ? CP_UTF8 : CP_ACP, 0, s.c_str(), slength, 0, 0);\n std::wstring buf;\n buf.resize(len);\n MultiByteToWideChar(isUtf8 ? CP_UTF8 : CP_ACP, 0, s.c_str(), slength,\n const_cast<wchar_t *>(buf.c_str()), len);\n return buf;\n}\n\nstd::wstring wrapper = s2ws(u8"My UTF8 string!");\nLPCWSTR result = wrapper.c_str();\n</code></pre>\n<blockquote>\n<p><strong>Note</strong> that we should use <code>CP_UTF8</code> for C++'s string-literal, but in some cases you may need to instead use <code>CP_ACP</code> (by setting second parameter to <code>false</code>).</p>\n</blockquote>\n"
},
{
"answer_id": 67597861,
"author": "Sabbir Pulak",
"author_id": 7134879,
"author_profile": "https://Stackoverflow.com/users/7134879",
"pm_score": -1,
"selected": false,
"text": "<p>It's so easy, no need to apply any custom method. Try with this:</p>\n<pre><code>string s = "So Easy Bro"\nLPCWSTR wide_string;\n\nwide_string = CA2T(s.c_str());\n</code></pre>\n<p>I think, it will works.</p>\n"
},
{
"answer_id": 68465921,
"author": "Ryan",
"author_id": 16493633,
"author_profile": "https://Stackoverflow.com/users/16493633",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using QT then you can convert to QString and then myqstring.toStdWString() will do the trick.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
] | I'm looking for a method, or a code snippet for converting std::string to LPCWSTR | The solution is actually a lot easier than any of the other suggestions:
```
std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();
```
Best of all, it's platform independent. |
27,222 | <p>I am looking for good methods of manipulating HTML in PHP. For example, the problem I currently have is dealing with malformed HTML.</p>
<p>I am getting input that looks something like this:</p>
<pre><code><div>This is some <b>text
</code></pre>
<p>As you noticed, the HTML is missing closing tags. I could use regex or an XML Parser to solve this problem. However, it is likely that I will have to do other DOM manipulation in the future. I wonder if there are any good PHP libraries that handle DOM manipulation similar to how Javascript deals with DOM manipulation.</p>
| [
{
"answer_id": 27236,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 5,
"selected": true,
"text": "<p>PHP has <a href=\"http://php.net/tidy\" rel=\"noreferrer\">a PECL extension that gives you access to the features of HTML Tidy</a>. Tidy is a pretty powerful library that should be able to take code like that and close tags in an intelligent manner.</p>\n\n<p>I use it to clean up malformed XML and HTML sent to me by a classified ad system prior to import.</p>\n"
},
{
"answer_id": 27284,
"author": "Juan",
"author_id": 550,
"author_profile": "https://Stackoverflow.com/users/550",
"pm_score": 1,
"selected": false,
"text": "<p>For manipulating the DOM i think that what you're looking for is <a href=\"http://www.php.net/manual/en/intro.dom.php\" rel=\"nofollow noreferrer\">this</a>. I've used to parse HTML documents from the web and it worked fine for me.</p>\n"
},
{
"answer_id": 503956,
"author": "bedlam",
"author_id": 45630,
"author_profile": "https://Stackoverflow.com/users/45630",
"pm_score": 3,
"selected": false,
"text": "<p>I've found PHP Simple HTML DOM to be the most useful and straight forward library yet. Better than PECL I would say.</p>\n\n<p>I've written an article on <a href=\"http://www.crainbandy.com/programming/using-php-and-simple-html-dom-parser-to-scrape-artist-tour-dates-off-myspace\" rel=\"noreferrer\">how to use it to scrape myspace artist tour dates</a> (just an example.) Here's a link to the <a href=\"http://simplehtmldom.sourceforge.net/\" rel=\"noreferrer\">php simple html dom parser.</a> </p>\n"
},
{
"answer_id": 4303405,
"author": "Decko",
"author_id": 320702,
"author_profile": "https://Stackoverflow.com/users/320702",
"pm_score": 2,
"selected": false,
"text": "<p>The DOM library which is now built-in can solve this problem easily. The loadHTML method will accept malformed XML while the load method will not.</p>\n\n<pre><code>$d = new DOMDocument;\n$d->loadHTML('<div>This is some <b>text');\n$d->saveHTML();\n</code></pre>\n\n<p>The output will be:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html>\n <body>\n <div>This is some <b>text</b></div>\n </body>\n</html>\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | I am looking for good methods of manipulating HTML in PHP. For example, the problem I currently have is dealing with malformed HTML.
I am getting input that looks something like this:
```
<div>This is some <b>text
```
As you noticed, the HTML is missing closing tags. I could use regex or an XML Parser to solve this problem. However, it is likely that I will have to do other DOM manipulation in the future. I wonder if there are any good PHP libraries that handle DOM manipulation similar to how Javascript deals with DOM manipulation. | PHP has [a PECL extension that gives you access to the features of HTML Tidy](http://php.net/tidy). Tidy is a pretty powerful library that should be able to take code like that and close tags in an intelligent manner.
I use it to clean up malformed XML and HTML sent to me by a classified ad system prior to import. |
27,240 | <p>In Java 5 and above you have the foreach loop, which works magically on anything that implements <code>Iterable</code>:</p>
<pre><code>for (Object o : list) {
doStuff(o);
}
</code></pre>
<p>However, <code>Enumerable</code> still does not implement <code>Iterable</code>, meaning that to iterate over an <code>Enumeration</code> you must do the following:</p>
<pre><code>for(; e.hasMoreElements() ;) {
doStuff(e.nextElement());
}
</code></pre>
<p>Does anyone know if there is a reason why <code>Enumeration</code> still does not implement <code>Iterable</code>?</p>
<p><strong>Edit:</strong> As a clarification, I'm not talking about the language concept of an <a href="http://en.wikipedia.org/wiki/Enumerated_type" rel="noreferrer">enum</a>, I'm talking a Java-specific class in the Java API called '<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Enumeration.html" rel="noreferrer">Enumeration</a>'. </p>
| [
{
"answer_id": 27389,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 6,
"selected": true,
"text": "<p>Enumeration hasn't been modified to support Iterable because it's an interface not a concrete class (like Vector, which was modifed to support the Collections interface).</p>\n\n<p>If Enumeration was changed to support Iterable it would break a bunch of people's code.</p>\n"
},
{
"answer_id": 27441,
"author": "dlinsin",
"author_id": 198,
"author_profile": "https://Stackoverflow.com/users/198",
"pm_score": 3,
"selected": false,
"text": "<p>AFAIK Enumeration is <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Iterator.html\" rel=\"noreferrer\">kinda \"deprecated\"</a>:</p>\n\n<blockquote>\n <p>Iterator takes the place of\n Enumeration in the Java collections\n framework</p>\n</blockquote>\n\n<p>I hope they'll change the Servlet API with JSR 315 to use Iterator instead of Enumeration. </p>\n"
},
{
"answer_id": 38518,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": false,
"text": "<p>It doesn't make sense for <code>Enumeration</code> to implement <code>Iterable</code>. <code>Iterable</code> is a factory method for <code>Iterator</code>. <code>Enumeration</code> is analogous to <code>Iterator</code>, and only maintains state for a single enumeration.</p>\n\n<p>So, be careful trying to wrap an <code>Enumeration</code> as an <code>Iterable</code>. If someone passes me an <code>Iterable</code>, I will assume that I can call <code>iterator()</code> on it repeatedly, creating as many <code>Iterator</code> instances as I want, and iterating independently on each. A wrapped <code>Enumeration</code> will not fulfill this contract; don't let your wrapped <code>Enumeration</code> escape from your own code. (As an aside, I noticed that Java 7's <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html\" rel=\"noreferrer\"><code>DirectoryStream</code></a> violates expectations in just this way, and shouldn't be allowed to \"escape\" either.)</p>\n\n<p><code>Enumeration</code> is like an <code>Iterator</code>, not an <code>Iterable</code>. A <code>Collection</code> is <code>Iterable</code>. An <code>Iterator</code> is not.</p>\n\n<p>You can't do this:</p>\n\n<pre><code>Vector<X> list = …\nIterator<X> i = list.iterator();\nfor (X x : i) {\n x.doStuff();\n}\n</code></pre>\n\n<p>So it wouldn't make sense to do this:</p>\n\n<pre><code>Vector<X> list = …\nEnumeration<X> i = list.enumeration();\nfor (X x : i) {\n x.doStuff();\n}\n</code></pre>\n\n<p>There is no <code>Enumerable</code> equivalent to <code>Iterable</code>. It could be added without breaking anything to work in for loops, but what would be the point? If you are able to implement this new <code>Enumerable</code> interface, why not just implement <code>Iterable</code> instead?</p>\n"
},
{
"answer_id": 46674,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": false,
"text": "<p>As an easy and <strong>clean</strong> way of using an Enumeration with the enhanced for loop, convert to an ArrayList with java.util.Collections.list.</p>\n\n<pre><code>for (TableColumn col : Collections.list(columnModel.getColumns()) {\n</code></pre>\n\n<p>(javax.swing.table.TableColumnModel.getColumns returns Enumeration.)</p>\n\n<p>Note, this may be very slightly less efficient.</p>\n"
},
{
"answer_id": 31172283,
"author": "user5071455",
"author_id": 5071455,
"author_profile": "https://Stackoverflow.com/users/5071455",
"pm_score": 2,
"selected": false,
"text": "<p>If you would just like it to be syntactically a little cleaner, you can use:</p>\n\n<pre><code>while(e.hasMoreElements()) {\n doStuff(e.nextElement());\n}\n</code></pre>\n"
},
{
"answer_id": 72718011,
"author": "Clement Cherlin",
"author_id": 4455546,
"author_profile": "https://Stackoverflow.com/users/4455546",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible to create an Iterable from any object with a method that returns an Enumeration, using a lambda as an adapter. In Java 8, use Guava's static <a href=\"https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/collect/Iterators.html#forEnumeration(java.util.Enumeration)\" rel=\"nofollow noreferrer\"><code>Iterators.forEnumeration</code></a> method, and in Java 9+ use the Enumeration instance method <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Enumeration.html#asIterator--\" rel=\"nofollow noreferrer\"><code>asIterator</code></a>.</p>\n<p>Consider the Servlet API's <code>HttpSession.getAttributeNames()</code>, which returns an <code>Enumeration<String></code> rather than an <code>Iterator<String></code>.</p>\n<p><strong>Java 8 using Guava</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Iterable<String> iterable = () -> Iterators.forEnumeration(session.getAttributeNames());\n</code></pre>\n<p><strong>Java 9+</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Iterable<String> iterable = () -> session.getAttributeNames().asIterator();\n</code></pre>\n<p>Note that these lambdas are truly Iterable; they return a fresh Iterator each time they are invoked. You can use them exactly like any other Iterable in an enhanced <code>for</code> loop, <code>StreamSupport.stream(iterable.spliterator(), false)</code>, and <code>iterable.forEach()</code>.</p>\n<p>The same trick works on classes that provide an Iterator but don't implement Iterable. <code>Iterable<Something> iterable = notIterable::createIterator;</code></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | In Java 5 and above you have the foreach loop, which works magically on anything that implements `Iterable`:
```
for (Object o : list) {
doStuff(o);
}
```
However, `Enumerable` still does not implement `Iterable`, meaning that to iterate over an `Enumeration` you must do the following:
```
for(; e.hasMoreElements() ;) {
doStuff(e.nextElement());
}
```
Does anyone know if there is a reason why `Enumeration` still does not implement `Iterable`?
**Edit:** As a clarification, I'm not talking about the language concept of an [enum](http://en.wikipedia.org/wiki/Enumerated_type), I'm talking a Java-specific class in the Java API called '[Enumeration](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Enumeration.html)'. | Enumeration hasn't been modified to support Iterable because it's an interface not a concrete class (like Vector, which was modifed to support the Collections interface).
If Enumeration was changed to support Iterable it would break a bunch of people's code. |
27,258 | <p>I'm about to start a fairly Ajax heavy feature in my company's application. What I need to do is make an Ajax callback every few minutes a user has been on the page. </p>
<ul>
<li>I don't need to do any DOM updates before, after, or during the callbacks. </li>
<li>I don't need any information from the page, just from a site cookie which should always be sent with requests anyway, and an ID value.</li>
</ul>
<p>What I'm curious to find out, is if there is any clean and simple way to make a JavaScript Ajax callback to an ASP.NET page without posting back the rest of the information on the page. I'd like to not have to do this if it is possible.</p>
<p>I really just want to be able to call a single method on the page, nothing else.</p>
<p>Also, I'm restricted to ASP.NET 2.0 so I can't use any of the new 3.5 framework ASP AJAX features, although I can use the ASP AJAX extensions for the 2.0 framework.</p>
<p><strong>UPDATE</strong><br>
I've decided to accept <a href="https://stackoverflow.com/questions/27258/aspnet-javascript-callbacks-without-full-postbacks#27270">DanP</a>'s answer as it seems to be exactly what I'm looking for. Our site already uses jQuery for some things so I'll probably use jQuery for making requests since in my experience it seems to perform much better than ASP's AJAX framework does. </p>
<p>What do you think would be the best method of transferring data to the IHttpHandler? Should I add variables to the query string or POST the data I need to send?</p>
<p>The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly or repeating requests. Is this possible?</p>
| [
{
"answer_id": 27264,
"author": "abigblackman",
"author_id": 2279,
"author_profile": "https://Stackoverflow.com/users/2279",
"pm_score": 2,
"selected": false,
"text": "<p>You are not just restricted to ASP.NET AJAX but can use any 3rd party library like jQuery, YUI etc to do the same thing. You can then just make a request to a blank page on your site which should return the headers that contain the cookies. </p>\n"
},
{
"answer_id": 27270,
"author": "Daniel Pollard",
"author_id": 2758,
"author_profile": "https://Stackoverflow.com/users/2758",
"pm_score": 4,
"selected": true,
"text": "<p>If you don't want to create a blank page, you could call a IHttpHandler (ashx) file:</p>\n\n<pre><code>public class RSSHandler : IHttpHandler\n {\n public void ProcessRequest (HttpContext context)\n { \n context.Response.ContentType = \"text/xml\";\n\n string sXml = BuildXMLString(); //not showing this function, \n //but it creates the XML string\n context.Response.Write( sXml );\n }\n\n public bool IsReusable\n {\n get { return true; }\n }\n\n }\n</code></pre>\n"
},
{
"answer_id": 27275,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": -1,
"selected": false,
"text": "<p>You can also use WebMethods which are built into the asp.net ajax library. You simply create a static method on the page's codebehind and call that from your Ajax.</p>\n<p>There's a pretty basic example of how to do it <a href=\"https://web.archive.org/web/20200803212711/http://geekswithblogs.net/frankw/archive/2008/03/13/asp.net-ajax-callbacks-to-web-methods-in-aspx-pages.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 27278,
"author": "Jim",
"author_id": 1208,
"author_profile": "https://Stackoverflow.com/users/1208",
"pm_score": -1,
"selected": false,
"text": "<p>You should use a web service (.asmx). With Microsoft's ASP.NET AJAX you can even auto-generate the stubs.</p>\n"
},
{
"answer_id": 27295,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 2,
"selected": false,
"text": "<p>You should use ASP.Net Callbacks which were introduced in Asp.Net 2.0. Here is an article that should get you set to go:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms178208.aspx\" rel=\"nofollow noreferrer\">Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages</a></p>\n\n<p>Edit: Also look at this:\n<a href=\"http://aspalliance.com/1537\" rel=\"nofollow noreferrer\">ICallback & JSON Based JavaScript Serialization</a></p>\n"
},
{
"answer_id": 27312,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>My vote is with the HTTPHandler suggestion as well. I utilize this often. Because it does not invoke an instance of the page class, it is very lightweight. </p>\n\n<p>All of the ASP.NET AJAX framework tricks actually instantiate and create the entire page again on the backend per call, so they are huge resource hogs.</p>\n\n<p>Hence, my typical style of XmlHttpRequest back to a HttpHandler.</p>\n"
},
{
"answer_id": 27340,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>What do you think would be the best method of transferring data to the IHttpHandler? Should I added variables to the query string or POST the data I need to send? The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly</p>\n</blockquote>\n\n<p>Considering the callback is buried in the client code, it would take someone with equal determination to get either the querystring or the POST request. IE, if they have firebug, your equally screwed.</p>\n\n<p>So, in that case, do whatever is easiest to you (Hint: I'd just use the querystring).</p>\n\n<p>To handle repeating requests/direct access, I'd generate a key that is sent with each request. Perhaps a hash of the current time (Fuzzy, I'd go down to minutes, but not seconds due to network latency) + the client IP.</p>\n\n<p>Then in the HTTPHandler, perform the same hash, and only run if they match.</p>\n"
},
{
"answer_id": 28105,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "<p>Since you are using only ASP.NET 2.0 I would recommend <a href=\"http://www.ajaxpro.info/\" rel=\"nofollow noreferrer\">AjaxPro</a> will which create the .ashx file. All you have to do is to pull the AjaxPro.dll into your web site. I developed an entire application with <a href=\"http://www.ajaxpro.info/\" rel=\"nofollow noreferrer\">AjaxPro</a> and found it worked very well. It uses serialization to pass objects back and forth.</p>\n\n<p>This is just a sample on how to simply use it.</p>\n\n<pre><code>namespace MyDemo\n{\n public class Default\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n AjaxPro.Utility.RegisterTypeForAjax(typeof(Default));\n }\n\n [AjaxPro.AjaxMethod]\n public DateTime GetServerTime()\n {\n return DateTime.Now;\n }\n }\n}\n</code></pre>\n\n<p>To call it via JavaScript it is as simple as </p>\n\n<pre><code>function getServerTime()\n{\n MyDemo._Default.GetServerTime(getServerTime_callback); // asynchronous call\n}\n\n// This method will be called after the method has been executed\n// and the result has been sent to the client.\n\nfunction getServerTime_callback(res)\n{\n alert(res.value);\n}\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>You also have to add </p>\n\n<p>\n \n</p>\n\n<p>To the config. AjaxPro also works well side by side with APS.NET Ajax and you can pass C# objects from Client to Sever if the class is marked as [Serializable]</p>\n"
},
{
"answer_id": 1958357,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 1,
"selected": false,
"text": "<p>Just to offer a different perspective, you could also use a PageMethod on your main page. Dave Ward has a nice post that <a href=\"http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/\" rel=\"nofollow noreferrer\">illustrates</a> this. Essentially you use jQuery ajax post to call the method, as illustrated in Dave's post:</p>\n\n<pre><code>$.ajax({\n type: \"POST\",\n url: \"Default.aspx/GetFeedburnerItems\",\n // Pass the \"Count\" parameter, via JSON object.\n data: \"{'Count':'7'}\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function(msg) {\n BuildTable(msg.d);\n }\n });\n</code></pre>\n\n<p>No need for Asp.Net Ajax extensions at all.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | I'm about to start a fairly Ajax heavy feature in my company's application. What I need to do is make an Ajax callback every few minutes a user has been on the page.
* I don't need to do any DOM updates before, after, or during the callbacks.
* I don't need any information from the page, just from a site cookie which should always be sent with requests anyway, and an ID value.
What I'm curious to find out, is if there is any clean and simple way to make a JavaScript Ajax callback to an ASP.NET page without posting back the rest of the information on the page. I'd like to not have to do this if it is possible.
I really just want to be able to call a single method on the page, nothing else.
Also, I'm restricted to ASP.NET 2.0 so I can't use any of the new 3.5 framework ASP AJAX features, although I can use the ASP AJAX extensions for the 2.0 framework.
**UPDATE**
I've decided to accept [DanP](https://stackoverflow.com/questions/27258/aspnet-javascript-callbacks-without-full-postbacks#27270)'s answer as it seems to be exactly what I'm looking for. Our site already uses jQuery for some things so I'll probably use jQuery for making requests since in my experience it seems to perform much better than ASP's AJAX framework does.
What do you think would be the best method of transferring data to the IHttpHandler? Should I add variables to the query string or POST the data I need to send?
The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly or repeating requests. Is this possible? | If you don't want to create a blank page, you could call a IHttpHandler (ashx) file:
```
public class RSSHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/xml";
string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string
context.Response.Write( sXml );
}
public bool IsReusable
{
get { return true; }
}
}
``` |
27,294 | <p>I'm working on an internal project for my company, and part of the project is to be able to parse various "Tasks" from an XML file into a collection of tasks to be ran later.</p>
<p>Because each type of Task has a multitude of different associated fields, I decided it would be best to represent each type of Task with a seperate class.</p>
<p>To do this, I constructed an abstract base class:</p>
<pre><code>public abstract class Task
{
public enum TaskType
{
// Types of Tasks
}
public abstract TaskType Type
{
get;
}
public abstract LoadFromXml(XmlElement task);
public abstract XmlElement CreateXml(XmlDocument currentDoc);
}
</code></pre>
<p>Each task inherited from this base class, and included the code necessary to create itself from the passed in XmlElement, as well as serialize itself back out to an XmlElement.</p>
<p>A basic example:</p>
<pre><code>public class MergeTask : Task
{
public override TaskType Type
{
get { return TaskType.Merge; }
}
// Lots of Properties / Methods for this Task
public MergeTask (XmlElement elem)
{
this.LoadFromXml(elem);
}
public override LoadFromXml(XmlElement task)
{
// Populates this Task from the Xml.
}
public override XmlElement CreateXml(XmlDocument currentDoc)
{
// Serializes this class back to xml.
}
}
</code></pre>
<p>The parser would then use code similar to this to create a task collection:</p>
<pre><code>XmlNode taskNode = parent.SelectNode("tasks");
TaskFactory tf = new TaskFactory();
foreach (XmlNode task in taskNode.ChildNodes)
{
// Since XmlComments etc will show up
if (task is XmlElement)
{
tasks.Add(tf.CreateTask(task as XmlElement));
}
}
</code></pre>
<p>All of this works wonderfully, and allows me to pass tasks around using the base class, while retaining the structure of having individual classes for each task.</p>
<p>However, I am not happy with my code for TaskFactory.CreateTask. This method accepts an XmlElement, and then returns an instance of the appropriate Task class:</p>
<pre><code>public Task CreateTask(XmlElement elem)
{
if (elem != null)
{
switch(elem.Name)
{
case "merge":
return new MergeTask(elem);
default:
throw new ArgumentException("Invalid Task");
}
}
}
</code></pre>
<p>Because I have to parse the XMLElement, I'm using a huge (10-15 cases in the real code) switch to pick which child class to instantiate. I'm hoping there is some sort of polymorphic trick I can do here to clean up this method.</p>
<p>Any advice?</p>
| [
{
"answer_id": 27310,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 5,
"selected": true,
"text": "<p>I use reflection to do this.\nYou can make a factory that basically expands without you having to add any extra code.</p>\n\n<p>make sure you have \"using System.Reflection\", place the following code in your instantiation method.</p>\n\n<pre><code>public Task CreateTask(XmlElement elem)\n{\n if (elem != null)\n { \n try\n {\n Assembly a = typeof(Task).Assembly\n string type = string.Format(\"{0}.{1}Task\",typeof(Task).Namespace,elem.Name);\n\n //this is only here, so that if that type doesn't exist, this method\n //throws an exception\n Type t = a.GetType(type, true, true);\n\n return a.CreateInstance(type, true) as Task;\n }\n catch(System.Exception)\n {\n throw new ArgumentException(\"Invalid Task\");\n }\n }\n}\n</code></pre>\n\n<p>Another observation, is that you can make this method, a static and hang it off of the Task class, so that you don't have to new up the TaskFactory, and also you get to save yourself a moving piece to maintain.</p>\n"
},
{
"answer_id": 27320,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>@ChanChan</p>\n\n<p>I like the idea of reflection, yet at the same time I've always been shy to use reflection. It's always struck me as a \"hack\" to work around something that should be easier. I did consider that approach, and then figured a switch statement would be faster for the same amount of code smell.</p>\n\n<p>You did get me thinking, I don't think the Type enum is needed, because I can always do something like this:</p>\n\n<pre><code>if (CurrentTask is MergeTask)\n{\n // Do Something Specific to MergeTask\n}\n</code></pre>\n\n<p>Perhaps I should crack open my GoF Design Patterns book again, but I really thought there was a way to polymorphically instantiate the right class.</p>\n"
},
{
"answer_id": 27324,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 2,
"selected": false,
"text": "<p>@jholland</p>\n\n<blockquote>\n <p>I don't think the Type enum is needed, because I can always do something like this:</p>\n</blockquote>\n\n<p>Enum?</p>\n\n<p>I admit that it feels hacky. Reflection feels dirty at first, but once you tame the beast you will enjoy what it allows you to do. (Remember recursion, it feels dirty, but its good)</p>\n\n<p>The trick is to realize, you are analyzing meta data, in this case a string provided from xml, and turning it into run-time behavior. That is what reflection is the best at.</p>\n\n<p><strong>BTW: the is operator, is reflection too.</strong></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Reflection_(computer_science)#Uses\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Reflection_(computer_science)#Uses</a> </p>\n"
},
{
"answer_id": 27328,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Enum?</p>\n</blockquote>\n\n<p>I was referring to the Type property and enum in my abstract class.</p>\n\n<p>Reflection it is then! I'll mark you answer as accepted in about 30 minutes, just to give time for anyone else to weigh in. Its a fun topic.</p>\n"
},
{
"answer_id": 27331,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for leaving it open, I won't complain. It is a fun topic, I wish you could polymorphicly instantiate.<br>\nEven ruby (and its superior meta-programming) has to use its reflection mechanism for this.</p>\n"
},
{
"answer_id": 27339,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": false,
"text": "<p>How do you feel about Dependency Injection? I use Ninject and the contextual binding support in it would be perfect for this situation. Look at this <a href=\"https://web.archive.org/web/20081025114811/http://kohari.org/2008/03/13/context-variables-in-ninject/\" rel=\"nofollow noreferrer\">blog post</a> on how you can use contextual binding with creating controllers with the IControllerFactory when they are requested. This should be a good resource on how to use it for your situation.</p>\n"
},
{
"answer_id": 27360,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>@Dale</p>\n\n<p>I have not inspected nInject closely, but from my high level understanding of dependency injection, I believe it would be accomplishing the same thing as ChanChans suggestion, only with more layers of cruft (er abstraction).</p>\n\n<p>In a one off situation where I just need it here, I think using some handrolled reflection code is a better approach than having an additional library to link against and only calling it one place...</p>\n\n<p>But maybe I don't understand the advantage nInject would give me here.</p>\n"
},
{
"answer_id": 27378,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 1,
"selected": false,
"text": "<p>Some frameworks may rely on reflection where needed, but most of the time you use a boot- strapper, if you will, to setup what to do when an instance of an object is needed. This is usually stored in a generic dictionary. I used my own up until recently, when I started using Ninject.</p>\n\n<p>With Ninject, the main thing I liked about it, is that when it does need to use reflection, it doesn't. Instead it takes advantage of the code generation features of .NET which make it incredibly fast. If you feel reflection would be faster in the context you are using, it also allows you to set it up that way.</p>\n\n<p>I know this maybe overkill for what you need at the moment, but I just wanted to point out dependency injection and give you some food for thought for the future. Visit the <a href=\"http://dojo.ninject.org/wiki/display/NINJECT/Home\" rel=\"nofollow noreferrer\">dojo</a> for a lesson.</p>\n"
},
{
"answer_id": 27429,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 3,
"selected": false,
"text": "<p>Create a \"Prototype\" instanace of each class and put them in a hashtable inside the factory , with the string you expect in the XML as the key.</p>\n\n<p>so CreateTask just finds the right Prototype object,\nby get() ing from the hashtable.</p>\n\n<p>then call LoadFromXML on it.</p>\n\n<p>you have to pre-load the classes into the hashtable,</p>\n\n<p>If you want it more automatic...</p>\n\n<p>You can make the classes \"self-registering\" by calling a static register method on the factory.</p>\n\n<p>Put calls to register ( with constructors) in the static blocks on the Task subclasses.\nThen all you need to do is \"mention\" the classes to get the static blocks run.</p>\n\n<p>A static array of Task subclasses would then suffice to \"mention\" them.\nOr use reflection to mention the classes.</p>\n"
},
{
"answer_id": 28659,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>@Tim, I ended up using a simplified version of your approach and ChanChans, Here is the code:</p>\n\n<pre><code>public class TaskFactory\n {\n private Dictionary<String, Type> _taskTypes = new Dictionary<String, Type>();\n\n public TaskFactory()\n {\n // Preload the Task Types into a dictionary so we can look them up later\n foreach (Type type in typeof(TaskFactory).Assembly.GetTypes())\n {\n if (type.IsSubclassOf(typeof(CCTask)))\n {\n _taskTypes[type.Name.ToLower()] = type;\n }\n }\n }\n\n public CCTask CreateTask(XmlElement task)\n {\n if (task != null)\n {\n string taskName = task.Name;\n taskName = taskName.ToLower() + \"task\";\n\n // If the Type information is in our Dictionary, instantiate a new instance of that task\n Type taskType;\n if (_taskTypes.TryGetValue(taskName, out taskType))\n {\n return (CCTask)Activator.CreateInstance(taskType, task);\n }\n else\n {\n throw new ArgumentException(\"Unrecognized Task:\" + task.Name);\n } \n }\n else\n {\n return null;\n }\n }\n }\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm working on an internal project for my company, and part of the project is to be able to parse various "Tasks" from an XML file into a collection of tasks to be ran later.
Because each type of Task has a multitude of different associated fields, I decided it would be best to represent each type of Task with a seperate class.
To do this, I constructed an abstract base class:
```
public abstract class Task
{
public enum TaskType
{
// Types of Tasks
}
public abstract TaskType Type
{
get;
}
public abstract LoadFromXml(XmlElement task);
public abstract XmlElement CreateXml(XmlDocument currentDoc);
}
```
Each task inherited from this base class, and included the code necessary to create itself from the passed in XmlElement, as well as serialize itself back out to an XmlElement.
A basic example:
```
public class MergeTask : Task
{
public override TaskType Type
{
get { return TaskType.Merge; }
}
// Lots of Properties / Methods for this Task
public MergeTask (XmlElement elem)
{
this.LoadFromXml(elem);
}
public override LoadFromXml(XmlElement task)
{
// Populates this Task from the Xml.
}
public override XmlElement CreateXml(XmlDocument currentDoc)
{
// Serializes this class back to xml.
}
}
```
The parser would then use code similar to this to create a task collection:
```
XmlNode taskNode = parent.SelectNode("tasks");
TaskFactory tf = new TaskFactory();
foreach (XmlNode task in taskNode.ChildNodes)
{
// Since XmlComments etc will show up
if (task is XmlElement)
{
tasks.Add(tf.CreateTask(task as XmlElement));
}
}
```
All of this works wonderfully, and allows me to pass tasks around using the base class, while retaining the structure of having individual classes for each task.
However, I am not happy with my code for TaskFactory.CreateTask. This method accepts an XmlElement, and then returns an instance of the appropriate Task class:
```
public Task CreateTask(XmlElement elem)
{
if (elem != null)
{
switch(elem.Name)
{
case "merge":
return new MergeTask(elem);
default:
throw new ArgumentException("Invalid Task");
}
}
}
```
Because I have to parse the XMLElement, I'm using a huge (10-15 cases in the real code) switch to pick which child class to instantiate. I'm hoping there is some sort of polymorphic trick I can do here to clean up this method.
Any advice? | I use reflection to do this.
You can make a factory that basically expands without you having to add any extra code.
make sure you have "using System.Reflection", place the following code in your instantiation method.
```
public Task CreateTask(XmlElement elem)
{
if (elem != null)
{
try
{
Assembly a = typeof(Task).Assembly
string type = string.Format("{0}.{1}Task",typeof(Task).Namespace,elem.Name);
//this is only here, so that if that type doesn't exist, this method
//throws an exception
Type t = a.GetType(type, true, true);
return a.CreateInstance(type, true) as Task;
}
catch(System.Exception)
{
throw new ArgumentException("Invalid Task");
}
}
}
```
Another observation, is that you can make this method, a static and hang it off of the Task class, so that you don't have to new up the TaskFactory, and also you get to save yourself a moving piece to maintain. |
27,303 | <p>Anyone know if it's possible to databind the ScaleX and ScaleY of a render transform in Silverlight 2 Beta 2? Binding transforms is possible in WPF - But I'm getting an error when setting up my binding in Silverlight through XAML. Perhaps it's possible to do it through code?</p>
<pre><code><Image Height="60" HorizontalAlignment="Right"
Margin="0,122,11,0" VerticalAlignment="Top" Width="60"
Source="Images/Fish128x128.png" Stretch="Fill"
RenderTransformOrigin="0.5,0.5" x:Name="fishImage">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</code></pre>
<p>I want to bind the ScaleX and ScaleY of the ScaleTransform element.</p>
<p>I'm getting a runtime error when I try to bind against a double property on my data context: </p>
<pre><code>Message="AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 1570 Position: 108]"
</code></pre>
<p>My binding looks like this:</p>
<pre><code><ScaleTransform ScaleX="{Binding Path=SelectedDive.Visibility}"
ScaleY="{Binding Path=SelectedDive.Visibility}"/>
</code></pre>
<p>I have triple verified that the binding path is correct - I'm binding a slidebar against the same value and that works just fine...</p>
<p>Visibility is of type double and is a number between 0.0 and 30.0. I have a value converter that scales that number down to 0.5 and 1 - I want to scale the size of the fish depending on the clarity of the water. So I don't think it's a problem with the type I'm binding against...</p>
| [
{
"answer_id": 27309,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "<p>Is it a runtime error or compile-time, Jonas? Looking at the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.scaletransform.scalex.aspx\" rel=\"nofollow noreferrer\">documentation</a>, ScaleX and ScaleY are dependency properties, so you should be able to write</p>\n\n<pre><code><ScaleTransform ScaleX=\"{Binding Foo}\" ScaleY=\"{Binding Bar}\" />\n</code></pre>\n\n<p>... where Foo and Bar are of the appropriate type.</p>\n\n<p>Edit: Of course, that's the WPF documentation. I suppose it's possible that they've changed ScaleX and ScaleY to be standard properties rather than dependency properties in Silverlight. I'd love to hear more about the error you're seeing.</p>\n"
},
{
"answer_id": 27337,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Ah I think I see your problem. You're attempting to bind a property of type Visibility (SelectedDive.Visibility) to a property of type Double (ScaleTransform.ScaleX). WPF/Silverlight can't convert between those two types.</p>\n\n<p>What are you trying to accomplish? Maybe I can help you with the XAML. What is \"SelectedDive\" and what do you want to happen when its Visibility changes?</p>\n"
},
{
"answer_id": 27401,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry - was looking for the answer count to go up so I didn't realise you'd edited the question with more information.</p>\n\n<p>OK, so Visibility is of type Double, so the binding should work in that regard.</p>\n\n<p>As a workaround, could you try binding your ScaleX and ScaleY values directly to the slider control that SelectedDive.Visibility is bound to? Something like:</p>\n\n<pre><code><ScaleTransform ScaleX=\"{Binding ElementName=slider1,Path=Value}\" ... />\n</code></pre>\n\n<p>If that works then it'll at least get you going.</p>\n\n<p>Edit: Ah, I just remembered that I read once that Silverlight doesn't support the ElementName syntax in bindings, so that might not work.</p>\n"
},
{
"answer_id": 27413,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Yeah maybe the embedded render transforms aren't inheriting the DataContext from the object they apply to. Can you force the DataContext into them? For example, give the transform a name:</p>\n\n<pre><code><ScaleTransform x:Name=\"myScaler\" ... />\n</code></pre>\n\n<p>... and then in your code-behind:</p>\n\n<pre><code>myScaler.DataContext = fishImage.DataContext;\n</code></pre>\n\n<p>... so that the scaler definitely shares its DataContext with the Image.</p>\n"
},
{
"answer_id": 27424,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, is the Image itself picking up the DataContext properly?</p>\n\n<p>Try adding this:</p>\n\n<pre><code><Image Tooltip=\"{Binding SelectedDive.Visibility}\" ... />\n</code></pre>\n\n<p>If that compiles and runs, hover over the image and see if it displays the right value.</p>\n"
},
{
"answer_id": 27478,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 2,
"selected": true,
"text": "<p>ScaleTransform doesn't have a data context so most likely the binding is looking for SelectedDive.Visibility off it's self and not finding it. There is much in Silverlight xaml and databinding that is different from WPF... </p>\n\n<p>Anyway to solve this you will want to set up the binding in code**, or manually listen for the PropertyChanged event of your data object and set the Scale in code behind.</p>\n\n<p>I would choose the latter if you wanted to do an animation/storyboard for the scale change.</p>\n\n<p>** i need to check but you may not be able to bind to it. as i recall if the RenderTransform is not part of an animation it gets turned into a matrix transform and all bets are off. </p>\n"
},
{
"answer_id": 27487,
"author": "Jonas Follesø",
"author_id": 1199387,
"author_profile": "https://Stackoverflow.com/users/1199387",
"pm_score": 0,
"selected": false,
"text": "<p>I was hoping to solve this through XAML, but turns out Brian's suggestion was the way to go. I used Matt's suggestion to give the scale transform a name, so that I can access it from code. Then I hooked the value changed event of the slider, and manually updates the ScaleX and ScaleY property. I kept my value converter to convert from the visibility range (0-30m) to scale (0.5 to 1). The code looks like this:</p>\n\n<pre><code> private ScaleConverter converter;\n\n public DiveLog()\n { \n InitializeComponent();\n\n converter = new ScaleConverter();\n visibilitySlider.ValueChanged += new \n RoutedPropertyChangedEventHandler<double>(visibilitySlider_ValueChanged);\n } \n\n private void visibilitySlider_ValueChanged(object sender, \n RoutedPropertyChangedEventArgs<double> e)\n {\n fishScale.ScaleX = (double)converter.Convert(e.NewValue, \n typeof(double), null, CultureInfo.CurrentCulture);\n fishScale.ScaleY = fishScale.ScaleX;\n }\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] | Anyone know if it's possible to databind the ScaleX and ScaleY of a render transform in Silverlight 2 Beta 2? Binding transforms is possible in WPF - But I'm getting an error when setting up my binding in Silverlight through XAML. Perhaps it's possible to do it through code?
```
<Image Height="60" HorizontalAlignment="Right"
Margin="0,122,11,0" VerticalAlignment="Top" Width="60"
Source="Images/Fish128x128.png" Stretch="Fill"
RenderTransformOrigin="0.5,0.5" x:Name="fishImage">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
```
I want to bind the ScaleX and ScaleY of the ScaleTransform element.
I'm getting a runtime error when I try to bind against a double property on my data context:
```
Message="AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 1570 Position: 108]"
```
My binding looks like this:
```
<ScaleTransform ScaleX="{Binding Path=SelectedDive.Visibility}"
ScaleY="{Binding Path=SelectedDive.Visibility}"/>
```
I have triple verified that the binding path is correct - I'm binding a slidebar against the same value and that works just fine...
Visibility is of type double and is a number between 0.0 and 30.0. I have a value converter that scales that number down to 0.5 and 1 - I want to scale the size of the fish depending on the clarity of the water. So I don't think it's a problem with the type I'm binding against... | ScaleTransform doesn't have a data context so most likely the binding is looking for SelectedDive.Visibility off it's self and not finding it. There is much in Silverlight xaml and databinding that is different from WPF...
Anyway to solve this you will want to set up the binding in code\*\*, or manually listen for the PropertyChanged event of your data object and set the Scale in code behind.
I would choose the latter if you wanted to do an animation/storyboard for the scale change.
\*\* i need to check but you may not be able to bind to it. as i recall if the RenderTransform is not part of an animation it gets turned into a matrix transform and all bets are off. |
27,359 | <p>I want to setup a cron job to rsync a remote system to a backup partition, something like:</p>
<pre><code>bash -c 'rsync -avz --delete --exclude=proc --exclude=sys root@remote1:/ /mnt/remote1/'
</code></pre>
<p>I would like to be able to "set it and forget it" but what if <code>/mnt/remote1</code> becomes unmounted? (After a reboot or something) I'd like to error out if <code>/mnt/remote1</code> isn't mounted, rather than filling up the local filesystem.</p>
<p><strong>Edit:</strong><br />
Here is what I came up with for a script, cleanup improvements appreciated (especially for the empty then ... else, I couldn't leave them empty or bash errors)</p>
<pre><code>#!/bin/bash
DATA=data
ERROR="0"
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1\$"; then
ERROR=0
else
if mount /dev/vg/$1 /mnt/$1; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1 could not be mounted: $ERROR"
fi
fi
if [ "$ERROR" = "0" ]; then
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1/$DATA\$"; then
ERROR=0
else
if mount /dev/vg/$1$DATA /mnt/$1/data; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1/data could not be mounted."
fi
fi
fi
if [ "$ERROR" = "0" ]; then
rsync -aqz --delete --numeric-ids --exclude=proc --exclude=sys \
root@$1.domain:/ /mnt/$1/
RETVAL=$?
echo "Backup of $1 completed, return value of rsync: $RETVAL"
fi
</code></pre>
| [
{
"answer_id": 27370,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 2,
"selected": false,
"text": "<p>A quick google led me to this bash script that can check if a filesystem is mounted. It seems that grepping the output of df or mount is the way to go:</p>\n\n<pre><code>if df |grep -q '/mnt/mountpoint$'\n then\n echo \"Found mount point, running task\"\n # Do some stuff\n else\n echo \"Aborted because the disk is not mounted\"\n # Do some error correcting stuff\n exit -1\nfi\n</code></pre>\n"
},
{
"answer_id": 27371,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 4,
"selected": true,
"text": "<pre><code>if cut -d' ' -f2 /proc/mounts | grep '^/mnt/remote1$' >/dev/null; then\n rsync -avz ...\nfi\n</code></pre>\n\n<p>Get the list of mounted partitions from <code>/proc/mounts</code>, only match <code>/mnt/remote1</code> (and if it is mounted, send grep's output to <code>/dev/null</code>), then run your <code>rsync</code> job.</p>\n\n<p>Recent <code>grep</code>s have a <code>-q</code> option that you can use instead of sending the output to <code>/dev/null</code>.</p>\n"
},
{
"answer_id": 3576205,
"author": "bob esponja",
"author_id": 19927,
"author_profile": "https://Stackoverflow.com/users/19927",
"pm_score": 3,
"selected": false,
"text": "<p><code>mountpoint</code> seems to be the best solution to this: it returns 0 if a path is a mount point:</p>\n\n<pre><code>#!/bin/bash\nif [[ `mountpoint -q /path` ]]; then\n echo \"filesystem mounted\"\nelse\n echo \"filesystem not mounted\"\nfi\n</code></pre>\n\n<p>Found at <a href=\"http://www.linuxquestions.org/questions/programming-9/bash-check-if-fs-is-already-mounted-on-directory-137282/#post4061230\" rel=\"noreferrer\">LinuxQuestions</a>.</p>\n"
},
{
"answer_id": 24021504,
"author": "Mike Q",
"author_id": 1618630,
"author_profile": "https://Stackoverflow.com/users/1618630",
"pm_score": 0,
"selected": false,
"text": "<p>I am skimming This but I would think you would rather rsync -e ssh and setup the keys to accept the account.</p>\n"
},
{
"answer_id": 28752314,
"author": "miu",
"author_id": 2524925,
"author_profile": "https://Stackoverflow.com/users/2524925",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>Copy and paste the script below to a file (e.g. backup.sh).</li>\n<li>Make the script executable (e.g. <code>chmod +x backup.sh</code>)</li>\n<li>Call the script as root with the format <code>backup.sh [username (for rsync)] [backup source device] [backup source location] [backup target device] [backup target location]</code></li>\n</ol>\n\n<p>!!!ATTENTION!!! Don't execute the script as root user without understanding the code!</p>\n\n<p>I think there's nothing to explain. The code is straightforward and well documented.</p>\n\n<pre><code>#!/bin/bash\n\n##\n## COMMAND USAGE: backup.sh [username] [backup source device] [backup source location] [backup target device] [backup target location]\n##\n## for example: sudo /home/manu/bin/backup.sh \"manu\" \"/media/disk1\" \"/media/disk1/.\" \"/media/disk2\" \"/media/disk2\"\n##\n\n##\n## VARIABLES\n##\n\n# execute as user\nUSER=\"$1\"\n\n# Set source location\nBACKUP_SOURCE_DEV=\"$2\"\nBACKUP_SOURCE=\"$3\"\n\n# Set target location\nBACKUP_TARGET_DEV=\"$4\"\nBACKUP_TARGET=\"$5\"\n\n# Log file\nLOG_FILE=\"/var/log/backup_script.log\"\n\n##\n## SCRIPT\n##\n\nfunction end() {\n echo -e \"###########################################################################\\\n#########################################################################\\n\\n\" >> \"$LOG_FILE\"\n exit $1\n}\n\n# Check that the log file exists\nif [ ! -e \"$LOG_FILE\" ]; then\n touch \"$LOG_FILE\"\n chown $USER \"$LOG_FILE\"\nfi\n\n# Check if backup source device is mounted\nif ! mountpoint \"$BACKUP_SOURCE_DEV\"; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Backup source device is not mounted!\" >> \"$LOG_FILE\"\n end 1\nfi\n\n# Check that source dir exists and is readable.\nif [ ! -r \"$BACKUP_SOURCE\" ]; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to read source dir.\" >> \"$LOG_FILE\"\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to sync.\" >> \"$LOG_FILE\"\n end 1\nfi\n\n# Check that target dir exists and is writable.\nif [ ! -w \"$BACKUP_TARGET\" ]; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to write to target dir.\" >> \"$LOG_FILE\"\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to sync.\" >> \"$LOG_FILE\"\n end 1\nfi\n\n# Check if the drive is mounted\nif ! mountpoint \"$BACKUP_TARGET_DEV\"; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - WARNING: Backup device needs mounting!\" >> \"$LOG_FILE\"\n\n # If not, mount the drive\n if mount \"$BACKUP_TARGET_DEV\" > /dev/null 2>&1 || /bin/false; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - Backup device mounted.\" >> \"$LOG_FILE\"\n else\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to mount backup device.\" >> \"$LOG_FILE\"\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to sync.\" >> \"$LOG_FILE\"\n end 1\n fi\nfi\n\n# Start entry in the log\necho \"$(date \"+%Y-%m-%d %k:%M:%S\") - Sync started.\" >> \"$LOG_FILE\"\n\n# Start sync\nsu -c \"rsync -ayhEAX --progress --delete-after --inplace --compress-level=0 --log-file=\\\"$LOG_FILE\\\" \\\"$BACKUP_SOURCE\\\" \\\"$BACKUP_TARGET\\\"\" $USER\necho \"\" >> \"$LOG_FILE\"\n\n# Unmount the drive so it does not accidentally get damaged or wiped\nif umount \"$BACKUP_TARGET_DEV\" > /dev/null 2>&1 || /bin/false; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - Backup device unmounted.\" >> \"$LOG_FILE\"\nelse\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - WARNING: Backup device could not be unmounted.\" >> \"$LOG_FILE\"\nfi\n\n# Exit successfully\nend 0\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] | I want to setup a cron job to rsync a remote system to a backup partition, something like:
```
bash -c 'rsync -avz --delete --exclude=proc --exclude=sys root@remote1:/ /mnt/remote1/'
```
I would like to be able to "set it and forget it" but what if `/mnt/remote1` becomes unmounted? (After a reboot or something) I'd like to error out if `/mnt/remote1` isn't mounted, rather than filling up the local filesystem.
**Edit:**
Here is what I came up with for a script, cleanup improvements appreciated (especially for the empty then ... else, I couldn't leave them empty or bash errors)
```
#!/bin/bash
DATA=data
ERROR="0"
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1\$"; then
ERROR=0
else
if mount /dev/vg/$1 /mnt/$1; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1 could not be mounted: $ERROR"
fi
fi
if [ "$ERROR" = "0" ]; then
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1/$DATA\$"; then
ERROR=0
else
if mount /dev/vg/$1$DATA /mnt/$1/data; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1/data could not be mounted."
fi
fi
fi
if [ "$ERROR" = "0" ]; then
rsync -aqz --delete --numeric-ids --exclude=proc --exclude=sys \
root@$1.domain:/ /mnt/$1/
RETVAL=$?
echo "Backup of $1 completed, return value of rsync: $RETVAL"
fi
``` | ```
if cut -d' ' -f2 /proc/mounts | grep '^/mnt/remote1$' >/dev/null; then
rsync -avz ...
fi
```
Get the list of mounted partitions from `/proc/mounts`, only match `/mnt/remote1` (and if it is mounted, send grep's output to `/dev/null`), then run your `rsync` job.
Recent `grep`s have a `-q` option that you can use instead of sending the output to `/dev/null`. |
27,405 | <p>On an 8-bit micro controller I would like to do the following:</p>
<pre><code>16bit_integer = another_16bit_integer * 0.997;</code></pre>
<p>with the least possible number of instructions.</p>
| [
{
"answer_id": 27415,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": false,
"text": "<p>How about integer arithmetic in 32 bits?</p>\n\n<pre><code>16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);\n</code></pre>\n\n<p>32 bits will be enough to store (INT16_MAX × 997), do the sum on values 1000 times larger then divide back to your 16 bit scale.</p>\n"
},
{
"answer_id": 27418,
"author": "Justin Tanner",
"author_id": 609,
"author_profile": "https://Stackoverflow.com/users/609",
"pm_score": 1,
"selected": false,
"text": "<p>On my platform ( Atmel AVR 8-bit micro-controller, running gcc )</p>\n\n<pre><code>16bit_integer = another_16bit_integer * 0.997;</code></pre>\n\n<p>Takes about 26 instructions.</p>\n\n<pre><code>16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);</code></pre>\n\n<p>Takes about 25 instructions.</p>\n"
},
{
"answer_id": 27451,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Precomputed lookup table:</p>\n\n<pre><code>16bit_integer = products[another_16bit_integer];\n</code></pre>\n"
},
{
"answer_id": 27479,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Precomputed lookup table:</p>\n</blockquote>\n\n<pre><code>16bit_integer = products[another_16bit_integer];\n</code></pre>\n\n<p>That's not going to work so good on the AVR, the 16bit address space is going to be exhausted.</p>\n"
},
{
"answer_id": 27481,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 0,
"selected": false,
"text": "<p>Since you are using an 8 bit processor, you can probably only handle 16 bit results, not 32 bit results. To reduce 16 bit overflow issues I would restate the formula like this:</p>\n\n<pre><code>result16 = operand16 - (operand16 * 3)/1000\n</code></pre>\n\n<p>This would give accurate results for unsigned integers up to 21845, or signed integers up to 10922. I am assuming the the processor can do 16 bit integer division. If you cannot then you need to do the division the hard way. Multiplying by 3 can be done by simple shifts & adds, if no multiply instruction exists or if multiplication only works with 8 bit operands.</p>\n\n<p>Without knowing the exact microprocessor it is impossible to determine how long such a calculation would take.</p>\n"
},
{
"answer_id": 27483,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>On my platform ( Atmel AVR 8-bit micro-controller, running gcc )</p>\n</blockquote>\n\n<pre><code>16bit_integer = another_16bit_integer * 0.997;\n</code></pre>\n\n<blockquote>\n <p>Takes about 26 instructions.</p>\n</blockquote>\n\n<pre><code>16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);\n</code></pre>\n\n<blockquote>\n <p>Takes about 25 instructions.</p>\n</blockquote>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Atmel_AVR\" rel=\"nofollow noreferrer\">Atmel AVR</a> is a RISC chip, so counting instructions is a valid comparison.</p>\n"
},
{
"answer_id": 28013,
"author": "Mike Haboustak",
"author_id": 2146,
"author_profile": "https://Stackoverflow.com/users/2146",
"pm_score": 2,
"selected": false,
"text": "<p>You probably meant to have some rounding in there, rather than truncating the result to an integer, otherwise the purpose of the operation is really limited. </p>\n\n<p>But since you asked the question with that specific formula, it brought to mind that your result set is really coarse. For the first 333 numbers, the result is: another_16bit_integer-1. You can approximate it (maybe even exactly, when not performed in my head) with something like:</p>\n\n<pre><code>16bit_integer = another_16bit_integer - 1 - (another_16bit_integer/334);\n</code></pre>\n\n<p>edit: unsigned int, and you handle 0 on your own.</p>\n"
},
{
"answer_id": 41497,
"author": "smh",
"author_id": 1077,
"author_profile": "https://Stackoverflow.com/users/1077",
"pm_score": 2,
"selected": false,
"text": "<p>Bit shifts are usually very fast:</p>\n\n<pre><code>y = 0xFF3B * (int32_t) x >> 16;\n</code></pre>\n\n<p>This is probably better written as:</p>\n\n<pre><code>y = (0.997 * 0x10000) * (int32_t)x >> 16;\n</code></pre>\n\n<p>A good compiler will generate equivalent output.</p>\n\n<p>If your integers are signed, the constants should be changed to 0x8000 and 15. </p>\n"
},
{
"answer_id": 4758603,
"author": "Rocketmagnet",
"author_id": 55934,
"author_profile": "https://Stackoverflow.com/users/55934",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a very fast way to do this operation:</p>\n\n<pre><code>a = b * 0.99609375;\n</code></pre>\n\n<p>It's similar to what you want, but it's <em>much</em> faster.</p>\n\n<pre><code>a = b;\na -= b>>8;\n</code></pre>\n\n<p>Or even faster using a trick that only works on little endian systems, like the PIC.</p>\n\n<pre><code>a = b;\na -= *((int8*)((&b)+1));\n</code></pre>\n\n<p>Off the top of my head, this comes down to the following assembler on a PIC18:</p>\n\n<pre><code>; a = b\nMOVFF 0xc4, 0xc2\nNOP\nMOVFF 0xc5, 0xc3\nNOP\n\n; a -= *((int8*)((&b)+1));\nMOVF 0xc5, w\nSUBWF 0xc2, f\nBTFSC STATUS, C\nDECF 0xc\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609/"
] | On an 8-bit micro controller I would like to do the following:
```
16bit_integer = another_16bit_integer * 0.997;
```
with the least possible number of instructions. | How about integer arithmetic in 32 bits?
```
16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);
```
32 bits will be enough to store (INT16\_MAX × 997), do the sum on values 1000 times larger then divide back to your 16 bit scale. |
27,442 | <p>Is there a rake task for backing up the data in your database? </p>
<p>I already have my schema backed up, but I want to make a backup of the data. It's a small MySQL database. </p>
| [
{
"answer_id": 27448,
"author": "thelsdj",
"author_id": 163,
"author_profile": "https://Stackoverflow.com/users/163",
"pm_score": 4,
"selected": true,
"text": "<p>The below script is a simplified version taken from <a href=\"http://github.com/engineyard/eycap/tree/master\" rel=\"nofollow noreferrer\">eycap</a>, specifically from <a href=\"http://github.com/engineyard/eycap/tree/master/lib/eycap/recipes/database.rb\" rel=\"nofollow noreferrer\">this file</a>.</p>\n\n<pre><code>set :dbuser \"user\"\nset :dbhost \"host\"\nset :database \"db\"\n\nnamespace :db do\n desc \"Get the database password from user\"\n task :get_password do\n set(:dbpass) do\n Capistrano::CLI.ui.ask \"Enter mysql password: \"\n end\n end\n\n task :backup_name, :only => { :primary => true } do\n now = Time.now\n run \"mkdir -p #{shared_path}/db_backups\"\n backup_time = [now.year,now.month,now.day,now.hour,now.min,now.sec].join('-')\n set :backup_file, \"#{shared_path}/db_backups/#{database}-snapshot-#{backup_time}.sql\"\n end\n\n desc \"Dump database to backup file\"\n task :dump, :roles => :db, :only => {:primary => true} do\n backup_name\n run \"mysqldump --add-drop-table -u #{dbuser} -h #{dbhost} -p#{dbpass} #{database} | bzip2 -c > #{backup_file}.bz2\"\n end\nend\n</code></pre>\n\n<p>Edit: Yeah, I guess I missed the point that you were looking for a rake task and not a capistrano task, but I don't have a rake one on hand, sorry.</p>\n"
},
{
"answer_id": 27503,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have a rake task for backing up my MySQL db, but I did write a script in Ruby to do just that for my WordPress DB:</p>\n\n<pre><code>filename = 'wp-config.php'\ndef get_db_info(file)\n username = nil\n password = nil\n db_name = nil\n\n file.each { |line|\n if line =~ /'DB_(USER|PASSWORD|NAME)', '([[:alnum:]]*)'/\n if $1 == \"USER\"\n username = $2\n elsif $1 == \"PASSWORD\"\n password = $2\n elsif $1 == \"NAME\"\n db_name = $2\n end\n end\n }\n\n if username.nil? || password.nil? || db_name.nil?\n puts \"[backup_db][bad] couldn't get all needed info\"\n exit\n end\n\n return username, password, db_name\nend\n\nbegin\n config_file = open(\"#{filename}\")\nrescue Errno::ENOENT\n puts \"[backup_db][bad] File '#{filename}' didn't exist\"\n exit\nelse\n puts \"[backup_db][good] File '#{filename}' existed\"\nend\n\nusername, password, db_name = get_db_info(config_file)\nsql_dump_info = `mysqldump --user=#{username} --password=#{password} #{dbname}`\nputs sql_dump_info\n</code></pre>\n\n<p>You should be able to take this and do some mild pruning of it to put in your username/password/dbname to get it up and working for you. I put it in my crontab to run everyday as well, and it shouldn't be too much work to convert this to run as a rake task since it's already Ruby code (might be a good learning exercise as well).</p>\n\n<p>Tell us how it goes!</p>\n"
},
{
"answer_id": 27511,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 1,
"selected": false,
"text": "<p>There are <a href=\"http://code.google.com/p/ar-backup/\" rel=\"nofollow noreferrer\">a</a> <a href=\"http://topfunky.net/svn/shovel/backup.rake\" rel=\"nofollow noreferrer\">few</a> <a href=\"http://snippets.dzone.com/posts/show/4777\" rel=\"nofollow noreferrer\">solutions</a> already on google. I am going to guess that you are using activerecord as your orm?</p>\n\n<p>If you are running rails, then you can looks at the Rakefile that it uses for activerecord in \\ruby\\lib\\ruby\\gems\\1.8\\gems\\rails-2.0.2-\\lib\\tasks\\database.rake. That gave me a lot of information on how to extend the generic Rakefile.</p>\n\n<p>You could take the capistrano tasks that <a href=\"https://stackoverflow.com/questions/27442/is-there-a-rake-task-for-backing-up-the-data-in-your-database#27448\">thelsdj</a> provides, and add it to your rake file. Then modify it a bit so that it uses the activerecord connection to the database.</p>\n"
},
{
"answer_id": 29276,
"author": "AndrewR",
"author_id": 2994,
"author_profile": "https://Stackoverflow.com/users/2994",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure to add the \"--routines\" parameter to mysqldump if you have any stored procs in your database so it backs them up too.</p>\n"
},
{
"answer_id": 53456,
"author": "user5510",
"author_id": 5510,
"author_profile": "https://Stackoverflow.com/users/5510",
"pm_score": 1,
"selected": false,
"text": "<p>There's a plugin out there called \"mysql tasks\", just google for it. It's just a rakefile -- I've found it very easy to use.</p>\n"
},
{
"answer_id": 1131737,
"author": "Darren Bishop",
"author_id": 133330,
"author_profile": "https://Stackoverflow.com/users/133330",
"pm_score": 2,
"selected": false,
"text": "<p>Just in case people are still surfing for solutions, we currently use the ar_fixtures plugin to backup our db, well as part of the solution anyway.</p>\n\n<p>It provides the rake <code>db:fixtures:dump</code> tasks. This spits out everythin in YAML into test/fixtures, so it can be loaded in again using <code>db:fixtures:load</code>.</p>\n\n<p>We use this to backup before every feature push to production. We also used this when migrating from sqlite3 to Postgres - which is subtlety very useful as incompatibilities between SQL dialects are, for the most part, hidden.</p>\n\n<p>All the best, D</p>\n"
},
{
"answer_id": 19730313,
"author": "mikowiec",
"author_id": 2945404,
"author_profile": "https://Stackoverflow.com/users/2945404",
"pm_score": 0,
"selected": false,
"text": "<p>There is my rake task to backup mysql, and rotate backups cyclically.</p>\n\n<pre><code>#encoding: utf-8\n#require 'fileutils'\n\nnamespace :mls do\n desc 'Create of realty_dev database backup'\n\n task :backup => :environment do\n backup_max_records = 4\n datestamp = Time.now.strftime(\"%Y-%m-%d_%H-%M\")\n backup_dir = File.join(Rails.root, ENV['DIR'] || 'backups', 'db')\n backup_file_name = \"#{datestamp}_#{Rails.env}_dump.sql\"\n backup_file_path = File.join(backup_dir, \"#{backup_file_name}\")\n FileUtils.mkdir_p(backup_dir)\n\n #database processing\n db_config = ActiveRecord::Base.configurations[Rails.env]\n system \"mysqldump -u#{db_config['username']} -p#{db_config['password']} -i -c -q #{db_config['database']} > #{backup_file_path}\"\n raise 'Unable to make DB backup!' if ($?.to_i > 0)\n\n # sql dump file compression\n system \"gzip -9 #{backup_file_path}\"\n\n # backup rotation\n dir = Dir.new(backup_dir)\n backup_all_records = dir.entries.sort[2..-1].reverse\n puts \"Created backup: #{backup_file_name}.gz\"\n #redundant records\n backup_del_records = backup_all_records[backup_max_records..-1] || []\n\n # backup deleting too old records\n for backup_del_record in backup_del_records\n FileUtils.rm_rf(File.join(backup_dir, backup_del_record))\n end\n\n puts \"Deleted #{backup_del_records.length} old backups, #{backup_all_records.length - backup_del_records.length} backups available\"\n puts \"Backup passed\"\n end\nend\n\n=begin\n run by this command: \" rake db:backup RAILS_ENV=\"development\" \"\n=end\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] | Is there a rake task for backing up the data in your database?
I already have my schema backed up, but I want to make a backup of the data. It's a small MySQL database. | The below script is a simplified version taken from [eycap](http://github.com/engineyard/eycap/tree/master), specifically from [this file](http://github.com/engineyard/eycap/tree/master/lib/eycap/recipes/database.rb).
```
set :dbuser "user"
set :dbhost "host"
set :database "db"
namespace :db do
desc "Get the database password from user"
task :get_password do
set(:dbpass) do
Capistrano::CLI.ui.ask "Enter mysql password: "
end
end
task :backup_name, :only => { :primary => true } do
now = Time.now
run "mkdir -p #{shared_path}/db_backups"
backup_time = [now.year,now.month,now.day,now.hour,now.min,now.sec].join('-')
set :backup_file, "#{shared_path}/db_backups/#{database}-snapshot-#{backup_time}.sql"
end
desc "Dump database to backup file"
task :dump, :roles => :db, :only => {:primary => true} do
backup_name
run "mysqldump --add-drop-table -u #{dbuser} -h #{dbhost} -p#{dbpass} #{database} | bzip2 -c > #{backup_file}.bz2"
end
end
```
Edit: Yeah, I guess I missed the point that you were looking for a rake task and not a capistrano task, but I don't have a rake one on hand, sorry. |
27,455 | <p>I'm attempting to use Mono to load a bitmap and print it on Linux but I'm getting an exception. Does Mono support printing on Linux? The code/exception are below:</p>
<p><strong>EDIT:</strong> No longer getting the exception, but I'm still curious what kind of support there is. Leaving the code for posterity or something.</p>
<pre><code>private void btnPrintTest_Click(object sender, EventArgs e)
{
_printDocTest.DefaultPageSettings.Landscape = true;
_printDocTest.DefaultPageSettings.Margins = new Margins(50,50,50,50);
_printDocTest.Print();
}
void _printDocTest_PrintPage(object sender, PrintPageEventArgs e)
{
var bmp = new Bitmap("test.bmp");
// Determine center of graph
var xCenter = e.MarginBounds.X + (e.MarginBounds.Width - bmp.Width) / 2;
var yCenter = e.MarginBounds.Y + (e.MarginBounds.Height - bmp.Height) / 2;
e.Graphics.DrawImage(bmp, xCenter, yCenter);
e.HasMorePages = false;
}
</code></pre>
| [
{
"answer_id": 27459,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 4,
"selected": true,
"text": "<p>From the <a href=\"http://www.mono-project.com/FAQ:_General\" rel=\"noreferrer\">Mono docs</a>, I think yes:</p>\n\n<blockquote>\n <p>Managed.Windows.Forms (aka\n System.Windows.Forms): A complete and\n cross platform, System.Drawing based\n Winforms implementation.</p>\n</blockquote>\n\n<p>It also useful if you run the <a href=\"http://www.mono-project.com/Moma\" rel=\"noreferrer\">Mono Migration Analyzer</a> first.</p>\n"
},
{
"answer_id": 27460,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.go-mono.com/archive/1.2/\" rel=\"nofollow noreferrer\">According to</a></p>\n\n<p>System.Drawing is now complete, and in addition to being the underlying rendering engine for Windows.Forms, it has also been tested for using third party controls that heavily depend on it.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I'm attempting to use Mono to load a bitmap and print it on Linux but I'm getting an exception. Does Mono support printing on Linux? The code/exception are below:
**EDIT:** No longer getting the exception, but I'm still curious what kind of support there is. Leaving the code for posterity or something.
```
private void btnPrintTest_Click(object sender, EventArgs e)
{
_printDocTest.DefaultPageSettings.Landscape = true;
_printDocTest.DefaultPageSettings.Margins = new Margins(50,50,50,50);
_printDocTest.Print();
}
void _printDocTest_PrintPage(object sender, PrintPageEventArgs e)
{
var bmp = new Bitmap("test.bmp");
// Determine center of graph
var xCenter = e.MarginBounds.X + (e.MarginBounds.Width - bmp.Width) / 2;
var yCenter = e.MarginBounds.Y + (e.MarginBounds.Height - bmp.Height) / 2;
e.Graphics.DrawImage(bmp, xCenter, yCenter);
e.HasMorePages = false;
}
``` | From the [Mono docs](http://www.mono-project.com/FAQ:_General), I think yes:
>
> Managed.Windows.Forms (aka
> System.Windows.Forms): A complete and
> cross platform, System.Drawing based
> Winforms implementation.
>
>
>
It also useful if you run the [Mono Migration Analyzer](http://www.mono-project.com/Moma) first. |
27,509 | <p>How do I check if an object property in JavaScript is undefined?</p>
| [
{
"answer_id": 27510,
"author": "tslocum",
"author_id": 1662,
"author_profile": "https://Stackoverflow.com/users/1662",
"pm_score": -1,
"selected": false,
"text": "<pre><code>if (somevariable == undefined) {\n alert('the variable is not defined!');\n}\n</code></pre>\n\n<p>You can also make it into a function, as shown <a href=\"http://verens.com/archives/2005/07/25/isset-for-javascript/\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>function isset(varname){\n return(typeof(window[varname]) != 'undefined');\n}\n</code></pre>\n"
},
{
"answer_id": 27517,
"author": "Pandincus",
"author_id": 2273,
"author_profile": "https://Stackoverflow.com/users/2273",
"pm_score": 7,
"selected": false,
"text": "<p>In JavaScript there is <strong>null</strong> and there is <strong>undefined</strong>. They have different meanings.</p>\n<ul>\n<li><strong>undefined</strong> means that the variable value has not been defined; it is not known what the value is.</li>\n<li><strong>null</strong> means that the variable value is defined and set to null (has no value).</li>\n</ul>\n<p>Marijn Haverbeke states, in his free, online book "<a href=\"http://eloquentjavascript.net/\" rel=\"noreferrer\">Eloquent JavaScript</a>" (emphasis mine):</p>\n<blockquote>\n<p>There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. <strong>In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.</strong></p>\n</blockquote>\n<p>So, I guess the best way to check if something was undefined would be:</p>\n<pre><code>if (something == undefined)\n</code></pre>\n<p>Object properties should work the same way.</p>\n<pre><code>var person = {\n name: "John",\n age: 28,\n sex: "male"\n};\n\nalert(person.name); // "John"\nalert(person.fakeVariable); // undefined\n</code></pre>\n"
},
{
"answer_id": 27911,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 4,
"selected": false,
"text": "<p>The solution is incorrect. In JavaScript,</p>\n\n<pre><code>null == undefined\n</code></pre>\n\n<p>will return true, because they both are \"casted\" to a boolean and are false. The correct way would be to check</p>\n\n<pre><code>if (something === undefined)\n</code></pre>\n\n<p>which is the identity operator...</p>\n"
},
{
"answer_id": 416327,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 13,
"selected": true,
"text": "<p>The usual way to check if the value of a property is the special value <code>undefined</code>, is:</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(o.myProperty === undefined) {\n alert("myProperty value is the special value `undefined`");\n}\n</code></pre>\n<p>To check if an object does not actually have such a property, and will therefore return <code>undefined</code> by default when you try to access it:</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(!o.hasOwnProperty('myProperty')) {\n alert("myProperty does not exist");\n}\n</code></pre>\n<p>To check if the value associated with an identifier is the special value <code>undefined</code>, <em>or</em> if that identifier has not been declared:</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(typeof myVariable === 'undefined') {\n alert('myVariable is either the special value `undefined`, or it has not been declared');\n}\n</code></pre>\n<p>Note: this last method is the only way to refer to an <strong>undeclared</strong> identifier without an early error, which is different from having a value of <code>undefined</code>.</p>\n<p>In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check <code>foo === undefined</code> might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.</p>\n<p>However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.</p>\n<p>If you are worried about this (unlikely) edge case, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void\" rel=\"noreferrer\">the void operator</a> to get at the special <code>undefined</code> value itself:</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(myVariable === void 0) {\n alert("myVariable is the special value `undefined`");\n}\n</code></pre>\n"
},
{
"answer_id": 3232194,
"author": "Rixius",
"author_id": 212307,
"author_profile": "https://Stackoverflow.com/users/212307",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function isUnset(inp) {\n return (typeof inp === 'undefined')\n}\n</code></pre>\n\n<p>Returns false if variable is set, and true if is undefined.</p>\n\n<p>Then use:</p>\n\n<pre><code>if (isUnset(var)) {\n // initialize variable here\n}\n</code></pre>\n"
},
{
"answer_id": 3345556,
"author": "Kevin",
"author_id": 403606,
"author_profile": "https://Stackoverflow.com/users/403606",
"pm_score": 6,
"selected": false,
"text": "<pre><code>if ( typeof( something ) == \"undefined\") \n</code></pre>\n\n<p>This worked for me while the others didn't.</p>\n"
},
{
"answer_id": 3550319,
"author": "MarkPflug",
"author_id": 190371,
"author_profile": "https://Stackoverflow.com/users/190371",
"pm_score": 10,
"selected": false,
"text": "<p>I believe there are a number of incorrect answers to this topic. Contrary to common belief, \"undefined\" is <strong>not</strong> a keyword in JavaScript and can in fact have a value assigned to it.</p>\n\n<h1>Correct Code</h1>\n\n<p>The most robust way to perform this test is:</p>\n\n<pre><code>if (typeof myVar === \"undefined\")\n</code></pre>\n\n<p>This will always return the correct result, and even handles the situation where <code>myVar</code> is not declared.</p>\n\n<h1>Degenerate code. DO NOT USE.</h1>\n\n<pre><code>var undefined = false; // Shockingly, this is completely legal!\nif (myVar === undefined) {\n alert(\"You have been misled. Run away!\");\n}\n</code></pre>\n\n<p>Additionally, <code>myVar === undefined</code> will raise an error in the situation where myVar is undeclared.</p>\n"
},
{
"answer_id": 3770178,
"author": "Eric",
"author_id": 455129,
"author_profile": "https://Stackoverflow.com/users/455129",
"pm_score": 5,
"selected": false,
"text": "<p>I'm not sure where the origin of using <code>===</code> with <code>typeof</code> came from, and as a convention I see it used in many libraries, but the typeof operator returns a string literal, and we know that up front, so why would you also want to type check it too?</p>\n\n<pre><code>typeof x; // some string literal \"string\", \"object\", \"undefined\"\nif (typeof x === \"string\") { // === is redundant because we already know typeof returns a string literal\nif (typeof x == \"string\") { // sufficient\n</code></pre>\n"
},
{
"answer_id": 6274093,
"author": "Michael Anderson",
"author_id": 221955,
"author_profile": "https://Stackoverflow.com/users/221955",
"pm_score": 6,
"selected": false,
"text": "<p>The issue boils down to three cases:</p>\n\n<ol>\n<li>The object has the property and its value is not <code>undefined</code>.</li>\n<li>The object has the property and its value is <code>undefined</code>.</li>\n<li>The object does not have the property.</li>\n</ol>\n\n<p>This tells us something I consider important:</p>\n\n<p><strong>There is a difference between an undefined member and a defined member with an undefined value.</strong></p>\n\n<p>But unhappily <code>typeof obj.foo</code> does not tell us which of the three cases we have. However we can combine this with <code>\"foo\" in obj</code> to distinguish the cases.</p>\n\n<pre><code> | typeof obj.x === 'undefined' | !(\"x\" in obj)\n1. { x:1 } | false | false\n2. { x : (function(){})() } | true | false\n3. {} | true | true\n</code></pre>\n\n<p>Its worth noting that these tests are the same for <code>null</code> entries too</p>\n\n<pre><code> | typeof obj.x === 'undefined' | !(\"x\" in obj)\n { x:null } | false | false\n</code></pre>\n\n<p>I'd argue that in some cases it makes more sense (and is clearer) to check whether the property is there, than checking whether it is undefined, and the only case where this check will be different is case 2, the rare case of an actual entry in the object with an undefined value.</p>\n\n<p>For example: I've just been refactoring a bunch of code that had a bunch of checks whether an object had a given property.</p>\n\n<pre><code>if( typeof blob.x != 'undefined' ) { fn(blob.x); }\n</code></pre>\n\n<p>Which was clearer when written without a check for undefined.</p>\n\n<pre><code>if( \"x\" in blob ) { fn(blob.x); }\n</code></pre>\n\n<p>But as has been mentioned these are not exactly the same (but are more than good enough for my needs). </p>\n"
},
{
"answer_id": 7041744,
"author": "Codebeat",
"author_id": 565244,
"author_profile": "https://Stackoverflow.com/users/565244",
"pm_score": 4,
"selected": false,
"text": "<p>If you do</p>\n\n<pre><code>if (myvar == undefined )\n{ \n alert('var does not exists or is not initialized');\n}\n</code></pre>\n\n<p>it will fail when the variable <code>myvar</code> does not exists, because myvar is not defined, so the script is broken and the test has no effect.</p>\n\n<p>Because the window object has a global scope (default object) outside a function, a declaration will be 'attached' to the window object.</p>\n\n<p>For example:</p>\n\n<pre><code>var myvar = 'test';\n</code></pre>\n\n<p>The global variable <em>myvar</em> is the same as <em>window.myvar</em> or <em>window['myvar']</em></p>\n\n<p>To avoid errors to test when a global variable exists, you better use:</p>\n\n<pre><code>if(window.myvar == undefined )\n{ \n alert('var does not exists or is not initialized');\n}\n</code></pre>\n\n<p>The question if a variable really exists doesn't matter, its value is incorrect. Otherwise, it is silly to initialize variables with undefined, and it is better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check its type or rely on <code>!window.myvar</code> to check if it has a proper/valid value. So even when the variable is not defined then <code>!window.myvar</code> is the same for <code>myvar = undefined</code> or <code>myvar = false</code> or <code>myvar = 0</code>.</p>\n\n<p>When you expect a specific type, test the type of the variable. To speed up testing a condition you better do:</p>\n\n<pre><code>if( !window.myvar || typeof window.myvar != 'string' )\n{\n alert('var does not exists or is not type of string');\n}\n</code></pre>\n\n<p>When the first and simple condition is true, the interpreter skips the next tests. </p>\n\n<p>It is always better to use the instance/object of the variable to check if it got a valid value. It is more stable and is a better way of programming. </p>\n\n<p>(y)</p>\n"
},
{
"answer_id": 7793028,
"author": "Anoop",
"author_id": 460942,
"author_profile": "https://Stackoverflow.com/users/460942",
"pm_score": 3,
"selected": false,
"text": "<p>You can get an array all undefined with path using the following code.</p>\n\n<pre><code> function getAllUndefined(object) {\n\n function convertPath(arr, key) {\n var path = \"\";\n for (var i = 1; i < arr.length; i++) {\n\n path += arr[i] + \"->\";\n }\n path += key;\n return path;\n }\n\n\n var stack = [];\n var saveUndefined= [];\n function getUndefiend(obj, key) {\n\n var t = typeof obj;\n switch (t) {\n case \"object\":\n if (t === null) {\n return false;\n }\n break;\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"null\":\n return false;\n default:\n return true;\n }\n stack.push(key);\n for (k in obj) {\n if (obj.hasOwnProperty(k)) {\n v = getUndefiend(obj[k], k);\n if (v) {\n saveUndefined.push(convertPath(stack, k));\n }\n }\n }\n stack.pop();\n\n }\n\n getUndefiend({\n \"\": object\n }, \"\");\n return saveUndefined;\n }\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/anoop26667/9XbEK/\" rel=\"noreferrer\">jsFiddle</a> link</p>\n"
},
{
"answer_id": 9342877,
"author": "Corey Richardson",
"author_id": 1419479,
"author_profile": "https://Stackoverflow.com/users/1419479",
"pm_score": -1,
"selected": false,
"text": "<p><code>Object.hasOwnProperty(o, 'propertyname');</code></p>\n\n<p>This doesn't look up through the prototype chain, however.</p>\n"
},
{
"answer_id": 12589152,
"author": "Joe Johnson",
"author_id": 836474,
"author_profile": "https://Stackoverflow.com/users/836474",
"pm_score": 5,
"selected": false,
"text": "<p>I didn't see (hope I didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):</p>\n<pre><code>if (obj && obj.prop) {\n // Do something;\n}\n</code></pre>\n<p>If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is <em>usually</em> the desired behavior in most code block statements (in JavaScript).</p>\n<h2>UPDATE: (7/2/2021)</h2>\n<p>The latest version of JavaScript introduces a new operator for\noptional chaining: <code>?.</code></p>\n<p>This is probably going to be the most explicit and efficient method of checking for the existence of object properties, moving forward.</p>\n<p>Ref: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining</a></p>\n"
},
{
"answer_id": 14306293,
"author": "drzaus",
"author_id": 1037948,
"author_profile": "https://Stackoverflow.com/users/1037948",
"pm_score": 5,
"selected": false,
"text": "<p>Crossposting <a href=\"https://stackoverflow.com/questions/3390396/how-can-i-check-for-undefined-in-javascript/14305002#14305002\">my answer</a> from related question <em><a href=\"https://stackoverflow.com/questions/3390396/how-can-i-check-for-undefined-in-javascript\">How can I check for "undefined" in JavaScript?</a></em>.</p>\n<p><em>Specific to this question, see test cases with <code>someObject.<whatever></code>.</em></p>\n<hr />\n<p>Some scenarios illustrating the results of the various answers:\n<a href=\"http://jsfiddle.net/drzaus/UVjM4/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/drzaus/UVjM4/</a></p>\n<p><em>(Note that the use of <code>var</code> for <code>in</code> tests make a difference when in a scoped wrapper)</em></p>\n<p>Code for reference:</p>\n<pre><code>(function(undefined) {\n var definedButNotInitialized;\n definedAndInitialized = 3;\n someObject = {\n firstProp: "1"\n , secondProp: false\n // , undefinedProp not defined\n }\n // var notDefined;\n\n var tests = [\n 'definedButNotInitialized in window',\n 'definedAndInitialized in window',\n 'someObject.firstProp in window',\n 'someObject.secondProp in window',\n 'someObject.undefinedProp in window',\n 'notDefined in window',\n\n '"definedButNotInitialized" in window',\n '"definedAndInitialized" in window',\n '"someObject.firstProp" in window',\n '"someObject.secondProp" in window',\n '"someObject.undefinedProp" in window',\n '"notDefined" in window',\n\n 'typeof definedButNotInitialized == "undefined"',\n 'typeof definedButNotInitialized === typeof undefined',\n 'definedButNotInitialized === undefined',\n '! definedButNotInitialized',\n '!! definedButNotInitialized',\n\n 'typeof definedAndInitialized == "undefined"',\n 'typeof definedAndInitialized === typeof undefined',\n 'definedAndInitialized === undefined',\n '! definedAndInitialized',\n '!! definedAndInitialized',\n\n 'typeof someObject.firstProp == "undefined"',\n 'typeof someObject.firstProp === typeof undefined',\n 'someObject.firstProp === undefined',\n '! someObject.firstProp',\n '!! someObject.firstProp',\n\n 'typeof someObject.secondProp == "undefined"',\n 'typeof someObject.secondProp === typeof undefined',\n 'someObject.secondProp === undefined',\n '! someObject.secondProp',\n '!! someObject.secondProp',\n\n 'typeof someObject.undefinedProp == "undefined"',\n 'typeof someObject.undefinedProp === typeof undefined',\n 'someObject.undefinedProp === undefined',\n '! someObject.undefinedProp',\n '!! someObject.undefinedProp',\n\n 'typeof notDefined == "undefined"',\n 'typeof notDefined === typeof undefined',\n 'notDefined === undefined',\n '! notDefined',\n '!! notDefined'\n ];\n\n var output = document.getElementById('results');\n var result = '';\n for(var t in tests) {\n if( !tests.hasOwnProperty(t) ) continue; // bleh\n\n try {\n result = eval(tests[t]);\n } catch(ex) {\n result = 'Exception--' + ex;\n }\n console.log(tests[t], result);\n output.innerHTML += "\\n" + tests[t] + ": " + result;\n }\n})();\n</code></pre>\n<p>And results:</p>\n<pre><code>definedButNotInitialized in window: true\ndefinedAndInitialized in window: false\nsomeObject.firstProp in window: false\nsomeObject.secondProp in window: false\nsomeObject.undefinedProp in window: true\nnotDefined in window: Exception--ReferenceError: notDefined is not defined\n"definedButNotInitialized" in window: false\n"definedAndInitialized" in window: true\n"someObject.firstProp" in window: false\n"someObject.secondProp" in window: false\n"someObject.undefinedProp" in window: false\n"notDefined" in window: false\ntypeof definedButNotInitialized == "undefined": true\ntypeof definedButNotInitialized === typeof undefined: true\ndefinedButNotInitialized === undefined: true\n! definedButNotInitialized: true\n!! definedButNotInitialized: false\ntypeof definedAndInitialized == "undefined": false\ntypeof definedAndInitialized === typeof undefined: false\ndefinedAndInitialized === undefined: false\n! definedAndInitialized: false\n!! definedAndInitialized: true\ntypeof someObject.firstProp == "undefined": false\ntypeof someObject.firstProp === typeof undefined: false\nsomeObject.firstProp === undefined: false\n! someObject.firstProp: false\n!! someObject.firstProp: true\ntypeof someObject.secondProp == "undefined": false\ntypeof someObject.secondProp === typeof undefined: false\nsomeObject.secondProp === undefined: false\n! someObject.secondProp: true\n!! someObject.secondProp: false\ntypeof someObject.undefinedProp == "undefined": true\ntypeof someObject.undefinedProp === typeof undefined: true\nsomeObject.undefinedProp === undefined: true\n! someObject.undefinedProp: true\n!! someObject.undefinedProp: false\ntypeof notDefined == "undefined": true\ntypeof notDefined === typeof undefined: true\nnotDefined === undefined: Exception--ReferenceError: notDefined is not defined\n! notDefined: Exception--ReferenceError: notDefined is not defined\n!! notDefined: Exception--ReferenceError: notDefined is not defined\n</code></pre>\n"
},
{
"answer_id": 18135509,
"author": "Konstantin Smolyanin",
"author_id": 1823469,
"author_profile": "https://Stackoverflow.com/users/1823469",
"pm_score": 7,
"selected": false,
"text": "<p>What does this mean: <strong>\"undefined object property\"</strong>?</p>\n\n<p>Actually it can mean two quite different things! First, it can mean <em>the property that has never been defined</em> in the object and, second, it can mean the <em>property that has an undefined value</em>. Let's look at this code:</p>\n\n<pre><code>var o = { a: undefined }\n</code></pre>\n\n<p>Is <code>o.a</code> undefined? Yes! Its value is undefined. Is <code>o.b</code> undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:</p>\n\n<pre><code>typeof o.a == 'undefined' // true\ntypeof o.b == 'undefined' // true\no.a === undefined // true\no.b === undefined // true\n'a' in o // true\n'b' in o // false\n</code></pre>\n\n<p>We can clearly see that <code>typeof obj.prop == 'undefined'</code> and <code>obj.prop === undefined</code> are equivalent, and they do not distinguish those different situations. And <code>'prop' in obj</code> can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.</p>\n\n<h2>So what to do?</h2>\n\n<p>1) You want to know if a property is undefined by either the first or second meaning (the most typical situation).</p>\n\n<pre><code>obj.prop === undefined // IMHO, see \"final fight\" below\n</code></pre>\n\n<p>2) You want to just know if object has some property and don't care about its value.</p>\n\n<pre><code>'prop' in obj\n</code></pre>\n\n<h2>Notes:</h2>\n\n<ul>\n<li>You can't check an object and its property at the same time. For example, this <code>x.a === undefined</code> or this <code>typeof x.a == 'undefined'</code> raises <code>ReferenceError: x is not defined</code> if x is not defined.</li>\n<li>Variable <code>undefined</code> is a global variable (so actually it is <code>window.undefined</code> in browsers). It has been supported since ECMAScript 1st Edition and since ECMAScript 5 it is <strong>read only</strong>. So in modern browsers it can't be <em>redefined to true</em> as many authors love to frighten us with, but this is still a true for older browsers.</li>\n</ul>\n\n<h2>Final fight: <code>obj.prop === undefined</code> vs <code>typeof obj.prop == 'undefined'</code></h2>\n\n<p>Pluses of <code>obj.prop === undefined</code>:</p>\n\n<ul>\n<li>It's a bit shorter and looks a bit prettier</li>\n<li>The JavaScript engine will give you an error if you have misspelled <code>undefined</code></li>\n</ul>\n\n<p>Minuses of <code>obj.prop === undefined</code>:</p>\n\n<ul>\n<li><code>undefined</code> can be overridden in old browsers</li>\n</ul>\n\n<p>Pluses of <code>typeof obj.prop == 'undefined'</code>:</p>\n\n<ul>\n<li>It is really universal! It works in new and old browsers.</li>\n</ul>\n\n<p>Minuses of <code>typeof obj.prop == 'undefined'</code>:</p>\n\n<ul>\n<li><code>'undefned'</code> (<em>misspelled</em>) here is just a string constant, so the JavaScript engine can't help you if you have misspelled it like I just did.</li>\n</ul>\n\n<h2>Update (for server-side JavaScript):</h2>\n\n<p>Node.js supports the global variable <code>undefined</code> as <code>global.undefined</code> (it can also be used without the 'global' prefix). I don't know about other implementations of server-side JavaScript.</p>\n"
},
{
"answer_id": 18254258,
"author": "wayneseymour",
"author_id": 352033,
"author_profile": "https://Stackoverflow.com/users/352033",
"pm_score": 3,
"selected": false,
"text": "<p>Here is my situation:</p>\n<p>I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object.</p>\n<p>There is one error I need to defend. If the arguments to the REST call were incorrect as far as the user specifying the arguments wrong, the REST call comes back basically empty.</p>\n<p>While using this post to help me defend against this, I tried this:</p>\n<pre><code>if( typeof restResult.data[0] === "undefined" ) { throw "Some error"; }\n</code></pre>\n<p>For my situation, if restResult.data[0] === "object", then I can safely start inspecting the rest of the members. If undefined then throw the error as above.</p>\n<p>What I am saying is that for my situation, all the previous suggestions in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone.</p>\n"
},
{
"answer_id": 20679527,
"author": "Marthijn",
"author_id": 788840,
"author_profile": "https://Stackoverflow.com/users/788840",
"pm_score": 4,
"selected": false,
"text": "<p>In the article <em><a href=\"http://flippinawesome.org/2013/12/09/exploring-the-abyss-of-null-and-undefined-in-javascript/\" rel=\"noreferrer\">Exploring the Abyss of Null and Undefined in JavaScript </a></em> I read that frameworks like <a href=\"https://en.wikipedia.org/wiki/Underscore.js\" rel=\"noreferrer\">Underscore.js</a> use this function:</p>\n\n<pre><code>function isUndefined(obj){\n return obj === void 0;\n}\n</code></pre>\n"
},
{
"answer_id": 20883574,
"author": "bevacqua",
"author_id": 389745,
"author_profile": "https://Stackoverflow.com/users/389745",
"pm_score": 3,
"selected": false,
"text": "<p>Compare with <code>void 0</code>, for terseness.</p>\n\n<pre><code>if (foo !== void 0)\n</code></pre>\n\n<p>It's not as verbose as <code>if (typeof foo !== 'undefined')</code></p>\n"
},
{
"answer_id": 21682564,
"author": "DenisS",
"author_id": 2088061,
"author_profile": "https://Stackoverflow.com/users/2088061",
"pm_score": 4,
"selected": false,
"text": "<h2>'<em>if (window.x) { }</em>' is error safe</h2>\n\n<p>Most likely you want <code>if (window.x)</code>. This check is safe even if x hasn't been declared (<code>var x;</code>) - browser doesn't throw an error. </p>\n\n<h2>Example: I want to know if my browser supports History API</h2>\n\n<pre><code>if (window.history) {\n history.call_some_function();\n}\n</code></pre>\n\n<h2>How this works:</h2>\n\n<p><strong>window</strong> is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If <strong>x</strong> hasn't been declared or hasn't been set then <code>window.x</code> returns <strong>undefined</strong>. <strong>undefined</strong> leads to <strong>false</strong> when <strong>if()</strong> evaluates it.</p>\n"
},
{
"answer_id": 22053469,
"author": "Ry-",
"author_id": 707111,
"author_profile": "https://Stackoverflow.com/users/707111",
"pm_score": 8,
"selected": false,
"text": "<p>Despite being vehemently recommended by many other answers here, <code>typeof</code> <em>is a bad choice</em>. It should never be used for checking whether variables have the value <code>undefined</code>, because it acts as a combined check for the value <code>undefined</code> and for whether a variable exists. In the vast majority of cases, you know when a variable exists, and <code>typeof</code> will just introduce the potential for a silent failure if you make a typo in the variable name or in the string literal <code>'undefined'</code>.</p>\n<pre><code>var snapshot = …;\n\nif (typeof snaposhot === 'undefined') {\n // ^\n // misspelled¹ – this will never run, but it won’t throw an error!\n}\n</code></pre>\n\n<pre><code>var foo = …;\n\nif (typeof foo === 'undefned') {\n // ^\n // misspelled – this will never run, but it won’t throw an error!\n}\n</code></pre>\n<p>So unless you’re doing feature detection², where there’s uncertainty whether a given name will be in scope (like checking <code>typeof module !== 'undefined'</code> as a step in code specific to a CommonJS environment), <code>typeof</code> is a harmful choice when used on a variable, and the correct option is to compare the value directly:</p>\n<pre><code>var foo = …;\n\nif (foo === undefined) {\n ⋮\n}\n</code></pre>\n<p>Some common misconceptions about this include:</p>\n<ul>\n<li><p>that reading an “uninitialized” variable (<code>var foo</code>) or parameter (<code>function bar(foo) { … }</code>, called as <code>bar()</code>) will fail. This is simply not true – variables without explicit initialization and parameters that weren’t given values always become <code>undefined</code>, and are always in scope.</p>\n</li>\n<li><p>that <code>undefined</code> can be overwritten. It’s true that <code>undefined</code> isn’t a keyword, but it <em>is</em> read-only and non-configurable. There are other built-ins you probably don’t avoid despite their non-keyword status (<code>Object</code>, <code>Math</code>, <code>NaN</code>…) and practical code usually isn’t written in an actively malicious environment, so this isn’t a good reason to be worried about <code>undefined</code>. (But if you are writing a code generator, feel free to use <code>void 0</code>.)</p>\n</li>\n</ul>\n<p>With how variables work out of the way, it’s time to address the actual question: object properties. There is no reason to ever use <code>typeof</code> for object properties. The earlier exception regarding feature detection doesn’t apply here – <code>typeof</code> only has special behaviour on variables, and expressions that reference object properties are not variables.</p>\n<p>This:</p>\n<pre><code>if (typeof foo.bar === 'undefined') {\n ⋮\n}\n</code></pre>\n<p>is <em>always exactly equivalent</em> to this³:</p>\n<pre><code>if (foo.bar === undefined) {\n ⋮\n}\n</code></pre>\n<p>and taking into account the advice above, to avoid confusing readers as to why you’re using <code>typeof</code>, because it makes the most sense to use <code>===</code> to check for equality, because it could be refactored to checking a variable’s value later, and because it just plain looks better, <strong>you should always use <code>=== undefined</code>³ here as well</strong>.</p>\n<p>Something else to consider when it comes to object properties is whether you really want to check for <code>undefined</code> at all. A given property name can be absent on an object (producing the value <code>undefined</code> when read), present on the object itself with the value <code>undefined</code>, present on the object’s prototype with the value <code>undefined</code>, or present on either of those with a non-<code>undefined</code> value. <code>'key' in obj</code> will tell you whether a key is anywhere on an object’s prototype chain, and <code>Object.prototype.hasOwnProperty.call(obj, 'key')</code> will tell you whether it’s directly on the object. I won’t go into detail in this answer about prototypes and using objects as string-keyed maps, though, because it’s mostly intended to counter all the bad advice in other answers irrespective of the possible interpretations of the original question. Read up on <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes\" rel=\"noreferrer\">object prototypes on MDN</a> for more!</p>\n<p><sub>¹ unusual choice of example variable name? this is real dead code from the NoScript extension for Firefox.</sub><br />\n<sub>² don’t assume that not knowing what’s in scope is okay in general, though. bonus vulnerability caused by abuse of dynamic scope: <a href=\"https://bugs.chromium.org/p/project-zero/issues/detail?id=1225&desc=6\" rel=\"noreferrer\">Project Zero 1225</a></sub><br />\n<sub>³ once again assuming an ES5+ environment and that <code>undefined</code> refers to the <code>undefined</code> property of the global object.</sub></p>\n"
},
{
"answer_id": 23463075,
"author": "sam",
"author_id": 822138,
"author_profile": "https://Stackoverflow.com/users/822138",
"pm_score": 4,
"selected": false,
"text": "<pre><code>\"propertyName\" in obj //-> true | false\n</code></pre>\n"
},
{
"answer_id": 24243518,
"author": "raskalbass",
"author_id": 1289868,
"author_profile": "https://Stackoverflow.com/users/1289868",
"pm_score": 2,
"selected": false,
"text": "<p>Also, the same things can be written shorter:</p>\n<pre><code>if (!variable){\n // Do it if the variable is undefined\n}\n</code></pre>\n<p>or</p>\n<pre><code>if (variable){\n // Do it if the variable is defined\n}\n</code></pre>\n"
},
{
"answer_id": 24277572,
"author": "Juan Garcia",
"author_id": 1802325,
"author_profile": "https://Stackoverflow.com/users/1802325",
"pm_score": 3,
"selected": false,
"text": "<p>All the answers are incomplete. This is the right way of knowing that there is a property 'defined as undefined':</p>\n<pre><code>var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){\n return ((prop in obj) && (typeof obj[prop] == 'undefined'));\n};\n</code></pre>\n<p>Example:</p>\n<pre><code>var a = { b : 1, e : null };\na.c = a.d;\n\nhasUndefinedProperty(a, 'b'); // false: b is defined as 1\nhasUndefinedProperty(a, 'c'); // true: c is defined as undefined\nhasUndefinedProperty(a, 'd'); // false: d is undefined\nhasUndefinedProperty(a, 'e'); // false: e is defined as null\n\n// And now...\ndelete a.c ;\nhasUndefinedProperty(a, 'c'); // false: c is undefined\n</code></pre>\n<p>Too bad that this been the right answer and is buried in wrong answers >_<</p>\n<p>So, for anyone who pass by, I will give you undefined's for free!!</p>\n<pre><code>var undefined ; undefined ; // undefined\n({}).a ; // undefined\n[].a ; // undefined\n''.a ; // undefined\n(function(){}()) ; // undefined\nvoid(0) ; // undefined\neval() ; // undefined\n1..a ; // undefined\n/a/.a ; // undefined\n(true).a ; // undefined\n</code></pre>\n"
},
{
"answer_id": 24626893,
"author": "Angelin Nadar",
"author_id": 412591,
"author_profile": "https://Stackoverflow.com/users/412591",
"pm_score": 3,
"selected": false,
"text": "<p>Going through the comments, for those who want to check both is it undefined or its value is null:</p>\n\n<pre><code>//Just in JavaScript\nvar s; // Undefined\nif (typeof s == \"undefined\" || s === null){\n alert('either it is undefined or value is null')\n}\n</code></pre>\n\n<p>If you are using jQuery Library then <code>jQuery.isEmptyObject()</code> will suffice for both cases,</p>\n\n<pre><code>var s; // Undefined\njQuery.isEmptyObject(s); // Will return true;\n\ns = null; // Defined as null\njQuery.isEmptyObject(s); // Will return true;\n\n//Usage\nif (jQuery.isEmptyObject(s)) {\n alert('Either variable:s is undefined or its value is null');\n} else {\n alert('variable:s has value ' + s);\n}\n\ns = 'something'; // Defined with some value\njQuery.isEmptyObject(s); // Will return false;\n</code></pre>\n"
},
{
"answer_id": 26273383,
"author": "Seti",
"author_id": 3535045,
"author_profile": "https://Stackoverflow.com/users/3535045",
"pm_score": 2,
"selected": false,
"text": "<p>I would like to show you something I'm using in order to protect the <code>undefined</code> variable:</p>\n\n<pre><code>Object.defineProperty(window, 'undefined', {});\n</code></pre>\n\n<p>This forbids anyone to change the <code>window.undefined</code> value therefore destroying the code based on that variable. If using <code>\"use strict\"</code>, anything trying to change its value will end in error, otherwise it would be silently ignored.</p>\n"
},
{
"answer_id": 27474938,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using Angular: </p>\n\n<pre><code>angular.isUndefined(obj)\nangular.isUndefined(obj.prop)\n</code></pre>\n\n<p>Underscore.js:</p>\n\n<pre><code>_.isUndefined(obj) \n_.isUndefined(obj.prop) \n</code></pre>\n"
},
{
"answer_id": 28522648,
"author": "Travis",
"author_id": 4303905,
"author_profile": "https://Stackoverflow.com/users/4303905",
"pm_score": 4,
"selected": false,
"text": "<p>Reading through this, I'm amazed I didn't see this. I have found multiple algorithms that would work for this.</p>\n\n<h1>Never Defined</h1>\n\n<p>If the value of an object was never defined, this will prevent from returning <code>true</code> if it is defined as <code>null</code> or <code>undefined</code>. This is helpful if you want true to be returned for values set as <code>undefined</code></p>\n\n<pre><code>if(obj.prop === void 0) console.log(\"The value has never been defined\");\n</code></pre>\n\n<h1>Defined as undefined Or never Defined</h1>\n\n<p>If you want it to result as <code>true</code> for values defined with the value of <code>undefined</code>, or never defined, you can simply use <code>=== undefined</code></p>\n\n<pre><code>if(obj.prop === undefined) console.log(\"The value is defined as undefined, or never defined\");\n</code></pre>\n\n<h1>Defined as a falsy value, undefined,null, or never defined.</h1>\n\n<p>Commonly, people have asked me for an algorithm to figure out if a value is either falsy, <code>undefined</code>, or <code>null</code>. The following works.</p>\n\n<pre><code>if(obj.prop == false || obj.prop === null || obj.prop === undefined) {\n console.log(\"The value is falsy, null, or undefined\");\n}\n</code></pre>\n"
},
{
"answer_id": 28902597,
"author": "Val",
"author_id": 1083704,
"author_profile": "https://Stackoverflow.com/users/1083704",
"pm_score": 3,
"selected": false,
"text": "<p>I use <code>if (this.variable)</code> to test if it is defined. A simple <code>if (variable)</code>, <a href=\"https://stackoverflow.com/questions/27509/detecting-an-undefined-object-property/12589152#12589152\">recommended in a previous answer</a>, fails for me.</p>\n<p>It turns out that it works only when a variable is a field of some object, <code>obj.someField</code> to check if it is defined in the dictionary. But we can use <code>this</code> or <code>window</code> as the dictionary object since any variable is a field in the current window, as I understand it. Therefore here is a test:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>if (this.abc) \n alert(\"defined\"); \nelse \n alert(\"undefined\");\n\nabc = \"abc\";\nif (this.abc) \n alert(\"defined\"); \nelse \n alert(\"undefined\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>It first detects that variable <code>abc</code> is undefined and it is defined after initialization.</p>\n"
},
{
"answer_id": 32009076,
"author": "Mike Clark",
"author_id": 4261022,
"author_profile": "https://Stackoverflow.com/users/4261022",
"pm_score": 2,
"selected": false,
"text": "<p>Use:</p>\n\n<p><strong>To check if property is undefined:</strong></p>\n\n<pre><code>if (typeof something === \"undefined\") {\n alert(\"undefined\");\n}\n</code></pre>\n\n<p><strong>To check if property is not undefined:</strong></p>\n\n<pre><code>if (typeof something !== \"undefined\") {\n alert(\"not undefined\");\n}\n</code></pre>\n"
},
{
"answer_id": 34782448,
"author": "lzl124631x",
"author_id": 3127828,
"author_profile": "https://Stackoverflow.com/users/3127828",
"pm_score": 2,
"selected": false,
"text": "<p>From lodash.js.</p>\n<pre><code>var undefined;\nfunction isUndefined(value) {\n return value === undefined;\n}\n</code></pre>\n<p>It creates a <em>local</em> variable named <code>undefined</code> which is initialized with the default value -- the real <code>undefined</code>, then compares <code>value</code> with the variable <code>undefined</code>.</p>\n<hr />\n<p>Update 9/9/2019</p>\n<p>I found Lodash updated its implementation. See <a href=\"https://github.com/lodash/lodash/issues/4041\" rel=\"nofollow noreferrer\">my issue</a> and <a href=\"https://github.com/lodash/lodash/blob/4ea8c2ec249be046a0f4ae32539d652194caf74f/isUndefined.js#L17\" rel=\"nofollow noreferrer\">the code</a>.</p>\n<p>To be bullet-proof, simply use:</p>\n<pre><code>function isUndefined(value) {\n return value === void 0;\n}\n</code></pre>\n"
},
{
"answer_id": 35768990,
"author": "Marian Klühspies",
"author_id": 2324388,
"author_profile": "https://Stackoverflow.com/users/2324388",
"pm_score": 3,
"selected": false,
"text": "<p>There is a nice and elegant way to assign a defined property to a new variable if it is defined or assign a default value to it as a fallback if it’s undefined.</p>\n<pre><code>var a = obj.prop || defaultValue;\n</code></pre>\n<p>It’s suitable if you have a function, which receives an additional configuration property:</p>\n<pre><code>var yourFunction = function(config){\n\n this.config = config || {};\n this.yourConfigValue = config.yourConfigValue || 1;\n console.log(this.yourConfigValue);\n}\n</code></pre>\n<p>Now executing</p>\n<pre><code>yourFunction({yourConfigValue:2});\n//=> 2\n\nyourFunction();\n//=> 1\n\nyourFunction({otherProperty:5});\n//=> 1\n</code></pre>\n"
},
{
"answer_id": 43058440,
"author": "Patrick Roberts",
"author_id": 1541563,
"author_profile": "https://Stackoverflow.com/users/1541563",
"pm_score": 1,
"selected": false,
"text": "<p>I'm surprised I haven't seen this suggestion yet, but it gets even more specificity than testing with <code>typeof</code>. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor\" rel=\"nofollow noreferrer\"><code>Object.getOwnPropertyDescriptor()</code></a> if you need to know whether an object property was initialized with <code>undefined</code> or if it was never initialized:</p>\n<pre><code>// to test someObject.someProperty\nvar descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');\n\nif (typeof descriptor === 'undefined') {\n // was never initialized\n} else if (typeof descriptor.value === 'undefined') {\n if (descriptor.get || descriptor.set) {\n // is an accessor property, defined via getter and setter\n } else {\n // is initialized with `undefined`\n }\n} else {\n // is initialized with some other value\n}\n</code></pre>\n"
},
{
"answer_id": 43527813,
"author": "Bekim Bacaj",
"author_id": 5896426,
"author_profile": "https://Stackoverflow.com/users/5896426",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably the only explicit form of determining if the existing property-name has an explicit and intended value of <code>undefined</code>; which is, nonetheless, a JavaScript type.</p>\n<pre><code>"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";\n>> true \\ false\n</code></pre>\n<p>This expression will only return <code>true</code> if the property name of the given context exists (truly) and only if its intended value is explicitly <code>undefined</code>.</p>\n<p>There will be no false positives like with empty or blank strings zeros nulls or empty arrays and alike. This does exactly that. Checks i.e., makes sure the property name exists (otherwise it would be a false positive), than it explicitly checks if its value is <code>undefined</code> e.g. of an undefined JavaScript type in it's string representation form (literally "undefined") therefore <code>==</code> instead of <code>===</code> because no further conversion is possible. And this expression will only return true if both, that is all conditions are met. E.g. if the property-name doesn't exist, - it will return false. Which is the only correct return since nonexistent properties can't have values, not even an undefined one.</p>\n<p>Example:</p>\n<pre><code>containerObject = { propertyName: void "anything" }\n>> Object { propertyName: undefined }\n\n// Now the testing\n\n"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";\n>> true\n\n/* Which makes sure that nonexistent property will not return a false positive\n * unless it is previously defined */\n\n"foo" in containerObject && ""+containerObject["foo"] == "undefined";\n>> false\n</code></pre>\n"
},
{
"answer_id": 44161028,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 4,
"selected": false,
"text": "<p>Simply anything is not defined in JavaScript, is <strong>undefined</strong>, doesn't matter if it's a property inside an <strong>Object/Array</strong> or as just a simple variable...</p>\n\n<p>JavaScript has <code>typeof</code> which make it very easy to detect an undefined variable.</p>\n\n<p>Simply check if <code>typeof whatever === 'undefined'</code> and it will return a boolean.</p>\n\n<p>That's how the famous function <code>isUndefined()</code> in AngularJs v.1x is written:</p>\n\n<pre><code>function isUndefined(value) {return typeof value === 'undefined';} \n</code></pre>\n\n<p>So as you see the function receive a value, if that value is defined, it will return <code>false</code>, otherwise for undefined values, return <code>true</code>. </p>\n\n<p>So let's have a look what gonna be the results when we passing values, including object properties like below, this is the list of variables we have:</p>\n\n<pre><code>var stackoverflow = {};\nstackoverflow.javascipt = 'javascript';\nvar today;\nvar self = this;\nvar num = 8;\nvar list = [1, 2, 3, 4, 5];\nvar y = null;\n</code></pre>\n\n<p>and we check them as below, you can see the results in front of them as a comment:</p>\n\n<pre><code>isUndefined(stackoverflow); //false\nisUndefined(stackoverflow.javascipt); //false\nisUndefined(today); //true\nisUndefined(self); //false\nisUndefined(num); //false\nisUndefined(list); //false\nisUndefined(y); //false\nisUndefined(stackoverflow.java); //true\nisUndefined(stackoverflow.php); //true\nisUndefined(stackoverflow && stackoverflow.css); //true\n</code></pre>\n\n<p>As you see we can check anything with using something like this in our code, as mentioned you can simply use <code>typeof</code> in your code, but if you are using it over and over, create a function like the angular sample which I share and keep reusing as following DRY code pattern.</p>\n\n<p>Also one more thing, for checking property on an object in a real application which you not sure even the object exists or not, check if the object exists first.</p>\n\n<p>If you check a property on an object and the object doesn't exist, will throw an error and stop the whole application running.</p>\n\n<pre><code>isUndefined(x.css);\nVM808:2 Uncaught ReferenceError: x is not defined(…)\n</code></pre>\n\n<p>So simple you can wrap inside an if statement like below:</p>\n\n<pre><code>if(typeof x !== 'undefined') {\n //do something\n}\n</code></pre>\n\n<p>Which also equal to isDefined in Angular 1.x...</p>\n\n<pre><code>function isDefined(value) {return typeof value !== 'undefined';}\n</code></pre>\n\n<p>Also other javascript frameworks like underscore has similar defining check, but I recommend you use <code>typeof</code> if you already not using any frameworks.</p>\n\n<p>I also add this section from MDN which has got useful information about typeof, undefined and void(0).</p>\n\n<blockquote>\n <p><strong>Strict equality and undefined</strong> <br> You can use undefined and the strict equality and inequality operators to determine whether a variable has\n a value. In the following code, the variable x is not defined, and the\n if statement evaluates to true.</p>\n</blockquote>\n\n<pre><code>var x;\nif (x === undefined) {\n // these statements execute\n}\nelse {\n // these statements do not execute\n}\n</code></pre>\n\n<blockquote>\n <p>Note: The strict equality operator rather than the standard equality\n operator must be used here, because x == undefined also checks whether\n x is null, while strict equality doesn't. null is not equivalent to\n undefined. See comparison operators for details.</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><strong>Typeof operator and undefined</strong> <br>\n Alternatively, typeof can be used:</p>\n</blockquote>\n\n<pre><code>var x;\nif (typeof x === 'undefined') {\n // these statements execute\n}\n</code></pre>\n\n<blockquote>\n <p>One reason to use typeof is that it does not throw an error if the\n variable has not been declared.</p>\n</blockquote>\n\n<pre><code>// x has not been declared before\nif (typeof x === 'undefined') { // evaluates to true without errors\n // these statements execute\n}\n\nif (x === undefined) { // throws a ReferenceError\n\n}\n</code></pre>\n\n<blockquote>\n <p>However, this kind of technique should be avoided. JavaScript is a\n statically scoped language, so knowing if a variable is declared can\n be read by seeing whether it is declared in an enclosing context. The\n only exception is the global scope, but the global scope is bound to\n the global object, so checking the existence of a variable in the\n global context can be done by checking the existence of a property on\n the global object (using the in operator, for instance).</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><strong>Void operator and undefined</strong></p>\n \n <p>The void operator is a third alternative.</p>\n</blockquote>\n\n<pre><code>var x;\nif (x === void 0) {\n // these statements execute\n}\n\n// y has not been declared before\nif (y === void 0) {\n // throws a ReferenceError (in contrast to `typeof`)\n}\n</code></pre>\n\n<p>more > <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 44556602,
"author": "IliasT",
"author_id": 3015469,
"author_profile": "https://Stackoverflow.com/users/3015469",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming you're going to also want to check for it being <em>either</em> <code>undefined</code> or <code>null</code>. If so, I suggest:</p>\n<p><code>myVar == null</code></p>\n<p>This is one of the only times a <strong>double equals</strong> is very helpful as it will evaluate to <code>true</code> when <code>myVar</code> is <code>undefined</code> or <code>null</code>, but it will evaluate to <code>false</code> when it is other falsey values such as <code>0</code>, <code>false</code>, <code>''</code>, and <code>NaN</code>.</p>\n<p>This the actual <a href=\"https://github.com/lodash/lodash/blob/4.17.4/lodash.js#L11987\" rel=\"nofollow noreferrer\">the source code</a> for Lodash's <a href=\"https://lodash.com/docs/4.17.4#isNil\" rel=\"nofollow noreferrer\"><code>isNil</code></a> method.</p>\n"
},
{
"answer_id": 46988171,
"author": "blackmiaool",
"author_id": 4831179,
"author_profile": "https://Stackoverflow.com/users/4831179",
"pm_score": 3,
"selected": false,
"text": "<p>I provide three ways here for those who expect weird answers:</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-js lang-js prettyprint-override\"><code>function isUndefined1(val) {\n try {\n val.a;\n } catch (e) {\n return /undefined/.test(e.message);\n }\n return false;\n}\n\nfunction isUndefined2(val) {\n return !val && val+'' === 'undefined';\n}\n\nfunction isUndefined3(val) {\n const defaultVal = {};\n return ((input = defaultVal) => input === defaultVal)(val);\n}\n\nfunction test(func){\n console.group(`test start :`+func.name);\n console.log(func(undefined));\n console.log(func(null));\n console.log(func(1));\n console.log(func(\"1\"));\n console.log(func(0));\n console.log(func({}));\n console.log(func(function () { }));\n console.groupEnd();\n}\ntest(isUndefined1);\ntest(isUndefined2);\ntest(isUndefined3);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>isUndefined1:</h3>\n<p>Try to get a property of the input value, and check the error message if it exists. If the input value is undefined, the error message would be <em>Uncaught TypeError: Cannot read property 'b' of undefined</em>.</p>\n<h3>isUndefined2:</h3>\n<p>Convert the input value to a string to compare with <code>"undefined"</code> and ensure it's a negative value.</p>\n<h3>isUndefined3:</h3>\n<p>In JavaScript, an optional parameter works when the input value is exactly <code>undefined</code>.</p>\n"
},
{
"answer_id": 49158713,
"author": "Aditya Vashishtha",
"author_id": 8618959,
"author_profile": "https://Stackoverflow.com/users/8618959",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the JavaScript object function like this:</p>\n<pre><code>var ojb ={\n age: 12\n}\n\nif(ojb.hasOwnProperty('name')){\n console.log('property exists and is not undefined');\n}\n</code></pre>\n<p>The above method returns <code>true</code> if it got that property or the property is not undefined.</p>\n"
},
{
"answer_id": 49412206,
"author": "Sarkis Arutiunian",
"author_id": 5278472,
"author_profile": "https://Stackoverflow.com/users/5278472",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use a Proxy. It will work with nested calls, but it will require one extra check:</p>\n<pre><code>function resolveUnknownProps(obj, resolveKey) {\n const handler = {\n get(target, key) {\n if (\n target[key] !== null &&\n typeof target[key] === 'object'\n ) {\n return resolveUnknownProps(target[key], resolveKey);\n } else if (!target[key]) {\n return resolveUnknownProps({ [resolveKey]: true }, resolveKey);\n }\n\n return target[key];\n },\n };\n\n return new Proxy(obj, handler);\n}\n\nconst user = {}\n\nconsole.log(resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else); // { isUndefined: true }\n</code></pre>\n<p>So you will use it like:</p>\n<pre><code>const { isUndefined } = resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else;\nif (!isUndefined) {\n // Do something\n}\n</code></pre>\n"
},
{
"answer_id": 49706807,
"author": "Aliaksandr Sushkevich",
"author_id": 7600492,
"author_profile": "https://Stackoverflow.com/users/7600492",
"pm_score": 0,
"selected": false,
"text": "<p>There are a few little helpers in the <a href=\"https://lodash.com/\" rel=\"nofollow noreferrer\">Lodash</a> library:</p>\n<p><a href=\"https://lodash.com/docs/4.17.5#isUndefined\" rel=\"nofollow noreferrer\">isUndefined</a> - to check if <em>value</em> is <code>undefined</code>.</p>\n<pre><code>_.isUndefined(undefined) // => true\n_.isUndefined(null) // => false\n</code></pre>\n<p><a href=\"https://lodash.com/docs/4.17.5#has\" rel=\"nofollow noreferrer\">has</a> - to check if object contains a property</p>\n<pre><code>const object = { 'a': { 'b': 2 } }\n\n_.has(object, 'a.b') // => true\n_.has(object, 'a.c') // => false\n</code></pre>\n"
},
{
"answer_id": 51478480,
"author": "Krishnadas PC",
"author_id": 2295484,
"author_profile": "https://Stackoverflow.com/users/2295484",
"pm_score": 1,
"selected": false,
"text": "<p>Introduced in <strong>ECMAScript 6</strong>, we can now deal with <code>undefined</code> in a new way using Proxies. It can be used to set a default value to any properties which doesn't exist so that we don't have to check each time whether it actually exists.</p>\n<pre><code>var handler = {\n get: function(target, name) {\n return name in target ? target[name] : 'N/A';\n }\n};\n\nvar p = new Proxy({}, handler);\np.name = 'Kevin';\nconsole.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)\n</code></pre>\n<p>Will output the below text without getting any undefined.</p>\n<pre><code>Name: Kevin , Age: N/A , Gender: N/A\n</code></pre>\n"
},
{
"answer_id": 52275862,
"author": "CodeDraken",
"author_id": 10326132,
"author_profile": "https://Stackoverflow.com/users/10326132",
"pm_score": 2,
"selected": false,
"text": "<p>A simple way to check if a key exists is to use <code>in</code>:</p>\n<pre><code>if (key in obj) {\n // Do something\n} else {\n // Create key\n}\n\nconst obj = {\n 0: 'abc',\n 1: 'def'\n}\n\nconst hasZero = 0 in obj\n\nconsole.log(hasZero) // true\n</code></pre>\n"
},
{
"answer_id": 58129331,
"author": "Przemek Struciński",
"author_id": 8680601,
"author_profile": "https://Stackoverflow.com/users/8680601",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://en.wikipedia.org/wiki/ECMAScript#10th_Edition_%E2%80%93_ECMAScript_2019\" rel=\"noreferrer\">ECMAScript 10</a> introduced a new feature - <strong>optional chaining</strong> which you can use to use a property of an object only when an object is defined like this:</p>\n<pre><code>const userPhone = user?.contactDetails?.phone;\n</code></pre>\n<p>It will reference to the phone property only when user and contactDetails are defined.</p>\n<p>Ref. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining</a></p>\n"
},
{
"answer_id": 59999090,
"author": "Ravi Makwana",
"author_id": 6631280,
"author_profile": "https://Stackoverflow.com/users/6631280",
"pm_score": 0,
"selected": false,
"text": "<p>I found this article, <em><a href=\"https://dmitripavlutin.com/7-tips-to-handle-undefined-in-javascript/\" rel=\"nofollow noreferrer\">7 Tips to Handle undefined in JavaScript</a></em>, which is showing really interesting things about <code>undefined</code>\nlike:</p>\n<p>The existence of undefined is a consequence of JavaScript’s permissive nature that allows the usage of:</p>\n<ul>\n<li>uninitialized variables</li>\n<li>non-existing object properties or methods</li>\n<li>out of bounds indexes to access array elements</li>\n<li>the invocation result of a function that returns nothing</li>\n</ul>\n"
},
{
"answer_id": 61550879,
"author": "Kiran Maniya",
"author_id": 8203357,
"author_profile": "https://Stackoverflow.com/users/8203357",
"pm_score": 0,
"selected": false,
"text": "<p>In JavaScript, there are <strong>truthy</strong> and <strong>falsy</strong> expressions. If you want to check if the property is undefined or not, there is a straight way of using an <strong>if</strong> condition as given,</p>\n<ol>\n<li>Using <b>truthy/falsy</b> concept.</li>\n</ol>\n<pre class=\"lang-js prettyprint-override\"><code>if(!ob.someProp){\n console.log('someProp is falsy')\n}\n</code></pre>\n<p>However, there are several more approaches to check the object has property or not, but it seems long to me. Here are those.</p>\n<ol start=\"2\">\n<li>Using <b><code>=== undefined</code></b> check in <b><code>if</code></b> condition</li>\n</ol>\n<pre class=\"lang-js prettyprint-override\"><code>if(ob.someProp === undefined){\n console.log('someProp is undefined')\n}\n</code></pre>\n<ol start=\"3\">\n<li>Using <b><code>typeof</code></b></li>\n</ol>\n<p><b><code>typeof</code></b> acts as a combined check for the value undefined and for whether a variable exists.</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(typeof ob.someProp === 'undefined'){\n console.log('someProp is undefined')\n}\n</code></pre>\n<ol start=\"4\">\n<li>Using <b><code>hasOwnProperty</code></b> method</li>\n</ol>\n<p>The JavaScript object has built in the <code>hasOwnProperty</code> function in the object prototype.</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(!ob.hasOwnProperty('someProp')){\n console.log('someProp is undefined')\n}\n</code></pre>\n<p>Not going in deep, but the 1<sup>st</sup> way looks shortened and good to me. Here are the details on <a href=\"https://howtodoinjava.com/typescript/truthy-and-falsy/\" rel=\"nofollow noreferrer\">truthy/falsy</a> values in JavaScript and <code>undefined</code> is the falsy value listed in there. So the <code>if</code> condition behaves normally without any glitch. Apart from the <code>undefined</code>, values <code>NaN</code>, <code>false</code> (Obviously), <code>''</code> (empty string) and number <code>0</code> are also the falsy values.</p>\n<blockquote>\n<p><strong>Warning</strong>: <em>Make sure the property value does not contain any falsy value, otherwise the <code>if</code> condition will return false. For such a case, you can use the <code>hasOwnProperty</code> method</em></p>\n</blockquote>\n"
},
{
"answer_id": 61607190,
"author": "Sajad Saderi",
"author_id": 9845404,
"author_profile": "https://Stackoverflow.com/users/9845404",
"pm_score": 3,
"selected": false,
"text": "<p>There is a very easy and simple way.</p>\n<p>You can use <strong>optional chaining</strong>:</p>\n<pre><code>x = {prop:{name:"sajad"}}\n\nconsole.log(x.prop?.name) // Output is: "sajad"\nconsole.log(x.prop?.lastName) // Output is: undefined\n</code></pre>\n<p>or</p>\n<pre><code>if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error\n</code></pre>\n<p>You can use optional chaining even for functions or arrays.</p>\n<p>As of mid-2020 this is not universally implemented. Check the documentation at <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining</a></p>\n"
},
{
"answer_id": 63021093,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 0,
"selected": false,
"text": "<h1>Review</h1>\n<p>A lot of the given answers give a wrong result because they do not distinguish between the case when an object property does not exist and the case when a property has value <code>undefined</code>. Here is <strong>proof</strong> for most popular solutions:</p>\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-js lang-js prettyprint-override\"><code>let obj = {\n a: 666,\n u: undefined // The 'u' property has value 'undefined'\n // The 'x' property does not exist\n}\n\nconsole.log('>>> good results:');\nconsole.log('A', \"u\" in obj, \"x\" in obj);\nconsole.log('B', obj.hasOwnProperty(\"u\"), obj.hasOwnProperty(\"x\"));\n\nconsole.log('\\n>>> bad results:');\nconsole.log('C', obj.u === undefined, obj.x === undefined);\nconsole.log('D', obj.u == undefined, obj.x == undefined);\nconsole.log('E', obj[\"u\"] === undefined, obj[\"x\"] === undefined);\nconsole.log('F', obj[\"u\"] == undefined, obj[\"x\"] == undefined);\nconsole.log('G', !obj.u, !obj.x);\nconsole.log('H', typeof obj.u === 'undefined', typeof obj.x === 'undefined');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64125263,
"author": "Hanzla Habib",
"author_id": 3946527,
"author_profile": "https://Stackoverflow.com/users/3946527",
"pm_score": 2,
"selected": false,
"text": "<p>In recent JavaScript release there is new chaining operator introduced, which is most probably best way to check if property exists else it will give you undefined</p>\n<p>see example below</p>\n<pre><code> const adventurer = {\n name: 'Alice',\n cat: {\n name: 'Dinah'\n }\n};\n\nconst dogName = adventurer.dog?.name;\nconsole.log(dogName);\n// expected output: undefined\n\nconsole.log(adventurer.someNonExistentMethod?.());\n// expected output: undefined\n</code></pre>\n<p>We can replace this old syntax</p>\n<pre><code>if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}\n</code></pre>\n<p>with this neater syntax</p>\n<pre><code>if( response?.data?.someData?.someMoreData) {}\n</code></pre>\n<p>This syntax is not supported in IE, Opera, safari & samsund android</p>\n<p>for more detail you can check this URL</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining</a></p>\n"
},
{
"answer_id": 65342690,
"author": "Adam111p",
"author_id": 3058581,
"author_profile": "https://Stackoverflow.com/users/3058581",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Version for the use of dynamic variables</strong>\nDid you know?</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-js lang-js prettyprint-override\"><code>var boo ='lala';\n\nfunction check(){\n if(this['foo']){\n console.log('foo is here');}\n else{\n console.log('have no foo');\n }\n\n if(this['boo']){\n console.log('boo is here');}\n else{\n console.log('have no boo');\n }\n}\n\ncheck();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68147770,
"author": "Balaji",
"author_id": 8389576,
"author_profile": "https://Stackoverflow.com/users/8389576",
"pm_score": 0,
"selected": false,
"text": "<p>handle undefined</p>\n<pre><code>function isUndefined(variable,defaultvalue=''){\n\n if (variable == undefined ) return defaultvalue;\n \n return variable;\n\n}\n</code></pre>\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 obj={\nund:undefined,\nnotundefined:'hi i am not undefined'\n}\n\n\nfunction isUndefined(variable,defaultvalue=''){\n\n if (variable == undefined )\n { \n return defaultvalue;\n }\n return variable\n\n}\n\nconsole.log(isUndefined(obj.und,'i am print'))\nconsole.log(isUndefined(obj.notundefined,'i am print'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 69569312,
"author": "Ali Yaghoubi",
"author_id": 11662335,
"author_profile": "https://Stackoverflow.com/users/11662335",
"pm_score": 2,
"selected": false,
"text": "<p>We at <strong>ES6</strong> can with <code>!!</code> Convert all <strong>values to Boolean</strong>.\nUsing this, all <em>falsy</em> values become <em>false</em>.</p>\n<p><strong>First solution</strong></p>\n<pre><code>if (!(!!variable)) {\n // Code\n}\n</code></pre>\n<p><strong>Second solution</strong></p>\n<pre><code>if (!variable) {\n // Code\n}\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | How do I check if an object property in JavaScript is undefined? | The usual way to check if the value of a property is the special value `undefined`, is:
```js
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
```
To check if an object does not actually have such a property, and will therefore return `undefined` by default when you try to access it:
```js
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
```
To check if the value associated with an identifier is the special value `undefined`, *or* if that identifier has not been declared:
```js
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
```
Note: this last method is the only way to refer to an **undeclared** identifier without an early error, which is different from having a value of `undefined`.
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check `foo === undefined` might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use [the void operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) to get at the special `undefined` value itself:
```js
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
``` |
27,532 | <p>Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is <a href="http://jtauber.com/blog/2008/05/18/creating_gradients_programmatically_in_python/" rel="noreferrer">this blog entry</a>, but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.</p>
| [
{
"answer_id": 27536,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<p>you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage <em>p</em> of the first colour and percentage 1 - <em>p</em> of the second:</p>\n\n<pre><code>R = firstCol.R * p + secondCol.R * (1 - p)\n</code></pre>\n\n<p>There's <a href=\"https://stackoverflow.com/questions/25007/conditional-formatting-percentage-to-color-conversion\">another question</a> related to this.</p>\n\n<p>There are other methods of interpolation that sometimes work better. For example, using a <a href=\"http://en.wikipedia.org/wiki/Sigmoid_function\" rel=\"noreferrer\">bell-shaped (sigmoidal)</a> interpolation function makes the transition smoother.</p>\n\n<p>/EDIT: Oops, you mean using a predefined function. OK, even easier. The blog post you linked now has an example code in Python.</p>\n\n<p>In Java, you could use the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/GradientPaint.html\" rel=\"noreferrer\"><code>GradientPaint</code></a>.</p>\n"
},
{
"answer_id": 27553,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 3,
"selected": false,
"text": "<p>Using the basic AWT classes, you could do something like this:</p>\n\n<pre><code>import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Rectangle2D;\nimport javax.swing.JPanel;\n\npublic class LinearGradient extends JPanel {\n\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n Color color1 = Color.RED;\n Color color2 = Color.BLUE;\n int steps = 30;\n int rectWidth = 10;\n int rectHeight = 10;\n\n for (int i = 0; i < steps; i++) {\n float ratio = (float) i / (float) steps;\n int red = (int) (color2.getRed() * ratio + color1.getRed() * (1 - ratio));\n int green = (int) (color2.getGreen() * ratio + color1.getGreen() * (1 - ratio));\n int blue = (int) (color2.getBlue() * ratio + color1.getBlue() * (1 - ratio));\n Color stepColor = new Color(red, green, blue);\n Rectangle2D rect2D = new Rectangle2D.Float(rectWidth * i, 0, rectWidth, rectHeight);\n g2.setPaint(stepColor);\n g2.fill(rect2D);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27561,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the built in <a href=\"https://docs.oracle.com/javase/7/docs/api/java/awt/GradientPaint.html\" rel=\"nofollow noreferrer\">GradientPaint</a> class. </p>\n\n<pre><code>void Paint(Graphics2D g, Regtangle r, Color c1, Color c2)\n{\n GradientPaint gp = new GradientPaint(0,0,c1,r.getWidth(),r.getHeight(),c2); \n g.setPaint(gp);\n g.fill(rect);\n}\n</code></pre>\n"
},
{
"answer_id": 221413,
"author": "Thibaut Barrère",
"author_id": 20302,
"author_profile": "https://Stackoverflow.com/users/20302",
"pm_score": 0,
"selected": false,
"text": "<p>I've been using <a href=\"http://blog.logeek.fr/2008/10/21/generating-gradients-for-your-css-using-rmagick\" rel=\"nofollow noreferrer\">RMagick for that</a>. If you need to go further the simple gradient, ImageMagick and one of its wrappers (like RMagick or <a href=\"http://sourceforge.net/projects/jmagick/\" rel=\"nofollow noreferrer\">JMagick</a> for Java) could be useful.</p>\n"
},
{
"answer_id": 47324548,
"author": "Holger Brandl",
"author_id": 590437,
"author_profile": "https://Stackoverflow.com/users/590437",
"pm_score": 2,
"selected": false,
"text": "<p>Following up on the execllent answer of David Crow, here's a Kotlin example implementation</p>\n\n<pre><code>fun gradientColor(x: Double, minX: Double, maxX: Double, \n from: Color = Color.RED, to: Color = Color.GREEN): Color {\n val range = maxX - minX\n val p = (x - minX) / range\n\n return Color(\n from.red * p + to.red * (1 - p),\n from.green * p + to.green * (1 - p),\n from.blue * p + to.blue * (1 - p),\n 1.0\n )\n}\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is [this blog entry](http://jtauber.com/blog/2008/05/18/creating_gradients_programmatically_in_python/), but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display. | you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage *p* of the first colour and percentage 1 - *p* of the second:
```
R = firstCol.R * p + secondCol.R * (1 - p)
```
There's [another question](https://stackoverflow.com/questions/25007/conditional-formatting-percentage-to-color-conversion) related to this.
There are other methods of interpolation that sometimes work better. For example, using a [bell-shaped (sigmoidal)](http://en.wikipedia.org/wiki/Sigmoid_function) interpolation function makes the transition smoother.
/EDIT: Oops, you mean using a predefined function. OK, even easier. The blog post you linked now has an example code in Python.
In Java, you could use the [`GradientPaint`](http://docs.oracle.com/javase/7/docs/api/java/awt/GradientPaint.html). |
27,559 | <p>The ones that stick out and make life usefull.</p>
| [
{
"answer_id": 27563,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 1,
"selected": false,
"text": "<p>Here is one for a testClass with Nunit support.</p>\n\n<pre><code>\n Imports Nunit.FrameWork\n\n Namespace $NAMESPACE$\n ''' \n ''' A TestClass\n ''' \n ''' \n _\n Public Class $CLASSNAME$\n\n#Region \" Setup and TearDown \"\n ''' \n ''' Sets up the Tests\n ''' \n ''' \n _\n Public Sub Setup()\n\n End Sub\n\n ''' \n ''' Tears down the test. Is executed after the Test is Completed\n ''' \n ''' \n _\n Public Sub TearDown()\n\n End Sub \n#End Region \n\n#Region \" Tests \"\n ''' \n ''' A Test\n ''' \n ''' \n _\n Public Sub $Test_Name$()\n\n End Sub\n#End Region\n\n End Class\nEnd Namespace</code></pre>\n"
},
{
"answer_id": 9226526,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": 0,
"selected": false,
"text": "<p>MSTest testclass. I like my testclass basic. Not like the one that is created by VS.</p>\n\n<pre><code>Imports Microsoft.VisualStudio.TestTools.UnitTesting\n\n<TestClass()> _\nPublic Class $ClassName$\n $END$\nEnd Class\n</code></pre>\n\n<p><code>$Classname</code> is \"Current file name without extension\" macro.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2936/"
] | The ones that stick out and make life usefull. | Here is one for a testClass with Nunit support.
```
Imports Nunit.FrameWork
Namespace $NAMESPACE$
'''
''' A TestClass
'''
'''
_
Public Class $CLASSNAME$
#Region " Setup and TearDown "
'''
''' Sets up the Tests
'''
'''
_
Public Sub Setup()
End Sub
'''
''' Tears down the test. Is executed after the Test is Completed
'''
'''
_
Public Sub TearDown()
End Sub
#End Region
#Region " Tests "
'''
''' A Test
'''
'''
_
Public Sub $Test_Name$()
End Sub
#End Region
End Class
End Namespace
``` |
27,570 | <p>Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this:</p>
<pre><code>int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");
</code></pre>
<p>I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.</p>
<p><strong>EDIT:</strong> If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it?</p>
| [
{
"answer_id": 27574,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Someone has to do the iterating part.</p>\n\n<p>AFAIK, there is no such method present in .NET already, so I guess that someone has to be you.</p>\n"
},
{
"answer_id": 27584,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 6,
"selected": true,
"text": "<p>You should use the <a href=\"http://msdn.microsoft.com/en-us/library/ms143316.aspx\" rel=\"noreferrer\">Directory.GetFiles(path, searchPattern, SearchOption)</a> overload of Directory.GetFiles().</p>\n\n<p>Path specifies the path, searchPattern specifies your wildcards (e.g., *, *.format) and SearchOption provides the option to include subdirectories.</p>\n\n<p>The Length property of the return array of this search will provide the proper file count for your particular search pattern and option:</p>\n\n<pre><code>string[] files = directory.GetFiles(@\"c:\\windows\\system32\", \"*.dll\", SearchOption.AllDirectories);\n\nreturn files.Length;\n</code></pre>\n\n<p><strong>EDIT:</strong> Alternatively you can use <a href=\"https://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles(v=vs.110).aspx\" rel=\"noreferrer\">Directory.EnumerateFiles method</a></p>\n\n<pre><code>return Directory.EnumerateFiles(@\"c:\\windows\\system32\", \"*.dll\", SearchOption.AllDirectories).Count();\n</code></pre>\n"
},
{
"answer_id": 27585,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 3,
"selected": false,
"text": "<p>You can use this overload of GetFiles:</p>\n<blockquote>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms143316.aspx\" rel=\"noreferrer\"> Directory.GetFiles Method (String,\nString, SearchOption</a>)</p>\n</blockquote>\n<p>and this member of SearchOption:</p>\n<blockquote>\n<p><strong>AllDirectories</strong> - Includes the current\ndirectory and all the subdirectories\nin a search operation. This option\nincludes reparse points like mounted\ndrives and symbolic links in the\nsearch.</p>\n</blockquote>\n<p>GetFiles returns an array of string so you can just get the Length which is the number of files found.</p>\n"
},
{
"answer_id": 27592,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 1,
"selected": false,
"text": "<p>Using recursion your MagicFindFileCount would look like this:</p>\n\n<pre><code>private int MagicFindFileCount( string strDirectory, string strFilter ) {\n int nFiles = Directory.GetFiles( strDirectory, strFilter ).Length;\n\n foreach( String dir in Directory.GetDirectories( strDirectory ) ) {\n nFiles += GetNumberOfFiles(dir, strFilter);\n }\n\n return nFiles;\n }\n</code></pre>\n\n<p>Though <a href=\"https://stackoverflow.com/questions/27570/find-number-of-files-in-all-subdirectories#27584\">Jon's solution</a> might be the better one.</p>\n"
},
{
"answer_id": 5410210,
"author": "Sauleil",
"author_id": 331752,
"author_profile": "https://Stackoverflow.com/users/331752",
"pm_score": 3,
"selected": false,
"text": "<p>I was looking for a more optimized version. Since I haven't found it, I decided to code it and share it here:</p>\n\n<pre><code> public static int GetFileCount(string path, string searchPattern, SearchOption searchOption)\n {\n var fileCount = 0;\n var fileIter = Directory.EnumerateFiles(path, searchPattern, searchOption);\n foreach (var file in fileIter)\n fileCount++;\n return fileCount;\n }\n</code></pre>\n\n<p>All the solutions using the GetFiles/GetDirectories are kind of slow since all those objects need to be created. Using the enumeration, it doesn't create any temporary objects (FileInfo/DirectoryInfo).</p>\n\n<p>see Remarks <a href=\"http://msdn.microsoft.com/en-us/library/dd383571.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/dd383571.aspx</a> for more information</p>\n"
},
{
"answer_id": 7430990,
"author": "Dean",
"author_id": 257810,
"author_profile": "https://Stackoverflow.com/users/257810",
"pm_score": 3,
"selected": false,
"text": "<p>The slickest method woud be to use linq:</p>\n\n<pre><code>var fileCount = (from file in Directory.EnumerateFiles(@\"H:\\iPod_Control\\Music\", \"*.mp3\", SearchOption.AllDirectories)\n select file).Count();\n</code></pre>\n"
},
{
"answer_id": 10193988,
"author": "DraxReaper",
"author_id": 1315396,
"author_profile": "https://Stackoverflow.com/users/1315396",
"pm_score": 1,
"selected": false,
"text": "<p>I have an app which generates counts of the directories and files in a parent directory. Some of the directories contain thousands of sub directories with thousands of files in each. To do this whilst maintaining a responsive ui I do the following ( sending the path to <em>ADirectoryPathWasSelected</em> method):</p>\n\n<pre><code>public class DirectoryFileCounter\n{\n int mDirectoriesToRead = 0;\n\n // Pass this method the parent directory path\n public void ADirectoryPathWasSelected(string path)\n {\n // create a task to do this in the background for responsive ui\n // state is the path\n Task.Factory.StartNew((state) =>\n {\n try\n {\n // Get the first layer of sub directories\n this.AddCountFilesAndFolders(state.ToString())\n\n\n }\n catch // Add Handlers for exceptions\n {}\n }, path));\n }\n\n // This method is called recursively\n private void AddCountFilesAndFolders(string path)\n {\n try\n {\n // Only doing the top directory to prevent an exception from stopping the entire recursion\n var directories = Directory.EnumerateDirectories(path, \"*.*\", SearchOption.TopDirectoryOnly);\n\n // calling class is tracking the count of directories\n this.mDirectoriesToRead += directories.Count();\n\n // get the child directories\n // this uses an extension method to the IEnumerable<V> interface,\n // which will run a function on an object. In this case 'd' is the \n // collection of directories\n directories.ActionOnEnumerable(d => AddCountFilesAndFolders(d));\n }\n catch // Add Handlers for exceptions\n {\n }\n try\n {\n // count the files in the directory\n this.mFilesToRead += Directory.EnumerateFiles(path).Count();\n }\n catch// Add Handlers for exceptions\n { }\n }\n}\n// Extension class\npublic static class Extensions\n{ \n // this runs the supplied method on each object in the supplied enumerable\n public static void ActionOnEnumerable<V>(this IEnumerable<V> nodes,Action<V> doit)\n {\n\n foreach (var node in nodes)\n { \n doit(node);\n }\n }\n}\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257/"
] | Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this:
```
int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");
```
I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.
**EDIT:** If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it? | You should use the [Directory.GetFiles(path, searchPattern, SearchOption)](http://msdn.microsoft.com/en-us/library/ms143316.aspx) overload of Directory.GetFiles().
Path specifies the path, searchPattern specifies your wildcards (e.g., \*, \*.format) and SearchOption provides the option to include subdirectories.
The Length property of the return array of this search will provide the proper file count for your particular search pattern and option:
```
string[] files = directory.GetFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories);
return files.Length;
```
**EDIT:** Alternatively you can use [Directory.EnumerateFiles method](https://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles(v=vs.110).aspx)
```
return Directory.EnumerateFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories).Count();
``` |
27,581 | <p>What issues / pitfalls must be considered when overriding <code>equals</code> and <code>hashCode</code>?</p>
| [
{
"answer_id": 27609,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 12,
"selected": true,
"text": "<h3>The theory (for the language lawyers and the mathematically inclined):</h3>\n\n<p><code>equals()</code> (<a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)\" rel=\"noreferrer\">javadoc</a>) must define an equivalence relation (it must be <em>reflexive</em>, <em>symmetric</em>, and <em>transitive</em>). In addition, it must be <em>consistent</em> (if the objects are not modified, then it must keep returning the same value). Furthermore, <code>o.equals(null)</code> must always return false.</p>\n\n<p><code>hashCode()</code> (<a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()\" rel=\"noreferrer\">javadoc</a>) must also be <em>consistent</em> (if the object is not modified in terms of <code>equals()</code>, it must keep returning the same value).</p>\n\n<p>The <strong>relation</strong> between the two methods is:</p>\n\n<blockquote>\n <p><em>Whenever <code>a.equals(b)</code>, then <code>a.hashCode()</code> must be same as <code>b.hashCode()</code>.</em></p>\n</blockquote>\n\n<h3>In practice:</h3>\n\n<p>If you override one, then you should override the other.</p>\n\n<p>Use the same set of fields that you use to compute <code>equals()</code> to compute <code>hashCode()</code>.</p>\n\n<p>Use the excellent helper classes <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html\" rel=\"noreferrer\">EqualsBuilder</a> and <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html\" rel=\"noreferrer\">HashCodeBuilder</a> from the <a href=\"http://commons.apache.org/lang/\" rel=\"noreferrer\">Apache Commons Lang</a> library. An example:</p>\n\n<pre><code>public class Person {\n private String name;\n private int age;\n // ...\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers\n // if deriving: appendSuper(super.hashCode()).\n append(name).\n append(age).\n toHashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Person))\n return false;\n if (obj == this)\n return true;\n\n Person rhs = (Person) obj;\n return new EqualsBuilder().\n // if deriving: appendSuper(super.equals(obj)).\n append(name, rhs.name).\n append(age, rhs.age).\n isEquals();\n }\n}\n</code></pre>\n\n<h3>Also remember:</h3>\n\n<p>When using a hash-based <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html\" rel=\"noreferrer\">Collection</a> or <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html\" rel=\"noreferrer\">Map</a> such as <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html\" rel=\"noreferrer\">HashSet</a>, <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html\" rel=\"noreferrer\">LinkedHashSet</a>, <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html\" rel=\"noreferrer\">HashMap</a>, <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html\" rel=\"noreferrer\">Hashtable</a>, or <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html\" rel=\"noreferrer\">WeakHashMap</a>, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=29\" rel=\"noreferrer\">which has also other benefits</a>.</p>\n"
},
{
"answer_id": 32223,
"author": "Ran Biron",
"author_id": 931,
"author_profile": "https://Stackoverflow.com/users/931",
"pm_score": 6,
"selected": false,
"text": "<p>A clarification about the <code>obj.getClass() != getClass()</code>.</p>\n\n<p>This statement is the result of <code>equals()</code> being inheritance unfriendly. The JLS (Java language specification) specifies that if <code>A.equals(B) == true</code> then <code>B.equals(A)</code> must also return <code>true</code>. If you omit that statement inheriting classes that override <code>equals()</code> (and change its behavior) will break this specification.</p>\n\n<p>Consider the following example of what happens when the statement is omitted:</p>\n\n<pre><code> class A {\n int field1;\n\n A(int field1) {\n this.field1 = field1;\n }\n\n public boolean equals(Object other) {\n return (other != null && other instanceof A && ((A) other).field1 == field1);\n }\n }\n\n class B extends A {\n int field2;\n\n B(int field1, int field2) {\n super(field1);\n this.field2 = field2;\n }\n\n public boolean equals(Object other) {\n return (other != null && other instanceof B && ((B)other).field2 == field2 && super.equals(other));\n }\n } \n</code></pre>\n\n<p>Doing <code>new A(1).equals(new A(1))</code> Also, <code>new B(1,1).equals(new B(1,1))</code> result give out true, as it should.</p>\n\n<p>This looks all very good, but look what happens if we try to use both classes:</p>\n\n<pre><code>A a = new A(1);\nB b = new B(1,1);\na.equals(b) == true;\nb.equals(a) == false;\n</code></pre>\n\n<p>Obviously, this is wrong.</p>\n\n<p>If you want to ensure the symmetric condition. a=b if b=a and the Liskov substitution principle call <code>super.equals(other)</code> not only in the case of <code>B</code> instance, but check after for <code>A</code> instance:</p>\n\n<pre><code>if (other instanceof B )\n return (other != null && ((B)other).field2 == field2 && super.equals(other)); \nif (other instanceof A) return super.equals(other); \n else return false;\n</code></pre>\n\n<p>Which will output:</p>\n\n<pre><code>a.equals(b) == true;\nb.equals(a) == true;\n</code></pre>\n\n<p>Where, if <code>a</code> is not a reference of <code>B</code>, then it might be a be a reference of class <code>A</code> (because you extend it), in this case you call <code>super.equals()</code> <strong>too</strong>.</p>\n"
},
{
"answer_id": 33010,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": false,
"text": "<p>There are a couple of ways to do your check for class equality before checking member equality, and I think both are useful in the right circumstances.</p>\n\n<ol>\n<li>Use the <code>instanceof</code> operator.</li>\n<li>Use <code>this.getClass().equals(that.getClass())</code>.</li>\n</ol>\n\n<p>I use #1 in a <code>final</code> equals implementation, or when implementing an interface that prescribes an algorithm for equals (like the <code>java.util</code> collection interfaces—the right way to check with with <code>(obj instanceof Set)</code> or whatever interface you're implementing). It's generally a bad choice when equals can be overridden because that breaks the symmetry property.</p>\n\n<p>Option #2 allows the class to be safely extended without overriding equals or breaking symmetry.</p>\n\n<p>If your class is also <code>Comparable</code>, the <code>equals</code> and <code>compareTo</code> methods should be consistent too. Here's a template for the equals method in a <code>Comparable</code> class:</p>\n\n<pre><code>final class MyClass implements Comparable<MyClass>\n{\n\n …\n\n @Override\n public boolean equals(Object obj)\n {\n /* If compareTo and equals aren't final, we should check with getClass instead. */\n if (!(obj instanceof MyClass)) \n return false;\n return compareTo((MyClass) obj) == 0;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 40669,
"author": "Darren Greaves",
"author_id": 151,
"author_profile": "https://Stackoverflow.com/users/151",
"pm_score": 3,
"selected": false,
"text": "<p>One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).<br>\nThese sorts of things are fairly common when doing Hibernate mappings for example.</p>\n\n<p>If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.<br>\nThe simplest solution is to not include the getChildren collection in the methods.</p>\n"
},
{
"answer_id": 55736,
"author": "Kevin Wong",
"author_id": 4792,
"author_profile": "https://Stackoverflow.com/users/4792",
"pm_score": 6,
"selected": false,
"text": "<p>For an inheritance-friendly implementation, check out Tal Cohen's solution, <a href=\"http://www.drdobbs.com/jvm/java-qa-how-do-i-correctly-implement-th/184405053\" rel=\"noreferrer\">How Do I Correctly Implement the equals() Method?</a></p>\n\n<p>Summary:</p>\n\n<p>In his book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201310058\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective Java Programming Language Guide</a> (Addison-Wesley, 2001), Joshua Bloch claims that \"There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract.\" Tal disagrees.</p>\n\n<p>His solution is to implement equals() by calling another nonsymmetric blindlyEquals() both ways. blindlyEquals() is overridden by subclasses, equals() is inherited, and never overridden.</p>\n\n<p>Example:</p>\n\n<pre><code>class Point {\n private int x;\n private int y;\n protected boolean blindlyEquals(Object o) {\n if (!(o instanceof Point))\n return false;\n Point p = (Point)o;\n return (p.x == this.x && p.y == this.y);\n }\n public boolean equals(Object o) {\n return (this.blindlyEquals(o) && o.blindlyEquals(this));\n }\n}\n\nclass ColorPoint extends Point {\n private Color c;\n protected boolean blindlyEquals(Object o) {\n if (!(o instanceof ColorPoint))\n return false;\n ColorPoint cp = (ColorPoint)o;\n return (super.blindlyEquals(cp) && \n cp.color == this.color);\n }\n}\n</code></pre>\n\n<p>Note that equals() must work across inheritance hierarchies if the <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"noreferrer\">Liskov Substitution Principle</a> is to be satisfied.</p>\n"
},
{
"answer_id": 256447,
"author": "Johannes Brodwall",
"author_id": 27658,
"author_profile": "https://Stackoverflow.com/users/27658",
"pm_score": 8,
"selected": false,
"text": "<p>There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!</p>\n\n<p><strong>Lazy loaded objects are subclasses</strong></p>\n\n<p>If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means that<code>this.getClass() == o.getClass()</code> will return <code>false</code>. For example:</p>\n\n<pre><code>Person saved = new Person(\"John Doe\");\nLong key = dao.save(saved);\ndao.flush();\nPerson retrieved = dao.retrieve(key);\nsaved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy\n</code></pre>\n\n<p><em>If you're dealing with an ORM, using <code>o instanceof Person</code> is the only thing that will behave correctly.</em></p>\n\n<p><strong>Lazy loaded objects have null-fields</strong></p>\n\n<p>ORMs usually use the getters to force loading of lazy loaded objects. This means that <code>person.name</code> will be <code>null</code> if <code>person</code> is lazy loaded, even if <code>person.getName()</code> forces loading and returns \"John Doe\". In my experience, this crops up more often in <code>hashCode()</code> and <code>equals()</code>.</p>\n\n<p><em>If you're dealing with an ORM, make sure to always use getters, and never field references in <code>hashCode()</code> and <code>equals()</code>.</em></p>\n\n<p><strong>Saving an object will change its state</strong></p>\n\n<p>Persistent objects often use a <code>id</code> field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in <code>hashCode()</code>. But you can use it in <code>equals()</code>.</p>\n\n<p>A pattern I often use is</p>\n\n<pre><code>if (this.getId() == null) {\n return this == other;\n}\nelse {\n return this.getId().equals(other.getId());\n}\n</code></pre>\n\n<p>But: you cannot include <code>getId()</code> in <code>hashCode()</code>. If you do, when an object is persisted, its <code>hashCode</code> changes. If the object is in a <code>HashSet</code>, you'll \"never\" find it again.</p>\n\n<p>In my <code>Person</code> example, I probably would use <code>getName()</code> for <code>hashCode</code> and <code>getId()</code> plus <code>getName()</code> (just for paranoia) for <code>equals()</code>. It's okay if there are some risk of \"collisions\" for <code>hashCode()</code>, but never okay for <code>equals()</code>.</p>\n\n<p><em><code>hashCode()</code> should use the non-changing subset of properties from <code>equals()</code></em></p>\n"
},
{
"answer_id": 596866,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "<p>For equals, look into <strong><a href=\"http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html\" rel=\"noreferrer\">Secrets of Equals</a></strong> by <a href=\"http://www.angelikalanger.com/\" rel=\"noreferrer\">Angelika Langer</a>. I love it very much. She's also a great FAQ about <strong><a href=\"http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html\" rel=\"noreferrer\">Generics in Java</a></strong>. View her other articles <a href=\"http://www.angelikalanger.com/Articles/Topics.html#JAVA\" rel=\"noreferrer\">here</a> (scroll down to \"Core Java\"), where she also goes on with Part-2 and \"mixed type comparison\". Have fun reading them!</p>\n"
},
{
"answer_id": 14827378,
"author": "Eugene",
"author_id": 1059372,
"author_profile": "https://Stackoverflow.com/users/1059372",
"pm_score": 5,
"selected": false,
"text": "<p>Still amazed that none recommended the guava library for this. </p>\n\n<pre><code> //Sample taken from a current working project of mine just to illustrate the idea\n\n @Override\n public int hashCode(){\n return Objects.hashCode(this.getDate(), this.datePattern);\n }\n\n @Override\n public boolean equals(Object obj){\n if ( ! obj instanceof DateAndPattern ) {\n return false;\n }\n return Objects.equal(((DateAndPattern)obj).getDate(), this.getDate())\n && Objects.equal(((DateAndPattern)obj).getDate(), this.getDatePattern());\n }\n</code></pre>\n"
},
{
"answer_id": 15599729,
"author": "Khaled.K",
"author_id": 2128327,
"author_profile": "https://Stackoverflow.com/users/2128327",
"pm_score": 3,
"selected": false,
"text": "<p>Logically we have:</p>\n\n<p><code>a.getClass().equals(b.getClass()) && a.equals(b)</code> ⇒ <code>a.hashCode() == b.hashCode()</code></p>\n\n<p>But <strong>not</strong> vice-versa!</p>\n"
},
{
"answer_id": 19563996,
"author": "rohan kamat",
"author_id": 2335562,
"author_profile": "https://Stackoverflow.com/users/2335562",
"pm_score": 4,
"selected": false,
"text": "<p>equals() method is used to determine the equality of two objects.</p>\n\n<p>as int value of 10 is always equal to 10. But this equals() method is about equality of two objects. When we say object, it will have properties. To decide about equality those properties are considered. It is not necessary that all properties must be taken into account to determine the equality and with respect to the class definition and context it can be decided. Then the equals() method can be overridden.</p>\n\n<p>we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.</p>\n\n<p>Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it.</p>\n\n<pre><code>public class Tiger {\n private String color;\n private String stripePattern;\n private int height;\n\n @Override\n public boolean equals(Object object) {\n boolean result = false;\n if (object == null || object.getClass() != getClass()) {\n result = false;\n } else {\n Tiger tiger = (Tiger) object;\n if (this.color == tiger.getColor()\n && this.stripePattern == tiger.getStripePattern()) {\n result = true;\n }\n }\n return result;\n }\n\n // just omitted null checks\n @Override\n public int hashCode() {\n int hash = 3;\n hash = 7 * hash + this.color.hashCode();\n hash = 7 * hash + this.stripePattern.hashCode();\n return hash;\n }\n\n public static void main(String args[]) {\n Tiger bengalTiger1 = new Tiger(\"Yellow\", \"Dense\", 3);\n Tiger bengalTiger2 = new Tiger(\"Yellow\", \"Dense\", 2);\n Tiger siberianTiger = new Tiger(\"White\", \"Sparse\", 4);\n System.out.println(\"bengalTiger1 and bengalTiger2: \"\n + bengalTiger1.equals(bengalTiger2));\n System.out.println(\"bengalTiger1 and siberianTiger: \"\n + bengalTiger1.equals(siberianTiger));\n\n System.out.println(\"bengalTiger1 hashCode: \" + bengalTiger1.hashCode());\n System.out.println(\"bengalTiger2 hashCode: \" + bengalTiger2.hashCode());\n System.out.println(\"siberianTiger hashCode: \"\n + siberianTiger.hashCode());\n }\n\n public String getColor() {\n return color;\n }\n\n public String getStripePattern() {\n return stripePattern;\n }\n\n public Tiger(String color, String stripePattern, int height) {\n this.color = color;\n this.stripePattern = stripePattern;\n this.height = height;\n\n }\n}\n</code></pre>\n\n<p>Example Code Output:</p>\n\n<pre><code>bengalTiger1 and bengalTiger2: true \nbengalTiger1 and siberianTiger: false \nbengalTiger1 hashCode: 1398212510 \nbengalTiger2 hashCode: 1398212510 \nsiberianTiger hashCode: –1227465966\n</code></pre>\n"
},
{
"answer_id": 20697433,
"author": "Luna Kong",
"author_id": 2038772,
"author_profile": "https://Stackoverflow.com/users/2038772",
"pm_score": 5,
"selected": false,
"text": "<p>There are two methods in super class as java.lang.Object. We need to override them to custom object.</p>\n\n<pre><code>public boolean equals(Object obj)\npublic int hashCode()\n</code></pre>\n\n<p>Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.</p>\n\n<pre><code>public class Test\n{\n private int num;\n private String data;\n public boolean equals(Object obj)\n {\n if(this == obj)\n return true;\n if((obj == null) || (obj.getClass() != this.getClass()))\n return false;\n // object must be Test at this point\n Test test = (Test)obj;\n return num == test.num &&\n (data == test.data || (data != null && data.equals(test.data)));\n }\n\n public int hashCode()\n {\n int hash = 7;\n hash = 31 * hash + num;\n hash = 31 * hash + (null == data ? 0 : data.hashCode());\n return hash;\n }\n\n // other methods\n}\n</code></pre>\n\n<p>If you want get more, please check this link as <a href=\"http://www.javaranch.com/journal/2002/10/equalhash.html\" rel=\"noreferrer\">http://www.javaranch.com/journal/2002/10/equalhash.html</a></p>\n\n<p>This is another example,\n<a href=\"http://java67.blogspot.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html\" rel=\"noreferrer\">http://java67.blogspot.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html</a></p>\n\n<p>Have Fun! @.@</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | What issues / pitfalls must be considered when overriding `equals` and `hashCode`? | ### The theory (for the language lawyers and the mathematically inclined):
`equals()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))) must define an equivalence relation (it must be *reflexive*, *symmetric*, and *transitive*). In addition, it must be *consistent* (if the objects are not modified, then it must keep returning the same value). Furthermore, `o.equals(null)` must always return false.
`hashCode()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode())) must also be *consistent* (if the object is not modified in terms of `equals()`, it must keep returning the same value).
The **relation** between the two methods is:
>
> *Whenever `a.equals(b)`, then `a.hashCode()` must be same as `b.hashCode()`.*
>
>
>
### In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute `equals()` to compute `hashCode()`.
Use the excellent helper classes [EqualsBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html) and [HashCodeBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html) from the [Apache Commons Lang](http://commons.apache.org/lang/) library. An example:
```
public class Person {
private String name;
private int age;
// ...
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
```
### Also remember:
When using a hash-based [Collection](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html) or [Map](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html) such as [HashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html), [LinkedHashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html), [HashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html), [Hashtable](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html), or [WeakHashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html), make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, [which has also other benefits](http://www.javapractices.com/topic/TopicAction.do?Id=29). |
27,599 | <p>(<strong>Updated a little</strong>)</p>
<p>I'm not very experienced with internationalization using PHP, it must be said, and a deal of searching didn't really provide the answers I was looking for.</p>
<p>I'm in need of working out a reliable way to convert only 'relevant' text to Unicode to send in an SMS message, using PHP (just temporarily, whilst service is rewritten using C#) - obviously, messages sent at the moment are sent as plain text.</p>
<p>I could conceivably convert everything to the Unicode charset (as opposed to using the standard GSM charset), but that would mean that <em>all</em> messages would be limited to 70 characters (instead of 160).</p>
<p>So, I guess my real question is: <em>what is the most reliable way to detect the requirement for a message to be Unicode-encoded, so I only have to do it when it's</em> <strong><em>absolutely necessary</em></strong> <em>(e.g. for non-Latin-language characters)?</em></p>
<h2>Added Info:</h2>
<p>Okay, so I've spent the morning working on this, and I'm still no further on than when I started (certainly due to my complete lack of competency when it comes to charset conversion). So here's the revised scenario:</p>
<p>I have text SMS messages coming from an external source, this external source provides the responses to me in plain text + Unicode slash-escaped characters. E.g. the 'displayed' text:</p>
<blockquote>
<p>Let's test öäü éàè אין תמיכה בעברית</p>
</blockquote>
<p>Returns:</p>
<blockquote>
<p>Let's test \u00f6\u00e4\u00fc \u00e9\u00e0\u00e8 \u05d0\u05d9\u05df \u05ea\u05de\u05d9\u05db\u05d4 \u05d1\u05e2\u05d1\u05e8\u05d9\u05ea</p>
</blockquote>
<p>Now, I can send on to my SMS provider in plaintext, GSM 03.38 or Unicode. Obviously, sending the above as plaintext results in a lot of missing characters (they're replaced by spaces by my provider) - I need to adopt relating to what content there is. What I want to <em>do</em> with this is the following:</p>
<ol>
<li><p>If all text is within the <a href="http://www.dreamfabric.com/sms/default_alphabet.html" rel="nofollow noreferrer">GSM 03.38 codepage</a>, send it as-is. (All but the Hebrew characters above fit into this category, but need to be converted.)</p></li>
<li><p>Otherwise, convert it to Unicode, and send it over multiple messages (as the Unicode limit is 70 chars not 160 for an SMS).</p></li>
</ol>
<p>As I said above, I'm stumped on doing this in PHP (C# wasn't much of an issue due to some simple conversion functions built-in), but it's quite probable I'm just missing the obvious, here. I couldn't find any pre-made conversion classes for 7-bit encoding in PHP, either - and my attempts to convert the string myself and send it on seemed futile.</p>
<p><strong>Any help would be greatly appreciated.</strong></p>
| [
{
"answer_id": 27603,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>PHP6 will have better unicode support but there are a few functions you can use.</p>\n\n<p>My first thought was <a href=\"http://php.net/manual/en/function.mb-convert-encoding.php\" rel=\"nofollow noreferrer\"><code>mb_convert_encoding</code></a> but as you said this will shorten messages to 70 chars - so perhaps you can use this in conjunction with <a href=\"http://php.net/manual/en/function.mb-detect-encoding.php\" rel=\"nofollow noreferrer\"><code>mb_detect_encoding</code></a>?</p>\n\n<p>See: <a href=\"http://php.net/manual/en/ref.mbstring.php\" rel=\"nofollow noreferrer\">Multibyte Functions</a></p>\n"
},
{
"answer_id": 27623,
"author": "Magnus Westin",
"author_id": 2957,
"author_profile": "https://Stackoverflow.com/users/2957",
"pm_score": 2,
"selected": false,
"text": "<p>I know this isnt php code, but I think it might help anyway. This is how I do it in an app I wrote to detect if its possible to send as GSM 03.38 (you could do something similar for plain text). It has two translation tables, one for normal GSM and one for the extended. And then a function that loops through all characters checking if it can be converted.</p>\n\n<pre><code>#define UCS2_TO_GSM_LOOKUP_TABLE_SIZE 0x100\n#define NON_GSM 0x80 \n#define UCS2_GCL_RANGE 24\n#define UCS2_GREEK_CAPITAL_LETTER_ALPHA 0x0391\n#define EXTEND 0x001B\n// note that the ` character is mapped to ' so that all characters that can be typed on\n// a standard north american keyboard can be converted to the GSM default character set\nstatic unsigned char Ucs2ToGsm[UCS2_TO_GSM_LOOKUP_TABLE_SIZE] =\n{ /*+0x0 +0x1 +0x2 +0x3 +0x4 +0x5 +0x6 +0x7*/\n/*0x00*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x08*/ NON_GSM, NON_GSM, 0x0a, NON_GSM, NON_GSM, 0x0d, NON_GSM, NON_GSM,\n/*0x10*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x18*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x20*/ 0x20, 0x21, 0x22, 0x23, 0x02, 0x25, 0x26, 0x27,\n/*0x28*/ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,\n/*0x30*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,\n/*0x38*/ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,\n/*0x40*/ 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,\n/*0x48*/ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,\n/*0x50*/ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,\n/*0x58*/ 0x58, 0x59, 0x5a, EXTEND, EXTEND, EXTEND, EXTEND, 0x11,\n/*0x60*/ 0x27, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,\n/*0x68*/ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,\n/*0x70*/ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,\n/*0x78*/ 0x78, 0x79, 0x7a, EXTEND, EXTEND, EXTEND, EXTEND, NON_GSM,\n/*0x80*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x88*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x90*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x98*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0xa0*/ NON_GSM, 0x40, NON_GSM, 0x01, 0x24, 0x03, NON_GSM, 0x5f,\n/*0xa8*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0xb0*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0xb8*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, 0x60,\n/*0xc0*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, 0x5b, 0x0e, 0x1c, 0x09,\n/*0xc8*/ NON_GSM, 0x1f, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, 0x60,\n/*0xd0*/ NON_GSM, 0x5d, NON_GSM, NON_GSM, NON_GSM, NON_GSM, 0x5c, NON_GSM,\n/*0xd8*/ 0x0b, NON_GSM, NON_GSM, NON_GSM, 0x5e, NON_GSM, NON_GSM, 0x1e,\n/*0xe0*/ 0x7f, NON_GSM, NON_GSM, NON_GSM, 0x7b, 0x0f, 0x1d, NON_GSM,\n/*0xe8*/ 0x04, 0x05, NON_GSM, NON_GSM, 0x07, NON_GSM, NON_GSM, NON_GSM,\n/*0xf0*/ NON_GSM, 0x7d, 0x08, NON_GSM, NON_GSM, NON_GSM, 0x7c, NON_GSM,\n/*0xf8*/ 0x0c, 0x06, NON_GSM, NON_GSM, 0x7e, NON_GSM, NON_GSM, NON_GSM\n};\n\nstatic unsigned char Ucs2GclToGsm[UCS2_GCL_RANGE + 1] =\n{\n/*0x0391*/ 0x41, // Alpha A\n/*0x0392*/ 0x42, // Beta B\n/*0x0393*/ 0x13, // Gamma\n/*0x0394*/ 0x10, // Delta\n/*0x0395*/ 0x45, // Epsilon E\n/*0x0396*/ 0x5A, // Zeta Z\n/*0x0397*/ 0x48, // Eta H\n/*0x0398*/ 0x19, // Theta\n/*0x0399*/ 0x49, // Iota I\n/*0x039a*/ 0x4B, // Kappa K\n/*0x039b*/ 0x14, // Lambda\n/*0x039c*/ 0x4D, // Mu M\n/*0x039d*/ 0x4E, // Nu N\n/*0x039e*/ 0x1A, // Xi\n/*0x039f*/ 0x4F, // Omicron O\n/*0x03a0*/ 0X16, // Pi\n/*0x03a1*/ 0x50, // Rho P\n/*0x03a2*/ NON_GSM,\n/*0x03a3*/ 0x18, // Sigma\n/*0x03a4*/ 0x54, // Tau T\n/*0x03a5*/ 0x59, // Upsilon Y\n/*0x03a6*/ 0x12, // Phi \n/*0x03a7*/ 0x58, // Chi X\n/*0x03a8*/ 0x17, // Psi\n/*0x03a9*/ 0x15 // Omega\n};\n\nbool Gsm0338Encoding::IsNotGSM( wchar_t szUnicodeChar )\n{\n bool result = true;\n if( szUnicodeChar < UCS2_TO_GSM_LOOKUP_TABLE_SIZE )\n {\n result = ( Ucs2ToGsm[szUnicodeChar] == NON_GSM );\n }\n else if( (szUnicodeChar >= UCS2_GREEK_CAPITAL_LETTER_ALPHA) &&\n (szUnicodeChar <= (UCS2_GREEK_CAPITAL_LETTER_ALPHA + UCS2_GCL_RANGE)) )\n {\n result = ( Ucs2GclToGsm[szUnicodeChar - UCS2_GREEK_CAPITAL_LETTER_ALPHA] == NON_GSM );\n }\n else if( szUnicodeChar == 0x20AC ) // €\n {\n result = false;\n }\n return result;\n}\n\nbool Gsm0338Encoding::IsGSM( const std::wstring& str )\n{\n bool result = true;\n if( std::find_if( str.begin(), str.end(), IsNotGSM ) != str.end() )\n {\n result = false;\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 68096,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>To deal with it conceptually before getting into mechanisms, and apologies if any of this is obvious, a string can be defined as a sequence of Unicode characters, Unicode being a database that gives an id number known as a code point to every character you might need to work with. GSM-338 contains a subset of the Unicode characters, so what you're doing is extracting a set of codepoints from your string, and checking to see if that set is contained in GSM-338.</p>\n\n<pre><code>// second column of http://unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT\n$gsm338_codepoints = array(0x0040, 0x0000, ..., 0x00fc, 0x00e0)\n$can_use_gsm338 = true;\nforeach(codepoints($mystring) as $codepoint){\n if(!in_array($codepoint, $gsm338_codepoints)){\n $can_use_gsm338 = false;\n break;\n }\n}\n</code></pre>\n\n<p>That leaves the definition of the function codepoints($string), which isn't built in to PHP. PHP understands a string to be a sequence of bytes rather than a sequence of Unicode characters. The best way of bridging the gap is to get your strings into UTF8 as quickly as you can and keep them in UTF8 as long as you can - you'll have to use other encodings when dealing with external systems, but isolate the conversion to the interface to that system and deal only with utf8 internally. </p>\n\n<p>The functions you need to convert between php strings in utf8 and sequences of codepoints can be found at <a href=\"http://hsivonen.iki.fi/php-utf8/\" rel=\"noreferrer\">http://hsivonen.iki.fi/php-utf8/</a> , so that's your codepoints() function.</p>\n\n<p>If you're taking data from an external source that gives you Unicode slash-escaped characters (\"Let's test \\u00f6\\u00e4\\u00fc...\"), that string escape format should be converted to utf8. I don't know offhand of a function to do this, if one can't be found, it's a matter of string/regex processing + the use of the hsivonen.iki.fi functions, for example when you hit \\u00f6, replace it with the utf8 representation of the codepoint 0xf6.</p>\n"
},
{
"answer_id": 1441442,
"author": "jW.",
"author_id": 8880,
"author_profile": "https://Stackoverflow.com/users/8880",
"pm_score": 3,
"selected": false,
"text": "<p>Although this is an old thread I recently had to solve a very similar problem and wanted to post my answer. The PHP code is somewhat simple. It starts with a painstakingly large array of GSM valid character codes in an array, then simply checks if the current character is in that array using the <a href=\"http://us2.php.net/ord\" rel=\"noreferrer\">ord($string) function</a> which returns the ascii value of the first character of the string passed. Here is the code I use to validate if a string is GSM worth.</p>\n\n<pre><code> $valid_gsm_keycodes = Array( \n 0x0040, 0x0394, 0x0020, 0x0030, 0x00a1, 0x0050, 0x00bf, 0x0070,\n 0x00a3, 0x005f, 0x0021, 0x0031, 0x0041, 0x0051, 0x0061, 0x0071,\n 0x0024, 0x03a6, 0x0022, 0x0032, 0x0042, 0x0052, 0x0062, 0x0072,\n 0x00a5, 0x0393, 0x0023, 0x0033, 0x0043, 0x0053, 0x0063, 0x0073,\n 0x00e8, 0x039b, 0x00a4, 0x0034, 0x0035, 0x0044, 0x0054, 0x0064, 0x0074,\n 0x00e9, 0x03a9, 0x0025, 0x0045, 0x0045, 0x0055, 0x0065, 0x0075,\n 0x00f9, 0x03a0, 0x0026, 0x0036, 0x0046, 0x0056, 0x0066, 0x0076,\n 0x00ec, 0x03a8, 0x0027, 0x0037, 0x0047, 0x0057, 0x0067, 0x0077, \n 0x00f2, 0x03a3, 0x0028, 0x0038, 0x0048, 0x0058, 0x0068, 0x0078,\n 0x00c7, 0x0398, 0x0029, 0x0039, 0x0049, 0x0059, 0x0069, 0x0079,\n 0x000a, 0x039e, 0x002a, 0x003a, 0x004a, 0x005a, 0x006a, 0x007a,\n 0x00d8, 0x001b, 0x002b, 0x003b, 0x004b, 0x00c4, 0x006b, 0x00e4,\n 0x00f8, 0x00c6, 0x002c, 0x003c, 0x004c, 0x00d6, 0x006c, 0x00f6,\n 0x000d, 0x00e6, 0x002d, 0x003d, 0x004d, 0x00d1, 0x006d, 0x00f1,\n 0x00c5, 0x00df, 0x002e, 0x003e, 0x004e, 0x00dc, 0x006e, 0x00fc,\n 0x00e5, 0x00c9, 0x002f, 0x003f, 0x004f, 0x00a7, 0x006f, 0x00e0 );\n\n\n for($i = 0; $i < strlen($string); $i++) {\n if(!in_array($string[$i], $valid_gsm_keycodes)) return false;\n }\n\n return true;\n</code></pre>\n"
},
{
"answer_id": 12196609,
"author": "Sergey Shuchkin",
"author_id": 594867,
"author_profile": "https://Stackoverflow.com/users/594867",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function is_gsm0338( $utf8_string ) {\n $gsm0338 = array(\n '@','Δ',' ','0','¡','P','¿','p',\n '£','_','!','1','A','Q','a','q',\n '$','Φ','\"','2','B','R','b','r',\n '¥','Γ','#','3','C','S','c','s',\n 'è','Λ','¤','4','D','T','d','t',\n 'é','Ω','%','5','E','U','e','u',\n 'ù','Π','&','6','F','V','f','v',\n 'ì','Ψ','\\'','7','G','W','g','w',\n 'ò','Σ','(','8','H','X','h','x',\n 'Ç','Θ',')','9','I','Y','i','y',\n \"\\n\",'Ξ','*',':','J','Z','j','z',\n 'Ø',\"\\x1B\",'+',';','K','Ä','k','ä',\n 'ø','Æ',',','<','L','Ö','l','ö',\n \"\\r\",'æ','-','=','M','Ñ','m','ñ',\n 'Å','ß','.','>','N','Ü','n','ü',\n 'å','É','/','?','O','§','o','à'\n );\n $len = mb_strlen( $utf8_string, 'UTF-8');\n\n for( $i=0; $i < $len; $i++)\n if (!in_array(mb_substr($utf8_string,$i,1,'UTF-8'), $gsm0338))\n return false;\n\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 13469742,
"author": "Enyby",
"author_id": 1504248,
"author_profile": "https://Stackoverflow.com/users/1504248",
"pm_score": 0,
"selected": false,
"text": "<pre><code>preg_match('/^[\\x0A\\x0C\\x0D\\x20-\\x5F\\x61-\\x7E\\xA0\\xA1\\xA3-\\xA5\\xA7'.\n '\\xBF\\xC4-\\xC6\\xC9\\xD1\\xD6\\xD8\\xDC\\xDF\\xE0\\xE4-\\xE9\\xEC\\xF1'.\n '\\xF2\\xF6\\xF8\\xF9\\xFC'.\n json_decode('\"\\u0393\\u0394\\u0398\\u039B\\u039E\\u03A0\\u03A3\\u03A6\\u03A8\\u03A9\\u20AC\"').\n ']*$/u', $text)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>preg_match('/^[\\x0A\\x0C\\x0D\\x20-\\x5F\\x61-\\x7E\\xA0\\xA1\\xA3-\\xA5\\xA7\\xBF\\xC4-\\xC6\\xC9\\xD1\\xD6\\xD8\\xDC\\xDF\\xE0\\xE4-\\xE9\\xEC\\xF1\\xF2\\xF6\\xF8\\xF9\\xFCΓΔΘΛΞΠΣΦΨΩ€]*$/u', $text)\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951/"
] | (**Updated a little**)
I'm not very experienced with internationalization using PHP, it must be said, and a deal of searching didn't really provide the answers I was looking for.
I'm in need of working out a reliable way to convert only 'relevant' text to Unicode to send in an SMS message, using PHP (just temporarily, whilst service is rewritten using C#) - obviously, messages sent at the moment are sent as plain text.
I could conceivably convert everything to the Unicode charset (as opposed to using the standard GSM charset), but that would mean that *all* messages would be limited to 70 characters (instead of 160).
So, I guess my real question is: *what is the most reliable way to detect the requirement for a message to be Unicode-encoded, so I only have to do it when it's* ***absolutely necessary*** *(e.g. for non-Latin-language characters)?*
Added Info:
-----------
Okay, so I've spent the morning working on this, and I'm still no further on than when I started (certainly due to my complete lack of competency when it comes to charset conversion). So here's the revised scenario:
I have text SMS messages coming from an external source, this external source provides the responses to me in plain text + Unicode slash-escaped characters. E.g. the 'displayed' text:
>
> Let's test öäü éàè אין תמיכה בעברית
>
>
>
Returns:
>
> Let's test \u00f6\u00e4\u00fc \u00e9\u00e0\u00e8 \u05d0\u05d9\u05df \u05ea\u05de\u05d9\u05db\u05d4 \u05d1\u05e2\u05d1\u05e8\u05d9\u05ea
>
>
>
Now, I can send on to my SMS provider in plaintext, GSM 03.38 or Unicode. Obviously, sending the above as plaintext results in a lot of missing characters (they're replaced by spaces by my provider) - I need to adopt relating to what content there is. What I want to *do* with this is the following:
1. If all text is within the [GSM 03.38 codepage](http://www.dreamfabric.com/sms/default_alphabet.html), send it as-is. (All but the Hebrew characters above fit into this category, but need to be converted.)
2. Otherwise, convert it to Unicode, and send it over multiple messages (as the Unicode limit is 70 chars not 160 for an SMS).
As I said above, I'm stumped on doing this in PHP (C# wasn't much of an issue due to some simple conversion functions built-in), but it's quite probable I'm just missing the obvious, here. I couldn't find any pre-made conversion classes for 7-bit encoding in PHP, either - and my attempts to convert the string myself and send it on seemed futile.
**Any help would be greatly appreciated.** | To deal with it conceptually before getting into mechanisms, and apologies if any of this is obvious, a string can be defined as a sequence of Unicode characters, Unicode being a database that gives an id number known as a code point to every character you might need to work with. GSM-338 contains a subset of the Unicode characters, so what you're doing is extracting a set of codepoints from your string, and checking to see if that set is contained in GSM-338.
```
// second column of http://unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT
$gsm338_codepoints = array(0x0040, 0x0000, ..., 0x00fc, 0x00e0)
$can_use_gsm338 = true;
foreach(codepoints($mystring) as $codepoint){
if(!in_array($codepoint, $gsm338_codepoints)){
$can_use_gsm338 = false;
break;
}
}
```
That leaves the definition of the function codepoints($string), which isn't built in to PHP. PHP understands a string to be a sequence of bytes rather than a sequence of Unicode characters. The best way of bridging the gap is to get your strings into UTF8 as quickly as you can and keep them in UTF8 as long as you can - you'll have to use other encodings when dealing with external systems, but isolate the conversion to the interface to that system and deal only with utf8 internally.
The functions you need to convert between php strings in utf8 and sequences of codepoints can be found at <http://hsivonen.iki.fi/php-utf8/> , so that's your codepoints() function.
If you're taking data from an external source that gives you Unicode slash-escaped characters ("Let's test \u00f6\u00e4\u00fc..."), that string escape format should be converted to utf8. I don't know offhand of a function to do this, if one can't be found, it's a matter of string/regex processing + the use of the hsivonen.iki.fi functions, for example when you hit \u00f6, replace it with the utf8 representation of the codepoint 0xf6. |
27,607 | <p>Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:</p>
<pre><code>find_if(serverNames.begin(), serverNames.end(), ContactServer());
</code></pre>
<p>Where ContactServer is a predicate function object.<br>
On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (<em>i.e.</em> the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.</p>
<p>What do you say?</p>
| [
{
"answer_id": 27614,
"author": "Magnus Hoff",
"author_id": 2971,
"author_profile": "https://Stackoverflow.com/users/2971",
"pm_score": 2,
"selected": false,
"text": "<p>I think I would go for it.</p>\n\n<p>The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like \"Find the first server I can contact\", which makes perfect sense.</p>\n\n<p>You might want to rename <code>ContactServer</code> to indicate that it is a predicate; <code>CanContactServer</code>? (But then people would complain about hidden side effects. Hmm...)</p>\n"
},
{
"answer_id": 27619,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>Isn't that what <code>find_if</code> is for?</p>\n\n<p>Note though, that it will find <em>all</em> the servers, if you iterate over the iterator - but you aren't going to do that (according to OP).</p>\n"
},
{
"answer_id": 27620,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>However, the same result will be returned regardless of which copy of the predicate is used (i.e. the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.</p>\n</blockquote>\n\n<p>So where's the problem? Function objects don't necessarily have to be stateful. It's actually best practice to use function objects instead of function pointers in such situations because compilers are better at inlining them. In your case, the instantiation and call of the function object may have no overhead at all since <code>find_if</code> is a function template and the compiler will generate an own version for your functor.</p>\n\n<p>On the other hand, using a function pointer would incur an indirection.</p>\n"
},
{
"answer_id": 39252,
"author": "Xavier Nodet",
"author_id": 4177,
"author_profile": "https://Stackoverflow.com/users/4177",
"pm_score": 0,
"selected": false,
"text": "<p>In the <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2723.pdf\" rel=\"nofollow noreferrer\">upcoming version of the C++ standard</a>, I could not find any explicit restriction with respect to the fact that a predicate should always return the same value for the same input. I looked into section 25 (paragraphs 7 to 10).</p>\n\n<p>Methods returning values that may change from one call to another, as in your case, should be volatile (from 7.1.6.1/11: \"volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation\"). </p>\n\n<p>Predicates \"shall not apply any non-constant function through the dereferenced iterators\" (paragraphs 7 and 8). I take this to mean that they are not required to use non-volatile methods, and that your use-case is thus ok with respect to the standard.</p>\n\n<p>If the wording was \"predicates should apply const functions...\" or something like that, then I would have concluded that 'const volatile' functions were not ok. But this is not the case. </p>\n"
},
{
"answer_id": 103138,
"author": "Timmie Smith",
"author_id": 8405,
"author_profile": "https://Stackoverflow.com/users/8405",
"pm_score": 0,
"selected": false,
"text": "<p>std::for_each might be a better candidate for this.</p>\n\n<p>1) After being copied in the same function object is used on each element and after all elements are processed a copy of the potentially updated function object is returned to the user.</p>\n\n<p>2) It would improve the readability of the call in my opinion as well.</p>\n\n<p>The function object and the for_each call would look something like:</p>\n\n<pre><code>\nstruct AttemptServerContact {\n bool server_contacted;\n std::string active_server; // name of server contacted\n\n AttemptServerContact() : server_contacted(false) {}\n\n void operator()(Server& s) {\n if (!server_contacted) {\n //attempt to contact s\n //if successful, set server_contacted and active_server\n }\n }\n};\n\nAttemptServerContact func;\nfunc = std::for_each(serverNames.begin(), serverNames.end(), func);\n//func.server_contacted and func.active_server contain server information.\n</code></pre>\n"
},
{
"answer_id": 103164,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 0,
"selected": false,
"text": "<p>find_if appears to be the right choice here. The predicate isn't stateful in this situation.</p>\n"
},
{
"answer_id": 113129,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 2,
"selected": false,
"text": "<p>This is exactly what the STL algorithms are for. This is not an abuse at all. Furthermore, it is very readable. Redirect to null anyone who tells you otherwise.</p>\n"
},
{
"answer_id": 10757848,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 2,
"selected": false,
"text": "<p>In my opinion, this use of <code>std::find_if</code> is a bit misleading. When I read this piece of code, I don't expect any side effects to occur, I just expect a server name to be found. The fact that the result of <code>find_if</code> is discarded would also make me wonder if the code is really correct. Perhaps another name for the predicate would make the intent clearer, but I think the problem is more fundamental.</p>\n\n<p>For most people, <code>find_if</code> is a <strong>querying</strong> algorithm, not a <strong>modifying</strong> algorithm. Even though you are not actually modifying the values iterated upon, you are modifying the global state of your application (in this case, you are even possibly modifying the state of distant servers).</p>\n\n<p>In such a case, I would probably stick with a manual loop, especially now that C++11 introduced range-based for loops:</p>\n\n<pre><code>for (std::string const & name : serverNames)\n{\n if (ContactServer(name)) break;\n}\n</code></pre>\n\n<p>Another solution would be to encapsulate this in a function with a name conveying more clearly the intent, such as <code>apply_until</code> or something like that:</p>\n\n<pre><code>template <typename InputIterator, typename Function>\nvoid apply_until(InputIterator first, InputIterator last, Function f)\n{\n std::find_if(first, last, f);\n // or\n // while (first != last)\n // {\n // if (f(*first)) break;\n //\n // ++first;\n // }\n}\n}\n</code></pre>\n\n<p>But perhaps I'm being over-puristic :)!</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2150/"
] | Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find\_if algorithm in the following way:
```
find_if(serverNames.begin(), serverNames.end(), ContactServer());
```
Where ContactServer is a predicate function object.
On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (*i.e.* the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.
What do you say? | I think I would go for it.
The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like "Find the first server I can contact", which makes perfect sense.
You might want to rename `ContactServer` to indicate that it is a predicate; `CanContactServer`? (But then people would complain about hidden side effects. Hmm...) |
27,610 | <p>I want to introduce some tracing to a C# application I am writing. Sadly, I can never really remember how it works and would like a tutorial with reference qualities to check up on every now and then. It should include:</p>
<ul>
<li>App.config / Web.config stuff to add for registering TraceListeners</li>
<li>how to set it up in the calling application</li>
</ul>
<p>Do you know the über tutorial that we should link to?</p>
<hr/>
<p>Glenn Slaven pointed me in the right direction. Add this to your App.config/Web.config inside <code><configuration/></code>:</p>
<pre><code><system.diagnostics>
<trace autoflush="true">
<listeners>
<add type="System.Diagnostics.TextWriterTraceListener" name="TextWriter"
initializeData="trace.log" />
</listeners>
</trace>
</system.diagnostics>
</code></pre>
<p>This will add a <code>TextWriterTraceListener</code> that will catch everything you send to with <code>Trace.WriteLine</code>, etc.</p>
<p>@DanEsparza pointed out that you should use <code>Trace.TraceInformation</code>, <code>Trace.TraceWarning</code> and <code>Trace.TraceError</code> instead of <code>Trace.WriteLine</code>, as they allow you to format messages the same way as <code>string.Format</code>.</p>
<p><strong>Tip:</strong> If you don't add any listeners, then you can still see the trace output with the Sysinternals program <a href="https://learn.microsoft.com/en-us/sysinternals/downloads/debugview" rel="nofollow noreferrer">DebugView</a> (<code>Dbgview.exe</code>):</p>
| [
{
"answer_id": 27659,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "<p>DotNetCoders has a starter article on it: <a href=\"http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50\" rel=\"nofollow noreferrer\">http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50</a>. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).</p>\n<p>There's another article on CodeProject: <em><a href=\"http://www.codeproject.com/KB/trace/debugtreatise.aspx\" rel=\"nofollow noreferrer\">A Treatise on Using Debug and Trace classes, including Exception Handling</a></em>, but it's the same age.</p>\n<p>CodeGuru has another article on custom TraceListeners: <em><a href=\"https://www.codeguru.com/vb/gen/vb_misc/debuggingandtracing/article.php/c5611/Implementing-a-Custom-TraceListener.htm\" rel=\"nofollow noreferrer\">Implementing a Custom TraceListener</a></em></p>\n"
},
{
"answer_id": 35034967,
"author": "Shaun",
"author_id": 276874,
"author_profile": "https://Stackoverflow.com/users/276874",
"pm_score": 3,
"selected": false,
"text": "<p>I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the <code>TraceSource.TraceEvent(TraceEventType, Int32, String)</code> method where the <code>TraceSource</code> object was initialised with a string making it a 'named source'.</p>\n<p>For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called <code>tracelog.txt</code>. For the following code:</p>\n<pre><code>TraceSource source = new TraceSource("sourceName");\nsource.TraceEvent(TraceEventType.Verbose, 1, "Trace message");\n</code></pre>\n<p>I successfully managed to log with the following diagnostics configuration:</p>\n<pre class=\"lang-html prettyprint-override\"><code><system.diagnostics>\n <sources>\n <source name="sourceName" switchName="switchName">\n <listeners>\n <add\n name="textWriterTraceListener"\n type="System.Diagnostics.TextWriterTraceListener"\n initializeData="tracelog.txt" />\n </listeners>\n </source>\n </sources>\n\n <switches>\n <add name="switchName" value="Verbose" />\n </switches>\n</system.diagnostics>\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I want to introduce some tracing to a C# application I am writing. Sadly, I can never really remember how it works and would like a tutorial with reference qualities to check up on every now and then. It should include:
* App.config / Web.config stuff to add for registering TraceListeners
* how to set it up in the calling application
Do you know the über tutorial that we should link to?
---
Glenn Slaven pointed me in the right direction. Add this to your App.config/Web.config inside `<configuration/>`:
```
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add type="System.Diagnostics.TextWriterTraceListener" name="TextWriter"
initializeData="trace.log" />
</listeners>
</trace>
</system.diagnostics>
```
This will add a `TextWriterTraceListener` that will catch everything you send to with `Trace.WriteLine`, etc.
@DanEsparza pointed out that you should use `Trace.TraceInformation`, `Trace.TraceWarning` and `Trace.TraceError` instead of `Trace.WriteLine`, as they allow you to format messages the same way as `string.Format`.
**Tip:** If you don't add any listeners, then you can still see the trace output with the Sysinternals program [DebugView](https://learn.microsoft.com/en-us/sysinternals/downloads/debugview) (`Dbgview.exe`): | I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the `TraceSource.TraceEvent(TraceEventType, Int32, String)` method where the `TraceSource` object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called `tracelog.txt`. For the following code:
```
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
```
I successfully managed to log with the following diagnostics configuration:
```html
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
``` |
27,621 | <p>On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?</p>
<p>Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.</p>
<p>Example: I need to copy every .txt file in the following hierarchy</p>
<pre><code>/foo/a.txt
/foo/x.jpg
/foo/bar/a.txt
/foo/bar/c.jpg
/foo/bar/b.txt
</code></pre>
<p>To a folder named 'dest' and get:</p>
<pre><code>/dest/a.txt
/dest/b.txt
</code></pre>
| [
{
"answer_id": 27625,
"author": "Magnus Hoff",
"author_id": 2971,
"author_profile": "https://Stackoverflow.com/users/2971",
"pm_score": 7,
"selected": true,
"text": "<p>In bash:</p>\n\n<pre><code>find /foo -iname '*.txt' -exec cp \\{\\} /dest/ \\;\n</code></pre>\n\n<p><code>find</code> will find all the files under the path <code>/foo</code> matching the wildcard <code>*.txt</code>, case insensitively (That's what <code>-iname</code> means). For each file, <code>find</code> will execute <code>cp {} /dest/</code>, with the found file in place of <code>{}</code>.</p>\n"
},
{
"answer_id": 27747,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 4,
"selected": false,
"text": "<p>The only problem with Magnus' solution is that it forks off a new \"cp\" process for every file, which is not terribly efficient especially if there is a large number of files.</p>\n\n<p>On Linux (or other systems with GNU coreutils) you can do:</p>\n\n<pre><code>find . -name \"*.xml\" -print0 | xargs -0 echo cp -t a\n</code></pre>\n\n<p>(The -0 allows it to work when your filenames have weird characters -- like spaces -- in them.)</p>\n\n<p>Unfortunately I think Macs come with BSD-style tools. Anyone know a \"standard\" equivalent to the \"-t\" switch?</p>\n"
},
{
"answer_id": 58521,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 1,
"selected": false,
"text": "<p>As far as the man page for cp on a FreeBSD box goes, there's no need for a -t switch. cp will assume the last argument on the command line to be the target directory if more than two names are passed.</p>\n"
},
{
"answer_id": 58536,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "<p>If you really want to run just one command, why not cons one up and run it? Like so:</p>\n\n<pre><code>$ find /foo -name '*.txt' | xargs echo | sed -e 's/^/cp /' -e 's|$| /dest|' | bash -sx\n</code></pre>\n\n<p>But that won't matter too much performance-wise unless you do this a lot or have a ton of files. Be careful of name collusions, however. I noticed in testing that GNU cp at least warns of collisions:</p>\n\n<pre><code>cp: will not overwrite just-created `/dest/tubguide.tex' with `./texmf/tex/plain/tugboat/tubguide.tex'\n</code></pre>\n\n<p>I think the cleanest is:</p>\n\n<pre><code>$ find /foo -name '*.txt' | xargs -i cp {} /dest\n</code></pre>\n\n<p>Less syntax to remember than the -exec option.</p>\n"
},
{
"answer_id": 3228414,
"author": "Rob Styles",
"author_id": 389473,
"author_profile": "https://Stackoverflow.com/users/389473",
"pm_score": 4,
"selected": false,
"text": "<p>The answers above don't allow for name collisions as the asker didn't mind files being over-written.</p>\n\n<p>I do mind files being over-written so came up with a different approach. Replacing each / in the path with - keep the hierarchy in the names, and puts all the files in one flat folder.</p>\n\n<p>We use find to get the list of all files, then awk to create a mv command with the original filename and the modified filename then pass those to bash to be executed.</p>\n\n<pre><code>find ./from -type f | awk '{ str=$0; sub(/\\.\\//, \"\", str); gsub(/\\//, \"-\", str); print \"mv \" $0 \" ./to/\" str }' | bash\n</code></pre>\n\n<p>where ./from and ./to are directories to mv from and to.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?
Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.
Example: I need to copy every .txt file in the following hierarchy
```
/foo/a.txt
/foo/x.jpg
/foo/bar/a.txt
/foo/bar/c.jpg
/foo/bar/b.txt
```
To a folder named 'dest' and get:
```
/dest/a.txt
/dest/b.txt
``` | In bash:
```
find /foo -iname '*.txt' -exec cp \{\} /dest/ \;
```
`find` will find all the files under the path `/foo` matching the wildcard `*.txt`, case insensitively (That's what `-iname` means). For each file, `find` will execute `cp {} /dest/`, with the found file in place of `{}`. |
27,622 | <p>The <strong><a href="http://msdn.microsoft.com/en-us/library/4wyz8787(VS.80).aspx" rel="noreferrer">TRACE macro</a></strong> can be used to output diagnostic messages to the debugger when the code is compiled in <strong>Debug</strong> mode. I need the same messages while in <strong>Release</strong> mode. Is there a way to achieve this?</p>
<p>(Please do <strong>not</strong> waste your time discussing why I should not be using TRACE in Release mode :-)</p>
| [
{
"answer_id": 27628,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "<p>In MFC, TRACE is defined as ATLTRACE. And in release mode that is defined as:</p>\n\n<pre><code>#define ATLTRACE __noop\n</code></pre>\n\n<p>So, using the out-the-box TRACE from MFC, you won't actually be able to read any TRACE text, because it won't even be written out. You could write your own TRACE function instead, then re-define the TRACE macro. You could do something like this:</p>\n\n<pre><code>void MyTrace(const CString& text)\n{\n ::OutputDebugString(text); // Outputs to console, same as regular TRACE\n // TODO: Do whatever output you need here. Write to event log / write to text file / write to pipe etc.\n}\n</code></pre>\n"
},
{
"answer_id": 27632,
"author": "Magnus Westin",
"author_id": 2957,
"author_profile": "https://Stackoverflow.com/users/2957",
"pm_score": 2,
"selected": false,
"text": "<p>TRACE is just a macro for <a href=\"http://msdn.microsoft.com/en-us/library/aa363362(VS.85).aspx\" rel=\"nofollow noreferrer\">OutputDebugString</a>. So you can easily just make your own TRACE macro (or call it something else) that will call <a href=\"http://msdn.microsoft.com/en-us/library/aa363362(VS.85).aspx\" rel=\"nofollow noreferrer\">OutputDebugString</a>.</p>\n"
},
{
"answer_id": 41046,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": true,
"text": "<p>Actually, the TRACE macro is a lot more flexible than OutputDebugString. It takes a printf() style format string and parameter list whereas OutputDebugString just takes a single string. In order to implement the full TRACE functionality in release mode you need to do something like this:</p>\n\n<pre><code>void trace(const char* format, ...)\n{\n char buffer[1000];\n\n va_list argptr;\n va_start(argptr, format);\n wvsprintf(buffer, format, argptr);\n va_end(argptr);\n\n OutputDebugString(buffer);\n}\n</code></pre>\n"
},
{
"answer_id": 777634,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A few years back I needed similar functionality so I cobbled together the following code. Just save it into a file, e.g. rtrace.h, include it at the end of your stdafx.h, and add _RTRACE to the release mode Preprocessor defines.</p>\n\n<p>Maybe someone will find a use for it :-)</p>\n\n<p>John</p>\n\n<pre>\n#pragma once\n\n//------------------------------------------------------------------------------------------------\n//\n// Author: John Cullen\n// Date: 2006/04/12\n// Based On: MSDN examples for variable argument lists and ATL implementation of TRACE.\n//\n// Description: Allows the use of TRACE statements in RELEASE builds, by overriding the\n// TRACE macro definition and redefining in terms of the RTRACE class and overloaded\n// operator (). Trace output is generated by calling OutputDebugString() directly.\n//\n//\n// Usage: Add to the end of stdafx.h and add _RTRACE to the preprocessor defines (typically\n// for RELEASE builds, although the flag will be ignored for DEBUG builds.\n//\n//------------------------------------------------------------------------------------------------\n\n#ifdef _DEBUG\n\n// NL defined as a shortcut for writing FTRACE(_T(\"\\n\")); for example, instead write FTRACE(NL);\n#define NL _T(\"\\n\") \n#define LTRACE TRACE(_T(\"%s(%d): \"), __FILE__, __LINE__); TRACE\n#define FTRACE TRACE(_T(\"%s(%d): %s: \"), __FILE__, __LINE__, __FUNCTION__); TRACE\n\n#else // _DEBUG\n\n#ifdef _RTRACE\n#undef TRACE\n#define TRACE RTRACE()\n#define LTRACE RTRACE(__FILE__, __LINE__)\n#define FTRACE RTRACE(__FILE__, __LINE__, __FUNCTION__)\n#define NL _T(\"\\n\") \n\nclass RTRACE\n{\npublic:\n // default constructor, no params\n RTRACE(void) : m_pszFileName( NULL ), m_nLineNo( 0 ), m_pszFuncName( NULL ) {};\n\n // overloaded constructor, filename and lineno\n RTRACE(PCTSTR const pszFileName, int nLineNo) :\n m_pszFileName(pszFileName), m_nLineNo(nLineNo), m_pszFuncName(NULL) {};\n\n // overloaded constructor, filename, lineno, and function name\n RTRACE(PCTSTR const pszFileName, int nLineNo, PCTSTR const pszFuncName) :\n m_pszFileName(pszFileName), m_nLineNo(nLineNo), m_pszFuncName(pszFuncName) {};\n\n virtual ~RTRACE(void) {};\n\n // no arguments passed, e.g. RTRACE()()\n void operator()() const\n {\n // no arguments passed, just dump the file, line and function if requested\n OutputFileAndLine();\n OutputFunction();\n }\n\n // format string and parameters passed, e.g. RTRACE()(_T(\"%s\\n\"), someStringVar)\n void operator()(const PTCHAR pszFmt, ...) const\n {\n // dump the file, line and function if requested, followed by the TRACE arguments\n OutputFileAndLine();\n OutputFunction();\n\n // perform the standard TRACE output processing\n va_list ptr; va_start( ptr, pszFmt );\n INT len = _vsctprintf( pszFmt, ptr ) + 1;\n TCHAR* buffer = (PTCHAR) malloc( len * sizeof(TCHAR) );\n _vstprintf( buffer, pszFmt, ptr );\n OutputDebugString(buffer);\n free( buffer );\n }\n\nprivate:\n // output the current file and line\n inline void OutputFileAndLine() const\n {\n if (m_pszFileName && _tcslen(m_pszFileName) > 0)\n {\n INT len = _sctprintf( _T(\"%s(%d): \"), m_pszFileName, m_nLineNo ) + 1;\n PTCHAR buffer = (PTCHAR) malloc( len * sizeof(TCHAR) );\n _stprintf( buffer, _T(\"%s(%d): \"), m_pszFileName, m_nLineNo );\n OutputDebugString( buffer );\n free( buffer );\n }\n }\n\n // output the current function name\n inline void OutputFunction() const\n {\n if (m_pszFuncName && _tcslen(m_pszFuncName) > 0)\n {\n INT len = _sctprintf( _T(\"%s: \"), m_pszFuncName ) + 1;\n PTCHAR buffer = (PTCHAR) malloc( len * sizeof(TCHAR) );\n _stprintf( buffer, _T(\"%s: \"), m_pszFuncName );\n OutputDebugString( buffer );\n free( buffer );\n }\n }\n\nprivate:\n PCTSTR const m_pszFuncName;\n PCTSTR const m_pszFileName;\n const int m_nLineNo;\n};\n\n#endif // _RTRACE\n\n#endif // NDEBUG\n\n</pre>\n"
},
{
"answer_id": 25657721,
"author": "deniro.wang",
"author_id": 2261302,
"author_profile": "https://Stackoverflow.com/users/2261302",
"pm_score": 2,
"selected": false,
"text": "<p>It's most simply code that I had see</p>\n\n<pre><code>#undef ATLTRACE\n#undef ATLTRACE2\n\n#define ATLTRACE2 CAtlTrace(__FILE__, __LINE__, __FUNCTION__)\n#define ATLTRACE ATLTRACE2\n</code></pre>\n\n<p>see\n<a href=\"http://alax.info/blog/1351\" rel=\"nofollow\">http://alax.info/blog/1351</a></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | The **[TRACE macro](http://msdn.microsoft.com/en-us/library/4wyz8787(VS.80).aspx)** can be used to output diagnostic messages to the debugger when the code is compiled in **Debug** mode. I need the same messages while in **Release** mode. Is there a way to achieve this?
(Please do **not** waste your time discussing why I should not be using TRACE in Release mode :-) | Actually, the TRACE macro is a lot more flexible than OutputDebugString. It takes a printf() style format string and parameter list whereas OutputDebugString just takes a single string. In order to implement the full TRACE functionality in release mode you need to do something like this:
```
void trace(const char* format, ...)
{
char buffer[1000];
va_list argptr;
va_start(argptr, format);
wvsprintf(buffer, format, argptr);
va_end(argptr);
OutputDebugString(buffer);
}
``` |
27,670 | <p>On my Vista machine I cannot install the .Net framework 3.5 SP1. Setup ends few moments after ending the download of the required files, stating in the log that: </p>
<pre><code>[08/26/08,09:46:11] Microsoft .NET Framework 2.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 2.0SP1 (CBS). MSI returned error code 1
[08/26/08,09:46:13] WapUI: [2] DepCheck indicates Microsoft .NET Framework 2.0SP1 (CBS) is not installed.
</code></pre>
<p>First thing I did was trying to install 2.0 SP1, but this time setup states that the "product is not supported on Vista system". Uhm.</p>
<p>The real big problem is that this setup fails also when it is called by the Visual Studio 2008 SP1.</p>
<p>Now, I searched the net for this, but I'm not finding a real solution... Any idea / hint? Did anybody have problems during SP1 install?</p>
<p>Thanks</p>
| [
{
"answer_id": 27677,
"author": "Magnus Westin",
"author_id": 2957,
"author_profile": "https://Stackoverflow.com/users/2957",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"http://blogs.msdn.com/astebner/archive/2007/08/24/4548657.aspx\" rel=\"nofollow noreferrer\">Here is an article describing what might be your problem.</a></p>\n"
},
{
"answer_id": 27678,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>I also experienced it on my XP.</p>\n\n<p>I searched for it, and the result was that some kind of beta .NET remained on my PC.</p>\n\n<p>There is a <a href=\"http://blogs.msdn.com/astebner/archive/2005/04/08/406671.aspx\" rel=\"nofollow noreferrer\">tool to remove all</a> .NET framework from the system. I run it and after it I successfully installed 3.5 SP1.</p>\n"
},
{
"answer_id": 463982,
"author": "LaserJesus",
"author_id": 45207,
"author_profile": "https://Stackoverflow.com/users/45207",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar error, though it listed error code 1060 rather than 1. I read elsewhere that having IIS turned off may be the issue, but this didn't seem to help. Then I read that windows update needed to be turned on. Mine was turned on, but when I tired to run it, it failed. I ran: regsvr32 wuaueng.dll which seemed to fix windows update. After windows update was working again I was able to install .Net 3.5 Sp 1. Note that I didn't actually run windows update, I just made sure that it could run.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] | On my Vista machine I cannot install the .Net framework 3.5 SP1. Setup ends few moments after ending the download of the required files, stating in the log that:
```
[08/26/08,09:46:11] Microsoft .NET Framework 2.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 2.0SP1 (CBS). MSI returned error code 1
[08/26/08,09:46:13] WapUI: [2] DepCheck indicates Microsoft .NET Framework 2.0SP1 (CBS) is not installed.
```
First thing I did was trying to install 2.0 SP1, but this time setup states that the "product is not supported on Vista system". Uhm.
The real big problem is that this setup fails also when it is called by the Visual Studio 2008 SP1.
Now, I searched the net for this, but I'm not finding a real solution... Any idea / hint? Did anybody have problems during SP1 install?
Thanks | [Here is an article describing what might be your problem.](http://blogs.msdn.com/astebner/archive/2007/08/24/4548657.aspx) |
27,711 | <p>I'm having a problem obtaining the total row count for items displayed in a Gridview using Paging and with a LinqDataSource as the source of data.</p>
<p>I've tried several approaches:</p>
<pre><code>protected void GridDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
totalLabel.Text = e.TotalRowCount.ToString();
}
</code></pre>
<p>returns -1 every time.</p>
<pre><code>protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
System.Collections.Generic.List<country> lst = e.Result as System.Collections.Generic.List<country>;
int count = lst.Count;
}
</code></pre>
<p>only gives me the count for the current page, and not the total.</p>
<p>Any other suggestions?</p>
| [
{
"answer_id": 27739,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 2,
"selected": false,
"text": "<p>The LinqDataSourceEventArgs returned in those events return -1 on these occasions:</p>\n\n<blockquote>\n <p>-1 if the LinqDataSourceStatusEventArgs object was created during a data modification operation; -1 if you enabled customized paging by setting AutoPage to true and by setting RetrieveTotalRowCount to false. </p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasourcestatuseventargs.totalrowcount.aspx\" rel=\"nofollow noreferrer\">Check here for more information</a> - the table towards the bottom, shows different properties to set to get the rowcount back, but it looks like you either have to set AutoPage and AllowPage properties to either both true or both false.</p>\n\n<p>Judging by the table in the link above and the example you provide you have Autopage set to false, but AllowPaging set to true, therefore it is returning the amount of rows in the page.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 27744,
"author": "tgmdbm",
"author_id": 1851,
"author_profile": "https://Stackoverflow.com/users/1851",
"pm_score": 0,
"selected": false,
"text": "<p>The TotalRowCount property is only valid for certain values of AutoPage and AllowPaging. They should both be true (in your case) or both be false.</p>\n\n<p>chech out the following page for an explanation of the TotalRowCount property.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasourcestatuseventargs.totalrowcount.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasourcestatuseventargs.totalrowcount.aspx</a></p>\n"
},
{
"answer_id": 28357,
"author": "Farinha",
"author_id": 2841,
"author_profile": "https://Stackoverflow.com/users/2841",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I've already set AutoPage and AllowPaging to true.\nI've confirmed that RetrieveTotalRowCount is set to true by checking its value in debug mode (couldn't find where to change its value).</p>\n\n<p>And it still returns -1.</p>\n\n<p>The only thing missing is:</p>\n\n<blockquote>\n <p>-1 if the LinqDataSourceStatusEventArgs object was created during a data modification operation;</p>\n</blockquote>\n\n<p>and I'm not quite sure what this means.\nI am using a modified version of the LinqDataSource to enable some custom filtering, so that might be the problem. On the other hand, while messing around in debug mode I did manage to check the value of the arguments.TotalRowCount and it was correct. But the value that comes out in the Selected event is always -1.</p>\n"
},
{
"answer_id": 3341109,
"author": "Mamoon ur Rasheed",
"author_id": 403004,
"author_profile": "https://Stackoverflow.com/users/403004",
"pm_score": 0,
"selected": false,
"text": "<p>I was stuck with the same problem. I solved my problem with the following line of code</p>\n\n<p>protected void LinqDataSourcePoints_Selected(object sender, LinqDataSourceStatusEventArgs e)\n {\n totalRecords = (e.Result as List).Count;\n }</p>\n\n<p>Explanation:\n1-Parse the e.Result as your data source\n2-Get the count.</p>\n\n<p>Work perfectly for me.</p>\n"
},
{
"answer_id": 3347416,
"author": "Nick Kahn",
"author_id": 275390,
"author_profile": "https://Stackoverflow.com/users/275390",
"pm_score": 0,
"selected": false,
"text": "<p>try this, i have tested and it returns all the rows.</p>\n\n<pre><code> protected void LinqDataSource1_Selecting(object sender, LinqDataSourceStatusEventArgs e)\n {\n System.Collections.Generic.List<country> lst = e.Result as System.Collections.Generic.List<country>;\n\n int count = lst.Count;\n }\n</code></pre>\n\n<p>make sure your event is \"<strong>Selecting</strong>\"</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
] | I'm having a problem obtaining the total row count for items displayed in a Gridview using Paging and with a LinqDataSource as the source of data.
I've tried several approaches:
```
protected void GridDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
totalLabel.Text = e.TotalRowCount.ToString();
}
```
returns -1 every time.
```
protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
System.Collections.Generic.List<country> lst = e.Result as System.Collections.Generic.List<country>;
int count = lst.Count;
}
```
only gives me the count for the current page, and not the total.
Any other suggestions? | The LinqDataSourceEventArgs returned in those events return -1 on these occasions:
>
> -1 if the LinqDataSourceStatusEventArgs object was created during a data modification operation; -1 if you enabled customized paging by setting AutoPage to true and by setting RetrieveTotalRowCount to false.
>
>
>
[Check here for more information](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasourcestatuseventargs.totalrowcount.aspx) - the table towards the bottom, shows different properties to set to get the rowcount back, but it looks like you either have to set AutoPage and AllowPage properties to either both true or both false.
Judging by the table in the link above and the example you provide you have Autopage set to false, but AllowPaging set to true, therefore it is returning the amount of rows in the page.
HTH |
27,743 | <p>My RubyOnRails app is set up with the usual pack of mongrels behind Apache configuration. We've noticed that our Mongrel web server memory usage can grow quite large on certain operations and we'd really like to be able to dynamically do a graceful restart of selected Mongrel processes at any time.</p>
<p>However, for reasons I won't go into here it can sometimes be <em>very</em> important that we don't interrupt a Mongrel while it is servicing a request, so I assume a simple process kill isn't the answer.</p>
<p>Ideally, I want to send the Mongrel a signal that says "finish whatever you're doing and then quit before accepting any more connections".</p>
<p>Is there a standard technique or best practice for this?</p>
| [
{
"answer_id": 27787,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 0,
"selected": false,
"text": "<p>Try using:</p>\n\n<pre><code>mongrel_cluster_ctl stop\n</code></pre>\n\n<p>You can also use:</p>\n\n<pre><code>mongrel_cluster_ctl restart\n</code></pre>\n"
},
{
"answer_id": 29241,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 1,
"selected": false,
"text": "<p>Better question is how to keep your app from consuming so much memory that it requires you to reboot mongrels from time to time.</p>\n\n<p>www.modrails.com reduced our memory footprint significantly</p>\n"
},
{
"answer_id": 31556,
"author": "AndrewR",
"author_id": 2994,
"author_profile": "https://Stackoverflow.com/users/2994",
"pm_score": 5,
"selected": true,
"text": "<p>I've done a little more investigation into the Mongrel source and it turns out that Mongrel installs a signal handler to catch an standard process kill (TERM) and do a graceful shutdown, so I don't need a special procedure after all.</p>\n\n<p>You can see this working from the log output you get when killing a Mongrel while it's processing a request. For example:</p>\n\n<pre><code>** TERM signal received.\nThu Aug 28 00:52:35 +0000 2008: Reaping 2 threads for slow workers because of 'shutdown'\nWaiting for 2 requests to finish, could take 60 seconds.Thu Aug 28 00:52:41 +0000 2008: Reaping 2 threads for slow workers because of 'shutdown'\nWaiting for 2 requests to finish, could take 60 seconds.Thu Aug 28 00:52:43 +0000 2008 (13051) Rendering layoutfalsecontent_typetext/htmlactionindex within layouts/application\n</code></pre>\n"
},
{
"answer_id": 33906,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 3,
"selected": false,
"text": "<p>Look at using monit. You can dynamically restart mongrel based on memory or CPU usage. Here's a line from a config file that I wrote for a client of mine. </p>\n\n<pre><code>check process mongrel-8000 with pidfile /var/www/apps/fooapp/current/tmp/pids/mongrel.8000.pid\n start program = \"/usr/local/bin/mongrel_rails cluster::start --only 8000\"\n stop program = \"/usr/local/bin/mongrel_rails cluster::stop --only 8000\"\n\n if totalmem is greater than 150.0 MB for 5 cycles then restart # eating up memory?\n if cpu is greater than 50% for 8 cycles then alert # send an email to admin\n if cpu is greater than 80% for 5 cycles then restart # hung process?\n if loadavg(5min) greater than 10 for 3 cycles then restart # bad, bad, bad\n if 3 restarts within 5 cycles then timeout # something is wrong, call the sys-admin\n\n if failed host 192.168.106.53 port 8000 protocol http request /monit_stub\n with timeout 10 seconds\n then restart\n group mongrel\n</code></pre>\n\n<p>You'd then repeat this configuration for all of your mongrel cluster instances. The monit_stub line is just an empty file that monit tries to download. If it can't, it tries to restart the instance as well.</p>\n\n<p>Note: the resource monitoring seems not to work on OS X with the Darwin kernel.</p>\n"
},
{
"answer_id": 366416,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>got a question</p>\n\n<p>what happens when /usr/local/bin/mongrel_rails cluster::start --only 8000 is triggered ?</p>\n\n<p>are all of the requests served by this particular process, to their end ? or are they aborted ?</p>\n\n<p>I curious if this whole start/restart thing can be done without affecting the end users...</p>\n"
},
{
"answer_id": 517486,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Boggy:</p>\n\n<p>If you have one process running, it will gracefully shut down (service all the requests in its queue which should only be 1 if you are using proper load balancing). The problem is you can't start the new server until the old one dies, so your users will queue up in the load balancer. What I've found successful is a 'cascade' or rolling restart of the mongrels. Instead of stopping them all and starting them all (therefore queuing requests until the one mongrel is done, stopped, restarted and accepting connections), you can stop then start each mongrel sequentially, blocking the call to restart the next mongrel until the previous one is back up (use a real HTTP check to a /status controller). As your mongrels roll, only one at a time is down and you are serving across two code bases - if you can't do this you should throw up a maintenance page for a minute. You should be able to automate this with capistrano or whatever your deploy tool is.</p>\n\n<p>So I have 3 tasks:\ncap:deploy - which does the traditional restart all at the same time method with a hook that puts up a maintenance page and then takes it down after an HTTP check.\ncap:deploy:rolling - which does this cascade across the machine (I pull from a iClassify to know how many mongrels are on the given machine) without a maintenance page.\ncap deploy:migrations - which does maintenance page + migrations since its usually a bad idea to run migrations 'live'.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994/"
] | My RubyOnRails app is set up with the usual pack of mongrels behind Apache configuration. We've noticed that our Mongrel web server memory usage can grow quite large on certain operations and we'd really like to be able to dynamically do a graceful restart of selected Mongrel processes at any time.
However, for reasons I won't go into here it can sometimes be *very* important that we don't interrupt a Mongrel while it is servicing a request, so I assume a simple process kill isn't the answer.
Ideally, I want to send the Mongrel a signal that says "finish whatever you're doing and then quit before accepting any more connections".
Is there a standard technique or best practice for this? | I've done a little more investigation into the Mongrel source and it turns out that Mongrel installs a signal handler to catch an standard process kill (TERM) and do a graceful shutdown, so I don't need a special procedure after all.
You can see this working from the log output you get when killing a Mongrel while it's processing a request. For example:
```
** TERM signal received.
Thu Aug 28 00:52:35 +0000 2008: Reaping 2 threads for slow workers because of 'shutdown'
Waiting for 2 requests to finish, could take 60 seconds.Thu Aug 28 00:52:41 +0000 2008: Reaping 2 threads for slow workers because of 'shutdown'
Waiting for 2 requests to finish, could take 60 seconds.Thu Aug 28 00:52:43 +0000 2008 (13051) Rendering layoutfalsecontent_typetext/htmlactionindex within layouts/application
``` |
27,745 | <p>Given the URL (single line):<br>
<a href="http://test.example.com/dir/subdir/file.html" rel="noreferrer">http://test.example.com/dir/subdir/file.html</a></p>
<p>How can I extract the following parts using regular expressions:</p>
<ol>
<li>The Subdomain (test)</li>
<li>The Domain (example.com)</li>
<li>The path without the file (/dir/subdir/)</li>
<li>The file (file.html)</li>
<li>The path with the file (/dir/subdir/file.html)</li>
<li>The URL without the path (<a href="http://test.example.com" rel="noreferrer">http://test.example.com</a>)</li>
<li>(add any other that you think would be useful)</li>
</ol>
<p>The regex should work correctly even if I enter the following URL: </p>
<pre><code>http://example.example.com/example/example/example.html
</code></pre>
| [
{
"answer_id": 27755,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 8,
"selected": true,
"text": "<blockquote>\n <p>A single regex to parse and breakup a\n full URL including query parameters\n and anchors e.g.</p>\n \n <p><a href=\"https://www.google.com/dir/1/2/search.html?arg=0-a&arg1=1-b&arg3-c#hash\" rel=\"noreferrer\">https://www.google.com/dir/1/2/search.html?arg=0-a&arg1=1-b&arg3-c#hash</a> </p>\n \n <p><code>^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?$</code></p>\n \n <p>RexEx positions:</p>\n \n <p>url: RegExp['$&'], </p>\n \n <p>protocol:RegExp.$2,</p>\n \n <p>host:RegExp.$3, </p>\n \n <p>path:RegExp.$4,</p>\n \n <p>file:RegExp.$6, </p>\n \n <p>query:RegExp.$7,</p>\n \n <p>hash:RegExp.$8</p>\n</blockquote>\n\n<p>you could then further parse the host ('.' delimited) quite easily.</p>\n\n<p>What <strong>I</strong> would do is use something like this:</p>\n\n<pre><code>/*\n ^(.*:)//([A-Za-z0-9\\-\\.]+)(:[0-9]+)?(.*)$\n*/\nproto $1\nhost $2\nport $3\nthe-rest $4\n</code></pre>\n\n<p>the further parse 'the rest' to be as specific as possible. Doing it in one regex is, well, a bit crazy.</p>\n"
},
{
"answer_id": 27759,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 3,
"selected": false,
"text": "<p>Try the following:</p>\n<pre><code>^((ht|f)tp(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.[\\w]{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?\n</code></pre>\n<p>It supports HTTP / FTP, subdomains, folders, files etc.</p>\n<p>I found it from a quick google search:</p>\n<p><a href=\"https://web.archive.org/web/20210126191109/http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx\" rel=\"nofollow noreferrer\">Link</a></p>\n"
},
{
"answer_id": 27768,
"author": "tgmdbm",
"author_id": 1851,
"author_profile": "https://Stackoverflow.com/users/1851",
"pm_score": 3,
"selected": false,
"text": "<p>subdomain and domain are difficult because the subdomain can have several parts, as can the top level domain, <a href=\"http://sub1.sub2.domain.co.uk/\" rel=\"noreferrer\">http://sub1.sub2.domain.co.uk/</a></p>\n\n<pre><code> the path without the file : http://[^/]+/((?:[^/]+/)*(?:[^/]+$)?) \n the file : http://[^/]+/(?:[^/]+/)*((?:[^/.]+\\.)+[^/.]+)$ \n the path with the file : http://[^/]+/(.*) \n the URL without the path : (http://[^/]+/) \n</code></pre>\n\n<p>(Markdown isn't very friendly to regexes)</p>\n"
},
{
"answer_id": 27775,
"author": "pek",
"author_id": 2644,
"author_profile": "https://Stackoverflow.com/users/2644",
"pm_score": 0,
"selected": false,
"text": "<p>Using <a href=\"http://www.fileformat.info/tool/regex.htm\" rel=\"nofollow noreferrer\">http://www.fileformat.info/tool/regex.htm</a> hometoast's regex works great.</p>\n\n<p>But here is the deal, I want to use different regex patterns in different situations in my program.</p>\n\n<p>For example, I have this URL, and I have an enumeration that lists all supported URLs in my program. Each object in the enumeration has a method getRegexPattern that returns the regex pattern which will then be used to compare with a URL. If the particular regex pattern returns true, then I know that this URL is supported by my program. So, each enumeration has it's own regex depending on where it should look inside the URL.</p>\n\n<p>Hometoast's suggestion is great, but in my case, I think it wouldn't help (unless I copy paste the same regex in all enumerations).</p>\n\n<p>That is why I wanted the answer to give the regex for each situation separately. Although +1 for hometoast. ;)</p>\n"
},
{
"answer_id": 27785,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p>I know you're claiming language-agnostic on this, but can you tell us what you're using just so we know what regex capabilities you have?</p>\n\n<p>If you have the capabilities for non-capturing matches, you can modify hometoast's expression so that subexpressions that you aren't interested in capturing are set up like this:</p>\n\n<p><code>(?:SOMESTUFF)</code></p>\n\n<p>You'd still have to copy and paste (and slightly modify) the Regex into multiple places, but this makes sense--you're not just checking to see if the subexpression exists, but rather if it exists <em>as part of a URL</em>. Using the non-capturing modifier for subexpressions can give you what you need and nothing more, which, if I'm reading you correctly, is what you want.</p>\n\n<p>Just as a small, small note, hometoast's expression doesn't need to put brackets around the 's' for 'https', since he only has one character in there. Quantifiers quantify the one character (or character class or subexpression) directly preceding them. So:</p>\n\n<p><code>https?</code></p>\n\n<p>would match 'http' or 'https' just fine.</p>\n"
},
{
"answer_id": 27821,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 1,
"selected": false,
"text": "<p>Java offers a URL class that will do this. <a href=\"http://java.sun.com/docs/books/tutorial/networking/urls/urlInfo.html\" rel=\"nofollow noreferrer\">Query URL Objects.</a></p>\n\n<p>On a side note, PHP offers <a href=\"http://www.php.net/parse_url\" rel=\"nofollow noreferrer\">parse_url()</a>.</p>\n"
},
{
"answer_id": 309360,
"author": "mingfai",
"author_id": 39701,
"author_profile": "https://Stackoverflow.com/users/39701",
"pm_score": 5,
"selected": false,
"text": "<p>I found the highest voted answer (hometoast's answer) doesn't work perfectly for me. Two problems:</p>\n\n<ol>\n<li>It can not handle port number.</li>\n<li>The hash part is broken.</li>\n</ol>\n\n<p>The following is a modified version:</p>\n\n<pre><code>^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(\\?([^#]*))?(#(.*))?$\n</code></pre>\n\n<p>Position of parts are as follows:</p>\n\n<pre><code>int SCHEMA = 2, DOMAIN = 3, PORT = 5, PATH = 6, FILE = 8, QUERYSTRING = 9, HASH = 12\n</code></pre>\n\n<p>Edit posted by anon user:</p>\n\n<pre><code>function getFileName(path) {\n return path.match(/^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/[\\w\\/-]+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(\\?([^#]*))?(#(.*))?$/i)[8];\n}\n</code></pre>\n"
},
{
"answer_id": 441881,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 2,
"selected": false,
"text": "<pre><code>/^((?P<scheme>https?|ftp):\\/)?\\/?((?P<username>.*?)(:(?P<password>.*?)|)@)?(?P<hostname>[^:\\/\\s]+)(?P<port>:([^\\/]*))?(?P<path>(\\/\\w+)*\\/)(?P<filename>[-\\w.]+[^#?\\s]*)?(?P<query>\\?([^#]*))?(?P<fragment>#(.*))?$/\n</code></pre>\n\n<p>From my answer on a <a href=\"https://stackoverflow.com/questions/441739/regex-for-url-validation-with-parts-capturing#441781\">similar question</a>. Works better than some of the others mentioned because they had some bugs (such as not supporting username/password, not supporting single-character filenames, fragment identifiers being broken).</p>\n"
},
{
"answer_id": 1140642,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>regexp to get the URL path without the file.</p>\n\n<p>url = '<a href=\"http://domain/dir1/dir2/somefile\" rel=\"nofollow noreferrer\">http://domain/dir1/dir2/somefile</a>'\nurl.scan(/^(http://[^/]+)((?:/[^/]+)+(?=/))?/?(?:[^/]+)?$/i).to_s</p>\n\n<p>It can be useful for adding a relative path to this url.</p>\n"
},
{
"answer_id": 1541830,
"author": "CallMeLaNN",
"author_id": 186334,
"author_profile": "https://Stackoverflow.com/users/186334",
"pm_score": 2,
"selected": false,
"text": "<p>You can get all the http/https, host, port, path as well as query by using Uri object in .NET.\njust the difficult task is to break the host into sub domain, domain name and TLD.</p>\n\n<p>There is no standard to do so and can't be simply use string parsing or RegEx to produce the correct result. At first, I am using RegEx function but not all URL can be parse the subdomain correctly. The practice way is to use a list of TLDs. After a TLD for a URL is defined the left part is domain and the remaining is sub domain.</p>\n\n<p>However the list need to maintain it since new TLDs is possible. The current moment I know is publicsuffix.org maintain the latest list and you can use domainname-parser tools from google code to parse the public suffix list and get the sub domain, domain and TLD easily by using DomainName object: domainName.SubDomain, domainName.Domain and domainName.TLD.</p>\n\n<p>This answers also helpfull:\n<a href=\"https://stackoverflow.com/questions/288810/get-the-subdomain-from-a-url\">Get the subdomain from a URL</a></p>\n\n<p>CaLLMeLaNN</p>\n"
},
{
"answer_id": 1821918,
"author": "Jason",
"author_id": 206908,
"author_profile": "https://Stackoverflow.com/users/206908",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend not using regex. An API call like <em>WinHttpCrackUrl()</em> is less error prone.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa384092%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa384092%28VS.85%29.aspx</a></p>\n"
},
{
"answer_id": 3724500,
"author": "Shelby Moore",
"author_id": 449214,
"author_profile": "https://Stackoverflow.com/users/449214",
"pm_score": 3,
"selected": false,
"text": "<p>This improved version should work as reliably as a parser.</p>\n\n<pre><code> // Applies to URI, not just URL or URN:\n // http://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Relationship_to_URL_and_URN\n //\n // http://labs.apache.org/webarch/uri/rfc/rfc3986.html#regexp\n //\n // (?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?\n //\n // http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax\n //\n // $@ matches the entire uri\n // $1 matches scheme (ftp, http, mailto, mshelp, ymsgr, etc)\n // $2 matches authority (host, user:pwd@host, etc)\n // $3 matches path\n // $4 matches query (http GET REST api, etc)\n // $5 matches fragment (html anchor, etc)\n //\n // Match specific schemes, non-optional authority, disallow white-space so can delimit in text, and allow 'www.' w/o scheme\n // Note the schemes must match ^[^\\s|:/?#]+(?:\\|[^\\s|:/?#]+)*$\n //\n // (?:()(www\\.[^\\s/?#]+\\.[^\\s/?#]+)|(schemes)://([^\\s/?#]*))([^\\s?#]*)(?:\\?([^\\s#]*))?(#(\\S*))?\n //\n // Validate the authority with an orthogonal RegExp, so the RegExp above won’t fail to match any valid urls.\n function uriRegExp( flags, schemes/* = null*/, noSubMatches/* = false*/ )\n {\n if( !schemes )\n schemes = '[^\\\\s:\\/?#]+'\n else if( !RegExp( /^[^\\s|:\\/?#]+(?:\\|[^\\s|:\\/?#]+)*$/ ).test( schemes ) )\n throw TypeError( 'expected URI schemes' )\n return noSubMatches ? new RegExp( '(?:www\\\\.[^\\\\s/?#]+\\\\.[^\\\\s/?#]+|' + schemes + '://[^\\\\s/?#]*)[^\\\\s?#]*(?:\\\\?[^\\\\s#]*)?(?:#\\\\S*)?', flags ) :\n new RegExp( '(?:()(www\\\\.[^\\\\s/?#]+\\\\.[^\\\\s/?#]+)|(' + schemes + ')://([^\\\\s/?#]*))([^\\\\s?#]*)(?:\\\\?([^\\\\s#]*))?(?:#(\\\\S*))?', flags )\n }\n\n // http://en.wikipedia.org/wiki/URI_scheme#Official_IANA-registered_schemes\n function uriSchemesRegExp()\n {\n return 'about|callto|ftp|gtalk|http|https|irc|ircs|javascript|mailto|mshelp|sftp|ssh|steam|tel|view-source|ymsgr'\n }\n</code></pre>\n"
},
{
"answer_id": 11976301,
"author": "baadf00d",
"author_id": 1577533,
"author_profile": "https://Stackoverflow.com/users/1577533",
"pm_score": 4,
"selected": false,
"text": "<p>I needed a regular Expression to match all urls and made this one:</p>\n\n<pre><code>/(?:([^\\:]*)\\:\\/\\/)?(?:([^\\:\\@]*)(?:\\:([^\\@]*))?\\@)?(?:([^\\/\\:]*)\\.(?=[^\\.\\/\\:]*\\.[^\\.\\/\\:]*))?([^\\.\\/\\:]*)(?:\\.([^\\/\\.\\:]*))?(?:\\:([0-9]*))?(\\/[^\\?#]*(?=.*?\\/)\\/)?([^\\?#]*)?(?:\\?([^#]*))?(?:#(.*))?/\n</code></pre>\n\n<p>It matches all urls, any protocol, even urls like</p>\n\n<pre><code>ftp://user:[email protected]:8080/dir1/dir2/file.php?param1=value1#hashtag\n</code></pre>\n\n<p>The result (in JavaScript) looks like this:</p>\n\n<pre><code>[\"ftp\", \"user\", \"pass\", \"www.cs\", \"server\", \"com\", \"8080\", \"/dir1/dir2/\", \"file.php\", \"param1=value1\", \"hashtag\"]\n</code></pre>\n\n<p>An url like</p>\n\n<pre><code>mailto://[email protected]\n</code></pre>\n\n<p>looks like this:</p>\n\n<pre><code>[\"mailto\", \"admin\", undefined, \"www.cs\", \"server\", \"com\", undefined, undefined, undefined, undefined, undefined] \n</code></pre>\n"
},
{
"answer_id": 12470263,
"author": "Rob",
"author_id": 203452,
"author_profile": "https://Stackoverflow.com/users/203452",
"pm_score": 6,
"selected": false,
"text": "<p>I realize I'm late to the party, but there is a simple way to let the browser parse a url for you without a regex:</p>\n\n<pre><code>var a = document.createElement('a');\na.href = 'http://www.example.com:123/foo/bar.html?fox=trot#foo';\n\n['href','protocol','host','hostname','port','pathname','search','hash'].forEach(function(k) {\n console.log(k+':', a[k]);\n});\n\n/*//Output:\nhref: http://www.example.com:123/foo/bar.html?fox=trot#foo\nprotocol: http:\nhost: www.example.com:123\nhostname: www.example.com\nport: 123\npathname: /foo/bar.html\nsearch: ?fox=trot\nhash: #foo\n*/\n</code></pre>\n"
},
{
"answer_id": 14057711,
"author": "mjs",
"author_id": 961018,
"author_profile": "https://Stackoverflow.com/users/961018",
"pm_score": 2,
"selected": false,
"text": "<p>Here is one that is complete, and doesnt rely on any protocol.</p>\n\n<pre><code>function getServerURL(url) {\n var m = url.match(\"(^(?:(?:.*?)?//)?[^/?#;]*)\");\n console.log(m[1]) // Remove this\n return m[1];\n }\n\ngetServerURL(\"http://dev.test.se\")\ngetServerURL(\"http://dev.test.se/\")\ngetServerURL(\"//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\")\ngetServerURL(\"//\")\ngetServerURL(\"www.dev.test.se/sdas/dsads\")\ngetServerURL(\"www.dev.test.se/\")\ngetServerURL(\"www.dev.test.se?abc=32\")\ngetServerURL(\"www.dev.test.se#abc\")\ngetServerURL(\"//dev.test.se?sads\")\ngetServerURL(\"http://www.dev.test.se#321\")\ngetServerURL(\"http://localhost:8080/sads\")\ngetServerURL(\"https://localhost:8080?sdsa\")\n</code></pre>\n\n<p><strong>Prints</strong></p>\n\n<pre><code>http://dev.test.se\n\nhttp://dev.test.se\n\n//ajax.googleapis.com\n\n//\n\nwww.dev.test.se\n\nwww.dev.test.se\n\nwww.dev.test.se\n\nwww.dev.test.se\n\n//dev.test.se\n\nhttp://www.dev.test.se\n\nhttp://localhost:8080\n\nhttps://localhost:8080\n</code></pre>\n"
},
{
"answer_id": 14385452,
"author": "Skone",
"author_id": 158039,
"author_profile": "https://Stackoverflow.com/users/158039",
"pm_score": 2,
"selected": false,
"text": "<p>None of the above worked for me. Here's what I ended up using:</p>\n\n<pre><code>/^(?:((?:https?|s?ftp):)\\/\\/)([^:\\/\\s]+)(?::(\\d*))?(?:\\/([^\\s?#]+)?([?][^?#]*)?(#.*)?)?/\n</code></pre>\n"
},
{
"answer_id": 17892757,
"author": "okigan",
"author_id": 142207,
"author_profile": "https://Stackoverflow.com/users/142207",
"pm_score": 3,
"selected": false,
"text": "<p>Propose a much more readable solution (in Python, but applies to any regex):</p>\n\n<pre><code>def url_path_to_dict(path):\n pattern = (r'^'\n r'((?P<schema>.+?)://)?'\n r'((?P<user>.+?)(:(?P<password>.*?))?@)?'\n r'(?P<host>.*?)'\n r'(:(?P<port>\\d+?))?'\n r'(?P<path>/.*?)?'\n r'(?P<query>[?].*?)?'\n r'$'\n )\n regex = re.compile(pattern)\n m = regex.match(path)\n d = m.groupdict() if m is not None else None\n\n return d\n\ndef main():\n print url_path_to_dict('http://example.example.com/example/example/example.html')\n</code></pre>\n\n<p>Prints: </p>\n\n<pre><code>{\n'host': 'example.example.com', \n'user': None, \n'path': '/example/example/example.html', \n'query': None, \n'password': None, \n'port': None, \n'schema': 'http'\n}\n</code></pre>\n"
},
{
"answer_id": 24527267,
"author": "Sam Adams",
"author_id": 1584651,
"author_profile": "https://Stackoverflow.com/users/1584651",
"pm_score": 4,
"selected": false,
"text": "<p>I was trying to solve this in javascript, which should be handled by:</p>\n\n<pre><code>var url = new URL('http://a:[email protected]:890/path/wah@t/foo.js?foo=bar&bingobang=&[email protected]#foobar/bing/bo@ng?bang');\n</code></pre>\n\n<p>since (in Chrome, at least) it parses to:</p>\n\n<pre><code>{\n \"hash\": \"#foobar/bing/bo@ng?bang\",\n \"search\": \"?foo=bar&bingobang=&[email protected]\",\n \"pathname\": \"/path/wah@t/foo.js\",\n \"port\": \"890\",\n \"hostname\": \"example.com\",\n \"host\": \"example.com:890\",\n \"password\": \"b\",\n \"username\": \"a\",\n \"protocol\": \"http:\",\n \"origin\": \"http://example.com:890\",\n \"href\": \"http://a:[email protected]:890/path/wah@t/foo.js?foo=bar&bingobang=&[email protected]#foobar/bing/bo@ng?bang\"\n}\n</code></pre>\n\n<p>However, this isn't cross browser (<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/URL</a>), so I cobbled this together to pull the same parts out as above:</p>\n\n<pre><code>^(?:(?:(([^:\\/#\\?]+:)?(?:(?:\\/\\/)(?:(?:(?:([^:@\\/#\\?]+)(?:\\:([^:@\\/#\\?]*))?)@)?(([^:\\/#\\?\\]\\[]+|\\[[^\\/\\]@#?]+\\])(?:\\:([0-9]+))?))?)?)?((?:\\/?(?:[^\\/\\?#]+\\/+)*)(?:[^\\?#]*)))?(\\?[^#]+)?)(#.*)?\n</code></pre>\n\n<p>Credit for this regex goes to <a href=\"https://gist.github.com/rpflorence\" rel=\"noreferrer\">https://gist.github.com/rpflorence</a> who posted this jsperf <a href=\"http://jsperf.com/url-parsing\" rel=\"noreferrer\">http://jsperf.com/url-parsing</a> (originally found here: <a href=\"https://gist.github.com/jlong/2428561#comment-310066\" rel=\"noreferrer\">https://gist.github.com/jlong/2428561#comment-310066</a>) who came up with the regex this was originally based on.</p>\n\n<p>The parts are in this order:</p>\n\n<pre><code>var keys = [\n \"href\", // http://user:[email protected]:81/directory/file.ext?query=1#anchor\n \"origin\", // http://user:[email protected]:81\n \"protocol\", // http:\n \"username\", // user\n \"password\", // pass\n \"host\", // host.com:81\n \"hostname\", // host.com\n \"port\", // 81\n \"pathname\", // /directory/file.ext\n \"search\", // ?query=1\n \"hash\" // #anchor\n];\n</code></pre>\n\n<p>There is also a small library which wraps it and provides query params:</p>\n\n<p><a href=\"https://github.com/sadams/lite-url\" rel=\"noreferrer\">https://github.com/sadams/lite-url</a> (also available on bower)</p>\n\n<p>If you have an improvement, please create a pull request with more tests and I will accept and merge with thanks.</p>\n"
},
{
"answer_id": 26766402,
"author": "jds",
"author_id": 1830334,
"author_profile": "https://Stackoverflow.com/users/1830334",
"pm_score": 7,
"selected": false,
"text": "<p>I'm a few years late to the party, but I'm surprised no one has mentioned the Uniform Resource Identifier specification has a <a href=\"https://www.rfc-editor.org/rfc/rfc3986#appendix-B\" rel=\"noreferrer\">section on parsing URIs with a regular expression</a>. The regular expression, written by Berners-Lee, et al., is:</p>\n<blockquote>\n<pre><code>^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n 12 3 4 5 6 7 8 9\n</code></pre>\n<p>The numbers in the second line above are only to assist readability;\nthey indicate the reference points for each subexpression (i.e., each\npaired parenthesis). We refer to the value matched for subexpression\n as $. For example, matching the above expression to</p>\n<p><code>http://www.ics.uci.edu/pub/ietf/uri/#Related</code></p>\n<p>results in the following subexpression matches:</p>\n<pre><code>$1 = http:\n$2 = http\n$3 = //www.ics.uci.edu\n$4 = www.ics.uci.edu\n$5 = /pub/ietf/uri/\n$6 = <undefined>\n$7 = <undefined>\n$8 = #Related\n$9 = Related\n</code></pre>\n</blockquote>\n<p>For what it's worth, I found that I had to escape the forward slashes in JavaScript:</p>\n<p><code>^(([^:\\/?#]+):)?(\\/\\/([^\\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?</code></p>\n"
},
{
"answer_id": 30563164,
"author": "Yetti99",
"author_id": 3874595,
"author_profile": "https://Stackoverflow.com/users/3874595",
"pm_score": 2,
"selected": false,
"text": "<p>I like the regex that was published in \"Javascript: The Good Parts\".\nIts not too short and not too complex.\nThis page on github also has the JavaScript code that uses it.\nBut it an be adapted for any language.\n<a href=\"https://gist.github.com/voodooGQ/4057330\" rel=\"nofollow\">https://gist.github.com/voodooGQ/4057330</a></p>\n"
},
{
"answer_id": 34451670,
"author": "ylev",
"author_id": 3187132,
"author_profile": "https://Stackoverflow.com/users/3187132",
"pm_score": -1,
"selected": false,
"text": "<pre><code>String s = \"https://www.thomas-bayer.com/axis2/services/BLZService?wsdl\";\n\nString regex = \"(^http.?://)(.*?)([/\\\\?]{1,})(.*)\";\n\nSystem.out.println(\"1: \" + s.replaceAll(regex, \"$1\"));\nSystem.out.println(\"2: \" + s.replaceAll(regex, \"$2\"));\nSystem.out.println(\"3: \" + s.replaceAll(regex, \"$3\"));\nSystem.out.println(\"4: \" + s.replaceAll(regex, \"$4\"));\n</code></pre>\n\n<p>Will provide the following output:<br>\n 1: https://<br>\n 2: www.thomas-bayer.com<br>\n 3: /<br>\n 4: axis2/services/BLZService?wsdl<br>\n<br>\nIf you change the URL to <br>\n String s = \"<a href=\"https://www.thomas-bayer.com?wsdl=qwerwer&ttt=888\" rel=\"nofollow\">https://www.thomas-bayer.com?wsdl=qwerwer&ttt=888</a>\";\nthe output will be the following :<br>\n 1: https://<br>\n 2: www.thomas-bayer.com<br>\n 3: ?<br>\n 4: wsdl=qwerwer&ttt=888<br></p>\n\n<p>enjoy..<br>\nYosi Lev</p>\n"
},
{
"answer_id": 39284990,
"author": "Steve K",
"author_id": 2020820,
"author_profile": "https://Stackoverflow.com/users/2020820",
"pm_score": 0,
"selected": false,
"text": "<p>The regex to do full parsing is quite horrendous. I've included named backreferences for legibility, and broken each part into separate lines, but it still looks like this:</p>\n\n<pre><code>^(?:(?P<protocol>\\w+(?=:\\/\\/))(?::\\/\\/))?\n(?:(?P<host>(?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^\\/?#:]+)(?::(?P<port>[0-9]+))?)\\/)?\n(?:(?P<path>(?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\\/)?\n(?P<file>(?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\n(?:\\?(?P<querystring>(?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^#])+))?\n(?:#(?P<fragment>.*))?$\n</code></pre>\n\n<p>The thing that requires it to be so verbose is that except for the protocol or the port, any of the parts can contain HTML entities, which makes delineation of the fragment quite tricky. So in the last few cases - the host, path, file, querystring, and fragment, we allow either any html entity or any character that isn't a <code>?</code> or <code>#</code>. The regex for an html entity looks like this:</p>\n\n<pre><code>$htmlentity = \"&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);\"\n</code></pre>\n\n<p>When that is extracted (I used a mustache syntax to represent it), it becomes a bit more legible:</p>\n\n<pre><code>^(?:(?P<protocol>(?:ht|f)tps?|\\w+(?=:\\/\\/))(?::\\/\\/))?\n(?:(?P<host>(?:{{htmlentity}}|[^\\/?#:])+(?::(?P<port>[0-9]+))?)\\/)?\n(?:(?P<path>(?:{{htmlentity}}|[^?#])+)\\/)?\n(?P<file>(?:{{htmlentity}}|[^?#])+)\n(?:\\?(?P<querystring>(?:{{htmlentity}};|[^#])+))?\n(?:#(?P<fragment>.*))?$\n</code></pre>\n\n<p>In JavaScript, of course, you can't use named backreferences, so the regex becomes</p>\n\n<pre><code>^(?:(\\w+(?=:\\/\\/))(?::\\/\\/))?(?:((?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^\\/?#:]+)(?::([0-9]+))?)\\/)?(?:((?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\\/)?((?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)(?:\\?((?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^#])+))?(?:#(.*))?$\n</code></pre>\n\n<p>and in each match, the protocol is <code>\\1</code>, the host is <code>\\2</code>, the port is <code>\\3</code>, the path <code>\\4</code>, the file <code>\\5</code>, the querystring <code>\\6</code>, and the fragment <code>\\7</code>.</p>\n"
},
{
"answer_id": 40766359,
"author": "Gil Zellner",
"author_id": 1889311,
"author_profile": "https://Stackoverflow.com/users/1889311",
"pm_score": 1,
"selected": false,
"text": "<p>I tried a few of these that didn't cover my needs, especially the highest voted which didn't catch a url without a path (<a href=\"http://example.com/\" rel=\"nofollow noreferrer\">http://example.com/</a>)</p>\n\n<p>also lack of group names made it unusable in ansible (or perhaps my jinja2 skills are lacking).</p>\n\n<p>so this is my version slightly modified with the source being the highest voted version here:</p>\n\n<pre><code>^((?P<protocol>http[s]?|ftp):\\/)?\\/?(?P<host>[^:\\/\\s]+)(?P<path>((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+))*(.*)?(#[\\w\\-]+)?$\n</code></pre>\n"
},
{
"answer_id": 45708666,
"author": "mohan mu",
"author_id": 7745445,
"author_profile": "https://Stackoverflow.com/users/7745445",
"pm_score": 0,
"selected": false,
"text": "<pre><code>//USING REGEX\n/**\n * Parse URL to get information\n *\n * @param url the URL string to parse\n * @return parsed the URL parsed or null\n */\nvar UrlParser = function (url) {\n \"use strict\";\n\n var regx = /^(((([^:\\/#\\?]+:)?(?:(\\/\\/)((?:(([^:@\\/#\\?]+)(?:\\:([^:@\\/#\\?]+))?)@)?(([^:\\/#\\?\\]\\[]+|\\[[^\\/\\]@#?]+\\])(?:\\:([0-9]+))?))?)?)?((\\/?(?:[^\\/\\?#]+\\/+)*)([^\\?#]*)))?(\\?[^#]+)?)(#.*)?/,\n matches = regx.exec(url),\n parser = null;\n\n if (null !== matches) {\n parser = {\n href : matches[0],\n withoutHash : matches[1],\n url : matches[2],\n origin : matches[3],\n protocol : matches[4],\n protocolseparator : matches[5],\n credhost : matches[6],\n cred : matches[7],\n user : matches[8],\n pass : matches[9],\n host : matches[10],\n hostname : matches[11],\n port : matches[12],\n pathname : matches[13],\n segment1 : matches[14],\n segment2 : matches[15],\n search : matches[16],\n hash : matches[17]\n };\n }\n\n return parser;\n};\n\nvar parsedURL=UrlParser(url);\nconsole.log(parsedURL);\n</code></pre>\n"
},
{
"answer_id": 63028949,
"author": "Bilal Demir",
"author_id": 9082736,
"author_profile": "https://Stackoverflow.com/users/9082736",
"pm_score": 0,
"selected": false,
"text": "<p>I tried this regex for parsing url partitions:</p>\n<pre><code>^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/?(?:[^\\/\\?#]+\\/+)*)([^\\?#]*))(\\?([^#]*))?(#(.*))?$\n</code></pre>\n<p>URL: <code>https://www.google.com/my/path/sample/asd-dsa/this?key1=value1&key2=value2</code></p>\n<p>Matches:</p>\n<pre><code>Group 1. 0-7 https:/\nGroup 2. 0-5 https\nGroup 3. 8-22 www.google.com\nGroup 6. 22-50 /my/path/sample/asd-dsa/this\nGroup 7. 22-46 /my/path/sample/asd-dsa/\nGroup 8. 46-50 this\nGroup 9. 50-74 ?key1=value1&key2=value2\nGroup 10. 51-74 key1=value1&key2=value2\n</code></pre>\n"
},
{
"answer_id": 64468826,
"author": "CallMarl",
"author_id": 5540407,
"author_profile": "https://Stackoverflow.com/users/5540407",
"pm_score": 1,
"selected": false,
"text": "<p>I build this one. Very permissive it's not to check url juste divide it.</p>\n<p><code>^((http[s]?):\\/\\/)?([a-zA-Z0-9-.]*)?([\\/]?[^?#\\n]*)?([?]?[^?#\\n]*)?([#]?[^?#\\n]*)$</code></p>\n<ul>\n<li>match 1 : full protocole with :// (http or https)</li>\n<li>match 2 : protocole without ://</li>\n<li>match 3 : host</li>\n<li>match 4 : slug</li>\n<li>match 5 : param</li>\n<li>match 6 : anchor</li>\n</ul>\n<p><strong>work</strong></p>\n<pre><code>http://\nhttps://\nwww.demo.com\n/slug\n?foo=bar\n#anchor\n\nhttps://demo.com\nhttps://demo.com/\nhttps://demo.com/slug\nhttps://demo.com/slug/foo\nhttps://demo.com/?foo=bar\nhttps://demo.com/?foo=bar#anchor\nhttps://demo.com/?foo=bar&bar=foo#anchor\nhttps://www.greate-demo.com/\n</code></pre>\n<p><strong>crash</strong></p>\n<pre><code>#anchor#\n?toto?\n</code></pre>\n"
},
{
"answer_id": 65070175,
"author": "Hritik Soni",
"author_id": 5113528,
"author_profile": "https://Stackoverflow.com/users/5113528",
"pm_score": 0,
"selected": false,
"text": "<p>The best answer suggested here didn't work for me because my URLs also contain a port.\nHowever modifying it to the following regex worked for me:</p>\n<pre><code>^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:\\d+)?((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?$\n</code></pre>\n"
},
{
"answer_id": 67148884,
"author": "igorzg",
"author_id": 3053382,
"author_profile": "https://Stackoverflow.com/users/3053382",
"pm_score": 3,
"selected": false,
"text": "<pre><code>const URI_RE = /^(([^:\\/\\s]+):\\/?\\/?([^\\/\\s@]*@)?([^\\/@:]*)?:?(\\d+)?)?(\\/[^?]*)?(\\?([^#]*))?(#[\\s\\S]*)?$/;\n/**\n* GROUP 1 ([scheme][authority][host][port])\n* GROUP 2 (scheme)\n* GROUP 3 (authority)\n* GROUP 4 (host)\n* GROUP 5 (port)\n* GROUP 6 (path)\n* GROUP 7 (?query)\n* GROUP 8 (query)\n* GROUP 9 (fragment)\n*/\nURI_RE.exec("https://john:[email protected]:123/forum/questions/?tag=networking&order=newest#top");\nURI_RE.exec("/forum/questions/?tag=networking&order=newest#top");\nURI_RE.exec("ldap://[2001:db8::7]/c=GB?objectClass?one");\nURI_RE.exec("mailto:[email protected]");\n</code></pre>\n<p>Above you can find javascript implementation with modified regex</p>\n"
},
{
"answer_id": 67796005,
"author": "MattWeiler",
"author_id": 1827349,
"author_profile": "https://Stackoverflow.com/users/1827349",
"pm_score": 1,
"selected": false,
"text": "<p>I needed some REGEX to parse the components of a URL in Java.\nThis is what I'm using:</p>\n<pre><code>"^(?:(http[s]?|ftp):/)?/?" + // METHOD\n"([^:^/^?^#\\\\s]+)" + // HOSTNAME\n"(?::(\\\\d+))?" + // PORT\n"([^?^#.*]+)?" + // PATH\n"(\\\\?[^#.]*)?" + // QUERY\n"(#[\\\\w\\\\-]+)?$" // ID\n</code></pre>\n<p><strong>Java Code Snippet:</strong></p>\n<pre><code>final Pattern pattern = Pattern.compile(\n "^(?:(http[s]?|ftp):/)?/?" + // METHOD\n "([^:^/^?^#\\\\s]+)" + // HOSTNAME\n "(?::(\\\\d+))?" + // PORT\n "([^?^#.*]+)?" + // PATH\n "(\\\\?[^#.]*)?" + // QUERY\n "(#[\\\\w\\\\-]+)?$" // ID\n);\nfinal Matcher matcher = pattern.matcher(url);\n\nSystem.out.println(" URL: " + url);\n\nif (matcher.matches())\n{\n System.out.println(" Method: " + matcher.group(1));\n System.out.println("Hostname: " + matcher.group(2));\n System.out.println(" Port: " + matcher.group(3));\n System.out.println(" Path: " + matcher.group(4));\n System.out.println(" Query: " + matcher.group(5));\n System.out.println(" ID: " + matcher.group(6));\n \n return matcher.group(2);\n}\n\nSystem.out.println();\nSystem.out.println();\n</code></pre>\n"
},
{
"answer_id": 70326445,
"author": "Exo Flame",
"author_id": 4530300,
"author_profile": "https://Stackoverflow.com/users/4530300",
"pm_score": 0,
"selected": false,
"text": "<p>For browser / nodejs environment there is a built in URL class which share the same signature it seems. but check out the respective focus for your case.</p>\n<p><a href=\"https://nodejs.org/api/url.html#urlhost\" rel=\"nofollow noreferrer\">https://nodejs.org/api/url.html#urlhost</a></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/URL</a></p>\n<p>This is how it may be used though.</p>\n<pre><code>let url = new URL('https://test.example.com/cats?name=foofy')\nurl.protocall; // https:\nurl.hostname; // test.example.com\nurl.pathname; // /cats\nurl.search; // ?name=foofy\n\nlet params = url.searchParams\nlet name = params.get('name');// always string I think so parse accordingly\n\n</code></pre>\n<p>for more on parameters also see <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams</a></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | Given the URL (single line):
<http://test.example.com/dir/subdir/file.html>
How can I extract the following parts using regular expressions:
1. The Subdomain (test)
2. The Domain (example.com)
3. The path without the file (/dir/subdir/)
4. The file (file.html)
5. The path with the file (/dir/subdir/file.html)
6. The URL without the path (<http://test.example.com>)
7. (add any other that you think would be useful)
The regex should work correctly even if I enter the following URL:
```
http://example.example.com/example/example/example.html
``` | >
> A single regex to parse and breakup a
> full URL including query parameters
> and anchors e.g.
>
>
> <https://www.google.com/dir/1/2/search.html?arg=0-a&arg1=1-b&arg3-c#hash>
>
>
> `^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$`
>
>
> RexEx positions:
>
>
> url: RegExp['$&'],
>
>
> protocol:RegExp.$2,
>
>
> host:RegExp.$3,
>
>
> path:RegExp.$4,
>
>
> file:RegExp.$6,
>
>
> query:RegExp.$7,
>
>
> hash:RegExp.$8
>
>
>
you could then further parse the host ('.' delimited) quite easily.
What **I** would do is use something like this:
```
/*
^(.*:)//([A-Za-z0-9\-\.]+)(:[0-9]+)?(.*)$
*/
proto $1
host $2
port $3
the-rest $4
```
the further parse 'the rest' to be as specific as possible. Doing it in one regex is, well, a bit crazy. |
27,757 | <p>I am storing a PNG as an embedded resource in an assembly. From within the same assembly I have some code like this:</p>
<pre><code>Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png");
</code></pre>
<p>The file, named "file.png" is stored in the "Resources" folder (within Visual Studio), and is marked as an embedded resource.</p>
<p>The code fails with an exception saying: </p>
<blockquote>
<p>Resource MyNamespace.Resources.file.png cannot be found in class MyNamespace.MyClass</p>
</blockquote>
<p>I have identical code (in a different assembly, loading a different resource) which works. So I know the technique is sound. My problem is I end up spending a lot of time trying to figure out what the correct path is. If I could simply query (eg. in the debugger) the assembly to find the correct path, that would save me a load of headaches.</p>
| [
{
"answer_id": 27769,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:</p>\n\n<pre><code>ProjectNamespace.Properties.Resources.file\n</code></pre>\n\n<p>Use the IDE's resource manager to add resources.</p>\n"
},
{
"answer_id": 27773,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 9,
"selected": true,
"text": "<p>This will get you a string array of all the resources:</p>\n\n<pre><code>System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();\n</code></pre>\n"
},
{
"answer_id": 28253,
"author": "Dylan",
"author_id": 3074,
"author_profile": "https://Stackoverflow.com/users/3074",
"pm_score": 6,
"selected": false,
"text": "<p>I find myself forgetting how to do this every time as well so I just wrap the two one-liners that I need in a little class:</p>\n\n<pre><code>public class Utility\n{\n /// <summary>\n /// Takes the full name of a resource and loads it in to a stream.\n /// </summary>\n /// <param name=\"resourceName\">Assuming an embedded resource is a file\n /// called info.png and is located in a folder called Resources, it\n /// will be compiled in to the assembly with this fully qualified\n /// name: Full.Assembly.Name.Resources.info.png. That is the string\n /// that you should pass to this method.</param>\n /// <returns></returns>\n public static Stream GetEmbeddedResourceStream(string resourceName)\n {\n return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);\n }\n\n /// <summary>\n /// Get the list of all emdedded resources in the assembly.\n /// </summary>\n /// <returns>An array of fully qualified resource names</returns>\n public static string[] GetEmbeddedResourceNames()\n {\n return Assembly.GetExecutingAssembly().GetManifestResourceNames();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 22045449,
"author": "user3356450",
"author_id": 3356450,
"author_profile": "https://Stackoverflow.com/users/3356450",
"pm_score": 2,
"selected": false,
"text": "<p>The name of the resource is the name space plus the \"pseudo\" name space of the path to the file. The \"pseudo\" name space is made by the sub folder structure using \\ (backslashes) instead of . (dots).</p>\n\n<pre><code>public static Stream GetResourceFileStream(String nameSpace, String filePath)\n{\n String pseduoName = filePath.Replace('\\\\', '.');\n Assembly assembly = Assembly.GetExecutingAssembly();\n return assembly.GetManifestResourceStream(nameSpace + \".\" + pseduoName);\n}\n</code></pre>\n\n<p>The following call:</p>\n\n<pre><code>GetResourceFileStream(\"my.namespace\", \"resources\\\\xml\\\\my.xml\")\n</code></pre>\n\n<p>will return the stream of my.xml located in the folder-structure resources\\xml in the name space: my.namespace.</p>\n"
},
{
"answer_id": 27993476,
"author": "masterwok",
"author_id": 563509,
"author_profile": "https://Stackoverflow.com/users/563509",
"pm_score": 3,
"selected": false,
"text": "<p>I use the following method to grab embedded resources:</p>\n<pre><code>protected static Stream GetResourceStream(string resourcePath)\n{\n Assembly assembly = Assembly.GetExecutingAssembly();\n List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());\n\n resourcePath = resourcePath.Replace(@"/", ".");\n resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath));\n\n if (resourcePath == null)\n throw new FileNotFoundException("Resource not found");\n\n return assembly.GetManifestResourceStream(resourcePath);\n}\n</code></pre>\n<p>I then call this with the path in the project:</p>\n<pre><code>GetResourceStream(@"DirectoryPathInLibrary/Filename");\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006/"
] | I am storing a PNG as an embedded resource in an assembly. From within the same assembly I have some code like this:
```
Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png");
```
The file, named "file.png" is stored in the "Resources" folder (within Visual Studio), and is marked as an embedded resource.
The code fails with an exception saying:
>
> Resource MyNamespace.Resources.file.png cannot be found in class MyNamespace.MyClass
>
>
>
I have identical code (in a different assembly, loading a different resource) which works. So I know the technique is sound. My problem is I end up spending a lot of time trying to figure out what the correct path is. If I could simply query (eg. in the debugger) the assembly to find the correct path, that would save me a load of headaches. | This will get you a string array of all the resources:
```
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
``` |
27,758 | <p>OK, I know what you're thinking, "why write a method you do not want people to use?" Right?</p>
<p>Well, in short, I have a class that needs to be serialized to XML. In order for the <a href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx" rel="noreferrer"><code>XmlSerializer</code></a> to do its magic, the class must have a default, empty constructor:</p>
<pre><code>public class MyClass
{
public MyClass()
{
// required for xml serialization
}
}
</code></pre>
<p>So, I need to have it, but I don't want people to <em>use</em> it, so <strong>is there any attribute that can be use to mark the method as "DO NOT USE"?</strong></p>
<p>I was thinking of using the <em>Obsolete</em> attribute (since this can stop the build), but that just seems kinda "wrong", is there any other way of doing this, or do I need to go ahead and bite the bullet? :)</p>
<h2>Update</h2>
<p>OK, I have accepted Keith's answer, since I guess in my heart of hearts, I totally agree. This is why I asked the question in the first place, I don't like the notion of having the <em>Obsolete</em> attribute.</p>
<h3>However...</h3>
<p>There <em>is</em> still a problem, while we are being notified in intellisense, ideally, we would like to break the build, so is there any way to do this? Perhaps create a custom attribute?</p>
<p><strong>More focused question has been created <a href="https://stackoverflow.com/questions/28150/create-an-attribute-to-break-the-build">here</a>.</strong></p>
| [
{
"answer_id": 27763,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 2,
"selected": false,
"text": "<p>I read the heading and immediately thought \"obsolete atribute\". How about</p>\n\n<pre><code> /// <summary>\n /// do not use\n /// </summary>\n /// <param name=\"item\">don't pass it anything -- you shouldn't use it.</param>\n /// <returns>nothing - you shouldn't use it</returns>\n public bool Include(T item) { \n ....\n</code></pre>\n"
},
{
"answer_id": 27764,
"author": "Sir Rippov the Maple",
"author_id": 2822,
"author_profile": "https://Stackoverflow.com/users/2822",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx\" rel=\"nofollow noreferrer\"><code>ObsoleteAttribute</code></a> will probably work in your situation - you can even cause the build to break if that method is used. </p>\n\n<p>Since obsolete warnings occur at compile time, and since the reflection needed for serialization occurs at runtime, marking that method obsolete won't break serialization, but will warn developers that the method is not there to be used.</p>\n"
},
{
"answer_id": 27765,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>What you're looking for is the <a href=\"http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx\" rel=\"nofollow noreferrer\"><code>ObsoleteAttribute</code></a> class:</p>\n\n<pre><code>using System;\n\npublic sealed class App {\n static void Main() { \n // The line below causes the compiler to issue a warning:\n // 'App.SomeDeprecatedMethod()' is obsolete: 'Do not call this method.'\n SomeDeprecatedMethod();\n }\n\n // The method below is marked with the ObsoleteAttribute. \n // Any code that attempts to call this method will get a warning.\n [Obsolete(\"Do not call this method.\")]\n private static void SomeDeprecatedMethod() { }\n}\n</code></pre>\n"
},
{
"answer_id": 27766,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 0,
"selected": false,
"text": "<p>Yep there is. </p>\n\n<p>I wrote this blogpost about it <a href=\"http://blogs.lessthandot.com/admin.php?ctrl=items&blog=4&p=104\" rel=\"nofollow noreferrer\">Working with the designer</a>.</p>\n\n<p>And here is the code:</p>\n\n<p><pre><code>\npublic class MyClass\n{\n [Obsolete(\"reason\", true)]\n public MyClass()\n {\n // required for xml serialization\n }\n}\n</pre></code></p>\n"
},
{
"answer_id": 27767,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using the <a href=\"http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx\" rel=\"nofollow noreferrer\"><code>ObsoleteAttribute</code></a>.</p>\n\n<p>But also you can have some comments of course.</p>\n\n<p>And finally remove it completely if you can (don't have to maintain the compatibility with something old). That's the best way.</p>\n"
},
{
"answer_id": 27796,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>Wow, that problem is bugging me too. </p>\n\n<p>You also need default constructors for NHibernate, but I want to force people to NOT use C# 3.0 object initializers so that classes go through constructor code.</p>\n"
},
{
"answer_id": 27825,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": true,
"text": "<p>If a class is <a href=\"https://msdn.microsoft.com/en-us/library/system.serializableattribute%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>[Serialisable]</code></a> (i.e. it can be copied around the place as needed) the param-less constructor is needed to deserialise.</p>\n\n<p>I'm guessing that you want to force your code's access to pass defaults for your properties to a parameterised constructor.</p>\n\n<p>Basically you're saying that it's OK for the <a href=\"https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>XmlSerializer</code></a> to make a copy and then set properties, but you don't want your own code to.</p>\n\n<p>To some extent I think this is over-designing. </p>\n\n<p>Just add XML comments that detail what properties need initialising (and what to). </p>\n\n<p>Don't use <a href=\"https://msdn.microsoft.com/en-us/library/system.obsoleteattribute%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>[Obsolete]</code></a>, because it isn't. Reserve that for genuinely deprecated methods.</p>\n"
},
{
"answer_id": 27906,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "<p>I would actually be inclined to disagree with everyone that is advocating the use of the <a href=\"http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx\" rel=\"nofollow noreferrer\"><code>ObsoleteAttribute</code></a> as the MSDN documentation says that:</p>\n\n<blockquote>\n <p>Marking an element as obsolete informs the users that the element will be removed in future versions of the product.</p>\n</blockquote>\n\n<p>Since the generic constructors for XML serialization should not be removed from the application I wouldn't apply it just in case a maintenance developer down the road is not familiar with how XML serialization works. </p>\n\n<p>I have actually been using <a href=\"https://stackoverflow.com/questions/27758/notify-developer-of-a-do-not-use-method#27825\">Keith's</a> method of just noting that the constructor is used for serialization in XML documentation so that it shows up in Intellisense.</p>\n"
},
{
"answer_id": 29068,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Prior to VS2013</strong> you could use:</p>\n<p><code>[<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.editorbrowsableattribute\" rel=\"nofollow noreferrer\">System.ComponentModel.EditorBrowsable</a>(<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.editorbrowsablestate\" rel=\"nofollow noreferrer\">System.ComponentModel.EditorBrowsableState.Never</a>)]\n</code></p>\n<p>so that it doesn't show up in IntelliSense. If the consumer still wants to use it they can, but it won't be as discoverable.</p>\n<p><a href=\"https://stackoverflow.com/a/27825/3195477\">Keith's point</a> about over-engineering still stands though.</p>\n<hr />\n<p><strong>Since VS2013</strong> this feature has been removed. As noted in <a href=\"https://github.com/dotnet/roslyn/issues/37478\" rel=\"nofollow noreferrer\">https://github.com/dotnet/roslyn/issues/37478</a> this was "by design" and apparently will not be brought back.</p>\n"
},
{
"answer_id": 29079,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 2,
"selected": false,
"text": "<p>You could build your own <a href=\"https://msdn.microsoft.com/en-us/library/system.attribute(v=vs.110).aspx\" rel=\"nofollow noreferrer\"><code>Attribute</code></a> derived class, say <code>NonCallableAttribute</code> to qualify methods, and then add to your build/CI code analysis task the check to monitor if any code is using those methods.</p>\n\n<p>In my opinion, you really cannot force developers to not use the method, but you could detect when someone broke the rule as soon as possible and fix it.</p>\n"
},
{
"answer_id": 29090,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<pre><code>throw new ISaidDoNotUseException();\n</code></pre>\n"
},
{
"answer_id": 29212,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Separate your serializable object from your domain object.</p>\n"
},
{
"answer_id": 60097575,
"author": "Lukáš Kmoch",
"author_id": 2945197,
"author_profile": "https://Stackoverflow.com/users/2945197",
"pm_score": 0,
"selected": false,
"text": "<p>There is already quite a lot of good answers.\nBut I think the best option is to use serializer that can use parametrized constructor.\nIt is not serializer you need but for example Entity Framework Core knows how to use parametrized constructors.</p>\n\n<p><strong>Entity Framework Core documentation:</strong></p>\n\n<blockquote>\n <p>If EF Core finds a parameterized constructor with parameter names and\n types that match those of mapped properties, then it will instead call\n the parameterized constructor with values for those properties and\n will not set each property explicitly.</p>\n</blockquote>\n"
},
{
"answer_id": 72444002,
"author": "Saly",
"author_id": 720275,
"author_profile": "https://Stackoverflow.com/users/720275",
"pm_score": 2,
"selected": false,
"text": "<p>Nowadays you can use <em>code analyzers</em> for such need - thanks to Roslyn compiler in modern .NET.</p>\n<p>Either you can write your own code analyzer. Here are some tips to start with:</p>\n<ul>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix</a></li>\n<li><a href=\"https://andrewlock.net/creating-a-roslyn-analyzer-in-visual-studio-2017/\" rel=\"nofollow noreferrer\">https://andrewlock.net/creating-a-roslyn-analyzer-in-visual-studio-2017/</a></li>\n<li><a href=\"https://www.meziantou.net/writing-a-roslyn-analyzer.htm\" rel=\"nofollow noreferrer\">https://www.meziantou.net/writing-a-roslyn-analyzer.htm</a></li>\n</ul>\n<p>Or use some already existing - this is way I have choosen for my needs:</p>\n<ul>\n<li><a href=\"https://github.com/dotnet/roslyn-analyzers/blob/5968beca1c5c6c12d4fa81a08b7b4561a3c05d6e/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md\" rel=\"nofollow noreferrer\">BannedApiAnalzyers</a> - <strong>this one is exactly for the "DO NOT USE" warning</strong></li>\n</ul>\n<p>Here is another nice "homepage" for Roslyn Analyzers:\nCybermaxs/awesome-analyzers: A curated list of .NET Compiler Platform ("Roslyn") diagnostic analyzers and code fixes. Everyone can contribute here!\n<a href=\"https://github.com/Cybermaxs/awesome-analyzers\" rel=\"nofollow noreferrer\">https://github.com/Cybermaxs/awesome-analyzers</a></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | OK, I know what you're thinking, "why write a method you do not want people to use?" Right?
Well, in short, I have a class that needs to be serialized to XML. In order for the [`XmlSerializer`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx) to do its magic, the class must have a default, empty constructor:
```
public class MyClass
{
public MyClass()
{
// required for xml serialization
}
}
```
So, I need to have it, but I don't want people to *use* it, so **is there any attribute that can be use to mark the method as "DO NOT USE"?**
I was thinking of using the *Obsolete* attribute (since this can stop the build), but that just seems kinda "wrong", is there any other way of doing this, or do I need to go ahead and bite the bullet? :)
Update
------
OK, I have accepted Keith's answer, since I guess in my heart of hearts, I totally agree. This is why I asked the question in the first place, I don't like the notion of having the *Obsolete* attribute.
### However...
There *is* still a problem, while we are being notified in intellisense, ideally, we would like to break the build, so is there any way to do this? Perhaps create a custom attribute?
**More focused question has been created [here](https://stackoverflow.com/questions/28150/create-an-attribute-to-break-the-build).** | If a class is [`[Serialisable]`](https://msdn.microsoft.com/en-us/library/system.serializableattribute%28v=vs.110%29.aspx) (i.e. it can be copied around the place as needed) the param-less constructor is needed to deserialise.
I'm guessing that you want to force your code's access to pass defaults for your properties to a parameterised constructor.
Basically you're saying that it's OK for the [`XmlSerializer`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx) to make a copy and then set properties, but you don't want your own code to.
To some extent I think this is over-designing.
Just add XML comments that detail what properties need initialising (and what to).
Don't use [`[Obsolete]`](https://msdn.microsoft.com/en-us/library/system.obsoleteattribute%28v=vs.110%29.aspx), because it isn't. Reserve that for genuinely deprecated methods. |
27,774 | <p>Effectively I want to give numeric scores to alphabetic grades and sum them. In Excel, putting the <code>LOOKUP</code> function into an array formula works:</p>
<pre><code>{=SUM(LOOKUP(grades, scoringarray))}
</code></pre>
<p>With the <code>VLOOKUP</code> function this does not work (only gets the score for the first grade). Google Spreadsheets does not appear to have the <code>LOOKUP</code> function and <code>VLOOKUP</code> fails in the same way using:</p>
<pre><code>=SUM(ARRAYFORMULA(VLOOKUP(grades, scoresarray, 2, 0)))
</code></pre>
<p>or</p>
<pre><code>=ARRAYFORMULA(SUM(VLOOKUP(grades, scoresarray, 2, 0)))
</code></pre>
<p>Is it possible to do this (but I have the syntax wrong)? Can you suggest a method that allows having the calculation in one simple cell like this rather than hiding the lookups somewhere else and summing them afterwards?</p>
| [
{
"answer_id": 28132,
"author": "paulmorriss",
"author_id": 2983,
"author_profile": "https://Stackoverflow.com/users/2983",
"pm_score": 2,
"selected": false,
"text": "<p>I'm afraid I think the answer is no. From the help text on\n<a href=\"http://docs.google.com/support/spreadsheets/bin/answer.py?answer=71291&query=arrayformula&topic=&type=\" rel=\"nofollow noreferrer\">http://docs.google.com/support/spreadsheets/bin/answer.py?answer=71291&query=arrayformula&topic=&type=</a></p>\n\n<blockquote>\n <p>The real power of ARRAYFORMULA comes when you take the result from one of those computations and wrap it inside a formula that does take array or range arguments: SUM, MAX, MIN, CONCATENATE,</p>\n</blockquote>\n\n<p>As vlookup takes a single cell to lookup (in the first argument) I don't think you can get it to work, without using a separate range of lookups.</p>\n"
},
{
"answer_id": 29690,
"author": "Sam Brightman",
"author_id": 2492,
"author_profile": "https://Stackoverflow.com/users/2492",
"pm_score": 1,
"selected": true,
"text": "<p>I still can't see the formulae in your example (just values), but that is exactly what I'm trying to do in terms of the result; obviously I can already do it \"by the side\" and sum separately - the key for me is doing it in one cell.</p>\n\n<p>I have looked at it again this morning - using the <code>MATCH</code> function for the lookup works in an array formula. But then the <code>INDEX</code> function does not. I have also tried using it with <code>OFFSET</code> and <code>INDIRECT</code> without success. Finally, the <code>CHOOSE</code> function does not seem to accept a cell range as its list to choose from - the range degrades to a single value (the first cell in the range). It should also be noted that the <code>CHOOSE</code> function only accepts 30 values to choose from (according to the documentation). All very annoying. However, I do now have a working solution in one cell: using the <code>CHOOSE</code> function and explicitly listing the result cells one by one in the arguments like this:</p>\n\n<pre><code>=ARRAYFORMULA(SUM(CHOOSE(MATCH(D1:D8,Lookups!$A$1:$A$3,0),\n Lookups!$B$1,Lookups!$B$2,Lookups!$B$3)))\n</code></pre>\n\n<p>Obviously this doesn't extend very well but hopefully the lookup tables are by nature quite fixed. For larger lookup tables it's a pain to type all the cells individually and some people may exceed the limit of 30 cells.</p>\n\n<p>I would certainly welcome a more elegant solution!</p>\n"
},
{
"answer_id": 14738977,
"author": "HHains",
"author_id": 2048572,
"author_profile": "https://Stackoverflow.com/users/2048572",
"pm_score": 0,
"selected": false,
"text": "<p>I know this thread is quite old, but I'd been struggling with this same problem for some time. I finally came across a solution (well, Frankenstiened one together). It's only slightly more elegant, but should be able to work with large data sets without trouble.</p>\n\n<p>The solution uses the following:</p>\n\n<pre><code>=ARRAYFORMULA(SUM(INDIRECT(ADDRESS(MATCH(), MATCH())))\n</code></pre>\n\n<p>as a surrogate for the vlookup function.</p>\n\n<p>I hope this helps someone!</p>\n"
},
{
"answer_id": 51566590,
"author": "pnuts",
"author_id": 1505120,
"author_profile": "https://Stackoverflow.com/users/1505120",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Google Spreadsheets does not appear to have the LOOKUP function</p>\n</blockquote>\n\n<p>Presumably not then but it does have now:</p>\n\n<p><a href=\"https://i.stack.imgur.com/l4Qo6.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l4Qo6.gif\" alt=\"SO27774 example\"></a></p>\n\n<p><code>grades</code> Sheet1!A2:A4<br>\n<code>scoringarray</code> Sheet1!A2:B4</p>\n"
},
{
"answer_id": 55196805,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "<p>you can do so easily like this by hardcoding it in VR table:</p>\n\n<pre><code>=SUM(IFERROR(ARRAYFORMULA(VLOOKUP(A2:A, {{\"A\", 6};\n {\"B\", 5};\n {\"C\", 4};\n {\"D\", 3};\n {\"E\", 2};\n {\"F\", 1}}, 2, 0)), ))\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/vVS8B.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vVS8B.png\" alt=\"0\"></a></p>\n\n<p>or you can use some side cells with rules:</p>\n\n<pre><code>=SUM(IFERROR(ARRAYFORMULA(VLOOKUP(A2:A, E2:F, 2, 0)), ))\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/hd1GN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hd1GN.png\" alt=\"6\"></a></p>\n\n<hr>\n\n<p><strong><sub>alternatives: <a href=\"https://webapps.stackexchange.com/a/123741/186471\">https://webapps.stackexchange.com/a/123741/186471</a></sub></strong></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2492/"
] | Effectively I want to give numeric scores to alphabetic grades and sum them. In Excel, putting the `LOOKUP` function into an array formula works:
```
{=SUM(LOOKUP(grades, scoringarray))}
```
With the `VLOOKUP` function this does not work (only gets the score for the first grade). Google Spreadsheets does not appear to have the `LOOKUP` function and `VLOOKUP` fails in the same way using:
```
=SUM(ARRAYFORMULA(VLOOKUP(grades, scoresarray, 2, 0)))
```
or
```
=ARRAYFORMULA(SUM(VLOOKUP(grades, scoresarray, 2, 0)))
```
Is it possible to do this (but I have the syntax wrong)? Can you suggest a method that allows having the calculation in one simple cell like this rather than hiding the lookups somewhere else and summing them afterwards? | I still can't see the formulae in your example (just values), but that is exactly what I'm trying to do in terms of the result; obviously I can already do it "by the side" and sum separately - the key for me is doing it in one cell.
I have looked at it again this morning - using the `MATCH` function for the lookup works in an array formula. But then the `INDEX` function does not. I have also tried using it with `OFFSET` and `INDIRECT` without success. Finally, the `CHOOSE` function does not seem to accept a cell range as its list to choose from - the range degrades to a single value (the first cell in the range). It should also be noted that the `CHOOSE` function only accepts 30 values to choose from (according to the documentation). All very annoying. However, I do now have a working solution in one cell: using the `CHOOSE` function and explicitly listing the result cells one by one in the arguments like this:
```
=ARRAYFORMULA(SUM(CHOOSE(MATCH(D1:D8,Lookups!$A$1:$A$3,0),
Lookups!$B$1,Lookups!$B$2,Lookups!$B$3)))
```
Obviously this doesn't extend very well but hopefully the lookup tables are by nature quite fixed. For larger lookup tables it's a pain to type all the cells individually and some people may exceed the limit of 30 cells.
I would certainly welcome a more elegant solution! |
27,818 | <p>We've embedded an OSGi runtime (Equinox) into out custom client-server application to facilitate plugin development and so far things are going great. We've been using Eclipse to build plugins due to the built-in manifest editor, dependency management, and export wizard. Using Eclipse to manager builds isn't very conducive to continuous integration via Hudson.</p>
<p>We have OSGi bundles which depend on other OSGi bundles. I'd really hate to hardcode build order in a custom ANT build. We've done this is the past and it's pretty horrible. Is there any build tool that can EASILY manage OSGi dependencies, if not automatically resolve them? Are there any DECENT examples of how to this?</p>
<p>CLARIFICATION:</p>
<p>The generated build scripts are only usable via Eclipse. They require manually running pieces of Eclipse. We've also got some standard targets which the Eclipse build won't have, and I don't want to modify the generated file since I may regenerate (I know I can do includes, but I want to avoid the Eclipse gen file all together)</p>
<p>Here is my project layout:</p>
<pre><code>/
-PluginA
-PluginB
-PluginC
.
.
.
</code></pre>
<p>In using the Eclipse PDE, each plugin has a Manifest, but no build.xml as the PDE does that for me. Hard to automate a gui driven process w/ Hudson. I'd like to setup my own build.xml to build each, BUT there are dependencies and build order issues. These issues are driven by the Manifest files (which describe OSGi imports). For example, PluginC depends on PluginB which depends on PluginA. They must be built in the correct order. I realize that I can manually control the build order, I'm looking for a tool to help automate the build order dependency management.</p>
| [
{
"answer_id": 45671,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 1,
"selected": false,
"text": "<p>We use <a href=\"http://www.eclipse.org/buckminster/\" rel=\"nofollow noreferrer\">Buckminster</a>. It's a build and assembly framework, which takes care of the resolution of dependencies, the fetching from various repositories, building and packaging of the product.</p>\n\n<p>It's an Eclipse Tools project. It integrates well with PDE. </p>\n\n<p>This means that all the meta-data we use to build the RCP is useful to Buckminster to resolve and build. For example, feature.xml and the Require-Bundle header in the Manifest.MF, .product.</p>\n\n<p>We haven't got any build scripts in each bundle now; we now have a single build per product. Buckminster takes care walking the dependency graph.</p>\n\n<p>It took a little bit of effort to get our existing cruise-control/ant system working with it, though they (the Buckminster team) have started using Hudson to host the project itself. I believe that their build setup is also available for download.</p>\n\n<p>We're really impressed with it, despite it's relative infancy.</p>\n\n<p>We also looked into <a href=\"http://www.ops4j.org/projects/pax/construct/index.html\" rel=\"nofollow noreferrer\">Pax-Construct</a> but we didn't want to use Maven.</p>\n\n<p>We're also currently looking at <a href=\"http://static.springframework.org/osgi/docs/1.1.0/reference/html/testing.html\" rel=\"nofollow noreferrer\">Spring DM testing framework</a> to augment the unit testing effort.</p>\n"
},
{
"answer_id": 45786,
"author": "Boris Terzic",
"author_id": 1996,
"author_profile": "https://Stackoverflow.com/users/1996",
"pm_score": 3,
"selected": false,
"text": "<p>Maven2 all the way; has an Eclipse plugin called <a href=\"http://m2eclipse.codehaus.org/\" rel=\"nofollow noreferrer\">m2eclipse</a> to help with managing it, solves exactly the dependency problem and then some. Has a <a href=\"http://www.sonatype.com/community/definitive_guide.html\" rel=\"nofollow noreferrer\">free online book as documentation</a>.</p>\n\n<p>Specifically look at <a href=\"http://www.sonatype.com/book/reference/multimodule.html#\" rel=\"nofollow noreferrer\">multi-module projects</a> for bundling many components together and have Maven work out the build order and dependencies.</p>\n\n<p>There is also a <a href=\"http://www.sonatype.com/book/reference/eclipse.html#\" rel=\"nofollow noreferrer\">chapter on the Eclipse integration</a>.</p>\n\n<p>And that is just Eclipse and Maven, next you get some cool goodies for OSGi:</p>\n\n<ul>\n<li>The <a href=\"http://felix.apache.org/site/maven-bundle-plugin-bnd.html\" rel=\"nofollow noreferrer\">Apache Felix BND Maven plugin</a> will auto-generate your manifests or at the very least help you</li>\n<li>The <a href=\"http://www.ops4j.org/projects/pax/maven/\" rel=\"nofollow noreferrer\">PAX OPS4J project</a> and their Maven plugins can be a great help in bootstrapping projects, providing launchers, etc</li>\n</ul>\n\n<p>And just fundamentally, the Maven module model fits perfectly with OSGi's bundle model. We've been building and managing multiple products with hundreds of bundles using Maven for more than 3 years now and it's great.</p>\n"
},
{
"answer_id": 46936,
"author": "Andreas Kraft",
"author_id": 4799,
"author_profile": "https://Stackoverflow.com/users/4799",
"pm_score": 0,
"selected": false,
"text": "<p>Can you please elaborate where the problem occurs? You mention OSGi bundle dependencies. Is this during runtime? Or during compile-time? In the first case you should consider Declarative Services (see OSGi Spec).</p>\n"
},
{
"answer_id": 208294,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>We use Hudson combined with <a href=\"http://www.pluginbuilder.org/\" rel=\"nofollow noreferrer\">PluginBuilder</a> to build our Eclipse-based OSGi bundles/plugins. This builds upon Eclipse's standard PDE process for building plugins. This means using Eclipse as the compiler.</p>\n"
},
{
"answer_id": 236483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Seconding Maven2. Look into the Tycho plugins for building - they use Eclipse's JDT compiler so it implements all of the OSGi rules at compile-time, the same way Eclipse does at runtime.</p>\n\n<p>Alternatively, the Apache Felix BND plugins also seem popular. I prefer Tycho because it more closely seems to unify the Maven and Eclipse development environments.</p>\n"
},
{
"answer_id": 478654,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 2,
"selected": true,
"text": "<p>Closing out some old questions...</p>\n\n<p>Our setup was not conducive to maven due to lack of network connectivity and timing. I know there are offline maven setups, but it was all too much given the time. Hopefully we'll get to use a proper setup when we've got time to reorganize the build process.</p>\n\n<p>The solution involved Ant, BND, and some custom ant tasks. The various bundle dependencies are manually managed. We were already using Ant; BND and custom tasks tied it all together. The custom tasks just made sure our bnd/eclipse projects were in sync.</p>\n"
},
{
"answer_id": 3135356,
"author": "Kevin",
"author_id": 378364,
"author_profile": "https://Stackoverflow.com/users/378364",
"pm_score": 1,
"selected": false,
"text": "<p>PDE Headless build. It's well documented by Eclipse. If you're building Eclipse plugins, and you want to do it via command line, The Eclipse PDE headless build is THE way to go.</p>\n"
},
{
"answer_id": 5155085,
"author": "mike",
"author_id": 639398,
"author_profile": "https://Stackoverflow.com/users/639398",
"pm_score": 0,
"selected": false,
"text": "<p>I use maven 3.0.2</p>\n\n<p>mvn generate:archetype</p>\n\n<pre><code>select 252 - osgi-archetype\nmvn idea:idea\n</code></pre>\n\n<p>see <a href=\"http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html\" rel=\"nofollow\">http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html</a></p>\n\n<p>to add your dependencies into the bundle use this short example in the pom.xml</p>\n\n<pre><code><Export-Package>org.foo.myproject.api</Export-Package>\n</code></pre>\n\n<p>or</p>\n\n<pre><code><Import-Package>org.foo.myproject.api</Import-Package>\n</code></pre>\n"
},
{
"answer_id": 6680679,
"author": "Mircea D.",
"author_id": 842897,
"author_profile": "https://Stackoverflow.com/users/842897",
"pm_score": 0,
"selected": false,
"text": "<p>Maven does not require internet connectivity! Use the -o switch, for Christ's sake.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287/"
] | We've embedded an OSGi runtime (Equinox) into out custom client-server application to facilitate plugin development and so far things are going great. We've been using Eclipse to build plugins due to the built-in manifest editor, dependency management, and export wizard. Using Eclipse to manager builds isn't very conducive to continuous integration via Hudson.
We have OSGi bundles which depend on other OSGi bundles. I'd really hate to hardcode build order in a custom ANT build. We've done this is the past and it's pretty horrible. Is there any build tool that can EASILY manage OSGi dependencies, if not automatically resolve them? Are there any DECENT examples of how to this?
CLARIFICATION:
The generated build scripts are only usable via Eclipse. They require manually running pieces of Eclipse. We've also got some standard targets which the Eclipse build won't have, and I don't want to modify the generated file since I may regenerate (I know I can do includes, but I want to avoid the Eclipse gen file all together)
Here is my project layout:
```
/
-PluginA
-PluginB
-PluginC
.
.
.
```
In using the Eclipse PDE, each plugin has a Manifest, but no build.xml as the PDE does that for me. Hard to automate a gui driven process w/ Hudson. I'd like to setup my own build.xml to build each, BUT there are dependencies and build order issues. These issues are driven by the Manifest files (which describe OSGi imports). For example, PluginC depends on PluginB which depends on PluginA. They must be built in the correct order. I realize that I can manually control the build order, I'm looking for a tool to help automate the build order dependency management. | Closing out some old questions...
Our setup was not conducive to maven due to lack of network connectivity and timing. I know there are offline maven setups, but it was all too much given the time. Hopefully we'll get to use a proper setup when we've got time to reorganize the build process.
The solution involved Ant, BND, and some custom ant tasks. The various bundle dependencies are manually managed. We were already using Ant; BND and custom tasks tied it all together. The custom tasks just made sure our bnd/eclipse projects were in sync. |
27,832 | <p>I have a DirectShow graph to render MPEG2/4 movies from a network stream. When I assemble the graph by connecting the pins manually it doesn't render. But when I call Render on the GraphBuilder it renders fine. </p>
<p>Obviously there is some setup step that I'm not performing on some filter in the graph that GraphBuilder is performing. </p>
<p>Is there any way to see debug output from GraphBuilder when it assembles a graph?</p>
<p>Is there a way to dump a working graph to see how it was put together?</p>
<p>Any other ideas for unraveling the mystery that lives in the DirectShow box?</p>
<p>Thanks!
-Z</p>
| [
{
"answer_id": 27858,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 5,
"selected": true,
"text": "<p>You can watch the graph you created using GraphEdit, a tool from the DirectShow SDK. In GraphEdit, select File->Connect to remote Graph...</p>\n\n<p>In order to find your graph in the list, you have to register it in the running object table:</p>\n\n<pre><code>void AddToRot( IUnknown *pUnkGraph, DWORD *pdwRegister ) \n{\n IMoniker* pMoniker;\n IRunningObjectTable* pROT;\n GetRunningObjectTable( 0, &pROT );\n\n WCHAR wsz[256]; \n swprintf_s( wsz, L\"FilterGraph %08p pid %08x\", (DWORD_PTR)pUnkGraph, GetCurrentProcessId() );\n CreateItemMoniker( L\"!\", wsz, &pMoniker );\n\n pROT->Register( 0, pUnkGraph, pMoniker, pdwRegister );\n\n // Clean up any COM stuff here ...\n}\n</code></pre>\n\n<p>After destroying your graph, you should remove it from the ROT by calling IRunningObjectTable::Revoke</p>\n"
},
{
"answer_id": 66739,
"author": "Jon Clegg",
"author_id": 1489,
"author_profile": "https://Stackoverflow.com/users/1489",
"pm_score": 0,
"selected": false,
"text": "<p>Older versions of DirectX, I belive 9a, but not 9b had a \"debug mode\" for dshow. It would output logs of debug info into the debug console. </p>\n\n<p>So download an older version, set it to debug. then open up debugview or load graphedt.exe in visual studio to see the debug info.</p>\n"
},
{
"answer_id": 1070337,
"author": "Cristian Adam",
"author_id": 131814,
"author_profile": "https://Stackoverflow.com/users/131814",
"pm_score": 3,
"selected": false,
"text": "<p>Roman Ryltsov has created a DirectShow Filter Graph Spy tool (<a href=\"http://alax.info/blog/777\" rel=\"noreferrer\">http://alax.info/blog/777</a>), a wrapper COM dll over the FilterGraph interface, which logs all the calls to FilterGraph methods.</p>\n\n<p>Also it will add all the created graphs into Running Object Table (ROT) which you can then visualize using tools like GraphEdit or GraphStudio. Very useful when you need to see how a Windows Media Player graph looks like.</p>\n"
},
{
"answer_id": 5515482,
"author": "persiflage",
"author_id": 222026,
"author_profile": "https://Stackoverflow.com/users/222026",
"pm_score": 3,
"selected": false,
"text": "<p>IGraphBuilder::SetLogFile (see <a href=\"http://msdn.microsoft.com/en-us/library/dd390091(v=vs.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/dd390091(v=vs.85).aspx</a>) will give you lots of useful diagnostic information about what happens during graph building. Pass in a file handle (e.g. opened by CreateFile) and cast it to a DWORD_PTR. Call again with NULL to finish logging before you close the file handle.</p>\n\n<p>The code in the following blog post for dumping a graph will give you some extra information to interpret the numbers in the log file.</p>\n\n<p><a href=\"http://rxwen.blogspot.com/2010/04/directshow-debugging-tips.html\" rel=\"noreferrer\">http://rxwen.blogspot.com/2010/04/directshow-debugging-tips.html</a></p>\n"
},
{
"answer_id": 7625454,
"author": "Aliza",
"author_id": 2885493,
"author_profile": "https://Stackoverflow.com/users/2885493",
"pm_score": 1,
"selected": false,
"text": "<p>There is a detailed MSDN entry on this.\n<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/dd390650(v=vs.85).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/dd390650(v=vs.85).aspx</a></p>\n"
},
{
"answer_id": 11781370,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 0,
"selected": false,
"text": "<p>You could \"save\" the graph (serialize it) to a .grf graphedit file, possibly: <a href=\"https://stackoverflow.com/a/10612735/32453\">https://stackoverflow.com/a/10612735/32453</a></p>\n\n<p>Also it appears that graphedit can \"remote attach\" to a running graph? <a href=\"http://rxwen.blogspot.com/2010/04/directshow-debugging-tips.html\" rel=\"nofollow noreferrer\">http://rxwen.blogspot.com/2010/04/directshow-debugging-tips.html</a></p>\n"
},
{
"answer_id": 26786068,
"author": "Nitay",
"author_id": 328059,
"author_profile": "https://Stackoverflow.com/users/328059",
"pm_score": 1,
"selected": false,
"text": "<p>You need to:</p>\n\n<ol>\n<li>Register you filter graph to the \"Running Objects Table\" - ROT - Using the code below</li>\n<li>Connect to your filter graph using GraphEdit (File->Connect to Remote Graph) or even better - With <a href=\"http://www.infognition.com/GraphEditPlus/\" rel=\"nofollow\">GraphEditPlus</a></li>\n</ol>\n\n<p>To register your filter graph as a \"connectable\" graph, call this with your filter graph:</p>\n\n<pre><code>void AddToROT( IUnknown *pUnkGraph, DWORD *pdwRegister ) \n{\n IMoniker * pMoniker;\n IRunningObjectTable *pROT;\n WCHAR wsz[128];\n HRESULT hr;\n\n if (FAILED(GetRunningObjectTable(0, &pROT)))\n return;\n\n wsprintfW(wsz, L\"FilterGraph %08x pid %08x\", (DWORD_PTR)pUnkGraph, GetCurrentProcessId());\n\n hr = CreateItemMoniker(L\"!\", wsz, &pMoniker);\n if (SUCCEEDED(hr)) \n {\n hr = pROT->Register(0, pUnkGraph, pMoniker, pdwRegister);\n pMoniker->Release();\n }\n\n pROT->Release();\n}\n</code></pre>\n\n<p>And call this before you release the graph:</p>\n\n<pre><code>void RemoveFromROT(DWORD pdwRegister)\n{\n IRunningObjectTable *pROT;\n\n if (SUCCEEDED(GetRunningObjectTable(0, &pROT))) \n {\n pROT->Revoke(pdwRegister);\n pROT->Release();\n }\n}\n</code></pre>\n\n<p>`</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2587612/"
] | I have a DirectShow graph to render MPEG2/4 movies from a network stream. When I assemble the graph by connecting the pins manually it doesn't render. But when I call Render on the GraphBuilder it renders fine.
Obviously there is some setup step that I'm not performing on some filter in the graph that GraphBuilder is performing.
Is there any way to see debug output from GraphBuilder when it assembles a graph?
Is there a way to dump a working graph to see how it was put together?
Any other ideas for unraveling the mystery that lives in the DirectShow box?
Thanks!
-Z | You can watch the graph you created using GraphEdit, a tool from the DirectShow SDK. In GraphEdit, select File->Connect to remote Graph...
In order to find your graph in the list, you have to register it in the running object table:
```
void AddToRot( IUnknown *pUnkGraph, DWORD *pdwRegister )
{
IMoniker* pMoniker;
IRunningObjectTable* pROT;
GetRunningObjectTable( 0, &pROT );
WCHAR wsz[256];
swprintf_s( wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)pUnkGraph, GetCurrentProcessId() );
CreateItemMoniker( L"!", wsz, &pMoniker );
pROT->Register( 0, pUnkGraph, pMoniker, pdwRegister );
// Clean up any COM stuff here ...
}
```
After destroying your graph, you should remove it from the ROT by calling IRunningObjectTable::Revoke |
27,846 | <p>What is the configuration setting for modifying the default homepage in a Grails application to no longer be appName/index.gsp? Of course you can set that page to be a redirect but there must be a better way.</p>
| [
{
"answer_id": 62067,
"author": "dahernan",
"author_id": 6435,
"author_profile": "https://Stackoverflow.com/users/6435",
"pm_score": 4,
"selected": false,
"text": "<p>Edit UrlMappings.groovy</p>\n\n<p>Add for example add this rule, to handle the root with a HomeController.</p>\n\n<p>\"/\"(controller:'home')</p>\n"
},
{
"answer_id": 62316,
"author": "Bob Herrmann",
"author_id": 6580,
"author_profile": "https://Stackoverflow.com/users/6580",
"pm_score": 6,
"selected": false,
"text": "<p>Add this in UrlMappings.groovy </p>\n\n<pre>\n \"/\" {\n controller = \"yourController\"\n action = \"yourAction\"\n }\n</pre>\n\n<p>By configuring the URLMappings this way, the home-page of the app will be yourWebApp/yourController/yourAction.</p>\n\n<p>(cut/pasted from <a href=\"http://blog.intelligrape.com/?p=18\" rel=\"noreferrer\">IntelliGrape Blog</a>)</p>\n"
},
{
"answer_id": 8580886,
"author": "element40",
"author_id": 845579,
"author_profile": "https://Stackoverflow.com/users/845579",
"pm_score": 2,
"selected": false,
"text": "<p>Simple and Neat</p>\n\n<ol>\n<li><p>Go to File: grails-app/conf/UrlMappings.groovy.</p></li>\n<li><p>Replace the line : \"/\"(view:\"/index\") with \n\"/\"(controller:'home', action:\"/index\").</p></li>\n</ol>\n\n<p>Home is Your Controller to Run(Like in spring security you can use 'login' ) and action is the grails view page associated with your controller(In Spring Security '/auth').</p>\n\n<p>Add redirection of pages as per your application needs.</p>\n"
},
{
"answer_id": 17335212,
"author": "Rashedul.Rubel",
"author_id": 1632305,
"author_profile": "https://Stackoverflow.com/users/1632305",
"pm_score": 4,
"selected": false,
"text": "<p>You may try as follows<br>\nin the UrlMappings.groovy class which is inside the configuration folder:</p>\n\n<pre><code>class UrlMappings {\n\n static mappings = {\n\n \"/$controller/$action?/$id?\"{\n constraints {\n // apply constraints here\n }\n }\n\n //\"/\"(view:\"/index\")\n \"/\" ( controller:'Item', action:'index' ) // Here i have changed the desired action to show the desired page while running the application\n \"500\"(view:'/error')\n }\n}\n</code></pre>\n\n<p>hope this helps,<br>\nRubel</p>\n"
},
{
"answer_id": 26539671,
"author": "Mehul Katpara",
"author_id": 4093220,
"author_profile": "https://Stackoverflow.com/users/4093220",
"pm_score": 0,
"selected": false,
"text": "<p>All the answers are correct!\nBut let's imagine a scenario: </p>\n\n<p>I mapped path \"/\" with the controller: \"Home\" and action: \"index\", so when i access \"/app-name/\" the controller Home gets executed, but if i type the path \"/app-name/home/index\", it will still be executed! so there are 2 paths for one resources. it would work until some one finds out \"home/index\" path.</p>\n\n<p>another thing is if I have a form without any action attribute specified, so by default it will be POST to the same controller and action! so if the form is mapped to \"/\" path and no action attribute is specified then it will be submitted to the same controller, but this time the path will be \"home/index\" in your address-bar, not \"/\", because it's being submitted to the controller/action not to the URI.</p>\n\n<p>To solve this problem what you have to do, is to remove or comment out these lines.</p>\n\n<pre><code>// \"/$controller/$action?/$id?(.$format)?\"{\n// constraints {\n// // apply constraints here\n// }\n// }\n</code></pre>\n\n<p>So now when you access \"/\", will work. but \"home/index\" will not. But there's a one flaw, now you have to map all the paths to the controllers manually by explicitly writing into URLMapping file. I guess this would help! </p>\n"
},
{
"answer_id": 28975869,
"author": "Robert Erlinger",
"author_id": 1552745,
"author_profile": "https://Stackoverflow.com/users/1552745",
"pm_score": 2,
"selected": false,
"text": "<p>Use controller, view and action parameter by the following syntax:</p>\n\n<pre><code>class UrlMappings {\n static mappings = {\n \"/\" (controller:'dashboard', view: 'index', action: 'index')\n \"500\"(view:'/error')\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55970990,
"author": "John Little",
"author_id": 1072187,
"author_profile": "https://Stackoverflow.com/users/1072187",
"pm_score": 0,
"selected": false,
"text": "<p>If anyone is looking for the answer for gails 3.x, they moved UrlMappings.groovy to grails-app/controllers/appname</p>\n\n<p>As the below answers say, just ed it the line starting with \"/\".</p>\n\n<p>In my case its:</p>\n\n<pre><code>\"/\"(controller:\"dashboard\", view:\"/index\")\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3014/"
] | What is the configuration setting for modifying the default homepage in a Grails application to no longer be appName/index.gsp? Of course you can set that page to be a redirect but there must be a better way. | Add this in UrlMappings.groovy
```
"/" {
controller = "yourController"
action = "yourAction"
}
```
By configuring the URLMappings this way, the home-page of the app will be yourWebApp/yourController/yourAction.
(cut/pasted from [IntelliGrape Blog](http://blog.intelligrape.com/?p=18)) |
27,894 | <p>In SQL Server 2005, we can create temp tables one of two ways:</p>
<pre><code>declare @tmp table (Col1 int, Col2 int);
</code></pre>
<p>or</p>
<pre><code>create table #tmp (Col1 int, Col2 int);
</code></pre>
<p>What are the differences between these two? I have read conflicting opinions on whether @tmp still uses tempdb, or if everything happens in memory. </p>
<p>In which scenarios does one out-perform the other? </p>
| [
{
"answer_id": 27905,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 4,
"selected": false,
"text": "<p>@wcm - actually to nit pick the Table Variable isn't Ram only - it can be partially stored on disk.</p>\n\n<p>A temp table can have indexes, whereas a table variable can only have a primary index. If speed is an issue Table variables can be faster, but obviously if there are a lot of records, or the need to search the temp table of a clustered index, then a Temp Table would be better.</p>\n\n<p><a href=\"http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1267047,00.html#\" rel=\"noreferrer\">Good background article</a></p>\n"
},
{
"answer_id": 27951,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "<p>For all of you who believe the myth that temp variables are in memory only </p>\n\n<p>First, the table variable is NOT necessarily memory resident. Under memory pressure, the pages belonging to a table variable can be pushed out to tempdb.</p>\n\n<p>Read the article here: <a href=\"http://blogs.msdn.com/sqlserverstorageengine/archive/2008/03/30/sql-server-table-variable-vs-local-temporary-table.aspx\" rel=\"noreferrer\">TempDB:: Table variable vs local temporary table</a> </p>\n"
},
{
"answer_id": 27954,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>In which scenarios does one out-perform the other?</p>\n</blockquote>\n\n<p>For smaller tables (less than 1000 rows) use a temp variable, otherwise use a temp table.</p>\n"
},
{
"answer_id": 64891,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 10,
"selected": true,
"text": "<p>There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.</p>\n\n<p>As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)</p>\n\n<p>Some points to consider when choosing between them: </p>\n\n<ul>\n<li><p>Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.</p></li>\n<li><p>Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) <a href=\"https://stackoverflow.com/questions/886050/sql-server-creating-an-index-on-a-table-variable/17385085#17385085\">SQL 2014 has non-unique indexes too</a>.</p></li>\n<li><p>Table variables don't participate in transactions and <code>SELECT</code>s are implicitly with <code>NOLOCK</code>. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!</p></li>\n<li><p>Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.</p></li>\n<li><p>You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront. </p></li>\n<li><p>You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).</p></li>\n<li><p>Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.</p></li>\n<li><p>Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb (<a href=\"https://learn.microsoft.com/sql/t-sql/language-elements/declare-local-variable-transact-sql\" rel=\"noreferrer\">ref</a>). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.</p></li>\n<li><p>Global Temp Tables (##tmp) are another type of temp table available to all sessions and users. </p></li>\n</ul>\n\n<p>Some further reading:</p>\n\n<ul>\n<li><p><a href=\"https://dba.stackexchange.com/a/16386\">Martin Smith's great answer</a> on dba.stackexchange.com</p></li>\n<li><p>MSDN FAQ on difference between the two: <a href=\"https://support.microsoft.com/en-gb/kb/305977\" rel=\"noreferrer\">https://support.microsoft.com/en-gb/kb/305977</a></p></li>\n<li><p>MDSN blog article: <a href=\"https://learn.microsoft.com/archive/blogs/sqlserverstorageengine/tempdb-table-variable-vs-local-temporary-table\" rel=\"noreferrer\">https://learn.microsoft.com/archive/blogs/sqlserverstorageengine/tempdb-table-variable-vs-local-temporary-table</a></p></li>\n<li><p>Article: <a href=\"https://searchsqlserver.techtarget.com/tip/Temporary-tables-in-SQL-Server-vs-table-variables\" rel=\"noreferrer\">https://searchsqlserver.techtarget.com/tip/Temporary-tables-in-SQL-Server-vs-table-variables</a></p></li>\n<li><p>Unexpected behaviors and performance implications of temp tables and temp variables: <a href=\"https://sql.kiwi/2012/08/temporary-tables-in-stored-procedures.html\" rel=\"noreferrer\">Paul White on SQLblog.com</a></p></li>\n</ul>\n"
},
{
"answer_id": 64968,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 2,
"selected": false,
"text": "<p>Consider also that you can often replace both with derived tables which may be faster as well. As with all performance tuning, though, only actual tests against your actual data can tell you the best approach for your particular query.</p>\n"
},
{
"answer_id": 65634,
"author": "GilaMonster",
"author_id": 9342,
"author_profile": "https://Stackoverflow.com/users/9342",
"pm_score": 3,
"selected": false,
"text": "<p>The other main difference is that table variables don't have column statistics, where as temp tables do. This means that the query optimiser doesn't know how many rows are in the table variable (it guesses 1), which can lead to highly non-optimal plans been generated if the table variable actually has a large number of rows.</p>\n"
},
{
"answer_id": 7609360,
"author": "BrianFinkel",
"author_id": 394837,
"author_profile": "https://Stackoverflow.com/users/394837",
"pm_score": 3,
"selected": false,
"text": "<p>Another difference:</p>\n\n<p>A table var can only be accessed from statements within the procedure that creates it, not from other procedures called by that procedure or nested dynamic SQL (via exec or sp_executesql).</p>\n\n<p>A temp table's scope, on the other hand, includes code in called procedures and nested dynamic SQL.</p>\n\n<p>If the table created by your procedure must be accessible from other called procedures or dynamic SQL, you must use a temp table. This can be very handy in complex situations.</p>\n"
},
{
"answer_id": 8204184,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 5,
"selected": false,
"text": "<p>Just looking at the claim in the accepted answer that table variables don't participate in logging. </p>\n\n<p>It seems generally untrue that there is any difference in quantity of logging (at least for <code>insert</code>/<code>update</code>/<code>delete</code> operations to the table itself though I have <a href=\"https://dba.stackexchange.com/a/13412/3690\">since found</a> that there is some small difference in this respect for cached temporary objects in stored procedures due to additional system table updates).</p>\n\n<p>I looked at the logging behaviour against both a <code>@table_variable</code> and a <code>#temp</code> table for the following operations.</p>\n\n<ol>\n<li>Successful Insert </li>\n<li>Multi Row Insert where statement rolled back due to constraint violation.</li>\n<li>Update</li>\n<li>Delete</li>\n<li>Deallocate</li>\n</ol>\n\n<p>The transaction log records were almost identical for all operations. </p>\n\n<p>The table variable version actually has a few <strong>extra</strong> log entries because it gets an entry added to (and later removed from) the <code>sys.syssingleobjrefs</code> base table but overall had a few less bytes logged purely as the internal name for table variables consumes 236 less bytes than for <code>#temp</code> tables (118 fewer <code>nvarchar</code> characters).</p>\n\n<h3>Full script to reproduce (best run on an instance started in single user mode and using <code>sqlcmd</code> mode)</h3>\n\n<pre><code>:setvar tablename \"@T\" \n:setvar tablescript \"DECLARE @T TABLE\"\n\n/*\n --Uncomment this section to test a #temp table\n:setvar tablename \"#T\" \n:setvar tablescript \"CREATE TABLE #T\"\n*/\n\nUSE tempdb \nGO \nCHECKPOINT\n\nDECLARE @LSN NVARCHAR(25)\n\nSELECT @LSN = MAX([Current LSN])\nFROM fn_dblog(null, null) \n\n\nEXEC(N'BEGIN TRAN StartBatch\nSAVE TRAN StartBatch\nCOMMIT\n\n$(tablescript)\n(\n[4CA996AC-C7E1-48B5-B48A-E721E7A435F0] INT PRIMARY KEY DEFAULT 0,\nInRowFiller char(7000) DEFAULT ''A'',\nOffRowFiller varchar(8000) DEFAULT REPLICATE(''B'',8000),\nLOBFiller varchar(max) DEFAULT REPLICATE(cast(''C'' as varchar(max)),10000)\n)\n\n\nBEGIN TRAN InsertFirstRow\nSAVE TRAN InsertFirstRow\nCOMMIT\n\nINSERT INTO $(tablename)\nDEFAULT VALUES\n\nBEGIN TRAN Insert9Rows\nSAVE TRAN Insert9Rows\nCOMMIT\n\n\nINSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])\nSELECT TOP 9 ROW_NUMBER() OVER (ORDER BY (SELECT 0))\nFROM sys.all_columns\n\nBEGIN TRAN InsertFailure\nSAVE TRAN InsertFailure\nCOMMIT\n\n\n/*Try and Insert 10 rows, the 10th one will cause a constraint violation*/\nBEGIN TRY\nINSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])\nSELECT TOP (10) (10 + ROW_NUMBER() OVER (ORDER BY (SELECT 0))) % 20\nFROM sys.all_columns\nEND TRY\nBEGIN CATCH\nPRINT ERROR_MESSAGE()\nEND CATCH\n\nBEGIN TRAN Update10Rows\nSAVE TRAN Update10Rows\nCOMMIT\n\nUPDATE $(tablename)\nSET InRowFiller = LOWER(InRowFiller),\n OffRowFiller =LOWER(OffRowFiller),\n LOBFiller =LOWER(LOBFiller)\n\n\nBEGIN TRAN Delete10Rows\nSAVE TRAN Delete10Rows\nCOMMIT\n\nDELETE FROM $(tablename)\nBEGIN TRAN AfterDelete\nSAVE TRAN AfterDelete\nCOMMIT\n\nBEGIN TRAN EndBatch\nSAVE TRAN EndBatch\nCOMMIT')\n\n\nDECLARE @LSN_HEX NVARCHAR(25) = \n CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 1, 8),2) AS INT) AS VARCHAR) + ':' +\n CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 10, 8),2) AS INT) AS VARCHAR) + ':' +\n CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 19, 4),2) AS INT) AS VARCHAR) \n\nSELECT \n [Operation],\n [Context],\n [AllocUnitName],\n [Transaction Name],\n [Description]\nFROM fn_dblog(@LSN_HEX, null) AS D\nWHERE [Current LSN] > @LSN \n\nSELECT CASE\n WHEN GROUPING(Operation) = 1 THEN 'Total'\n ELSE Operation\n END AS Operation,\n Context,\n AllocUnitName,\n COALESCE(SUM([Log Record Length]), 0) AS [Size in Bytes],\n COUNT(*) AS Cnt\nFROM fn_dblog(@LSN_HEX, null) AS D\nWHERE [Current LSN] > @LSN \nGROUP BY GROUPING SETS((Operation, Context, AllocUnitName),())\n</code></pre>\n\n<p>Results</p>\n\n<pre><code>+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n| | | | @TV | #TV | |\n+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n| Operation | Context | AllocUnitName | Size in Bytes | Cnt | Size in Bytes | Cnt | Difference Bytes |\n+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n| LOP_ABORT_XACT | LCX_NULL | | 52 | 1 | 52 | 1 | |\n| LOP_BEGIN_XACT | LCX_NULL | | 6056 | 50 | 6056 | 50 | |\n| LOP_COMMIT_XACT | LCX_NULL | | 2548 | 49 | 2548 | 49 | |\n| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysallocunits.clust | 624 | 3 | 624 | 3 | |\n| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysrowsets.clust | 208 | 1 | 208 | 1 | |\n| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysrscols.clst | 832 | 4 | 832 | 4 | |\n| LOP_CREATE_ALLOCCHAIN | LCX_NULL | | 120 | 3 | 120 | 3 | |\n| LOP_DELETE_ROWS | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 720 | 9 | 720 | 9 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysallocunits.clust | 444 | 3 | 444 | 3 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysallocunits.nc | 276 | 3 | 276 | 3 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syscolpars.clst | 628 | 4 | 628 | 4 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syscolpars.nc | 484 | 4 | 484 | 4 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysidxstats.clst | 176 | 1 | 176 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysidxstats.nc | 144 | 1 | 144 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysiscols.clst | 100 | 1 | 100 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysiscols.nc1 | 88 | 1 | 88 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysobjvalues.clst | 596 | 5 | 596 | 5 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysrowsets.clust | 132 | 1 | 132 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysrscols.clst | 528 | 4 | 528 | 4 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.clst | 1040 | 6 | 1276 | 6 | 236 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc1 | 820 | 6 | 1060 | 6 | 240 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc2 | 820 | 6 | 1060 | 6 | 240 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc3 | 480 | 6 | 480 | 6 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syssingleobjrefs.clst | 96 | 1 | | | -96 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syssingleobjrefs.nc1 | 88 | 1 | | | -88 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | Unknown Alloc Unit | 72092 | 19 | 72092 | 19 | |\n| LOP_DELETE_ROWS | LCX_TEXT_MIX | Unknown Alloc Unit | 16348 | 37 | 16348 | 37 | |\n| LOP_FORMAT_PAGE | LCX_HEAP | Unknown Alloc Unit | 1596 | 19 | 1596 | 19 | |\n| LOP_FORMAT_PAGE | LCX_IAM | Unknown Alloc Unit | 252 | 3 | 252 | 3 | |\n| LOP_FORMAT_PAGE | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 84 | 1 | 84 | 1 | |\n| LOP_FORMAT_PAGE | LCX_TEXT_MIX | Unknown Alloc Unit | 4788 | 57 | 4788 | 57 | |\n| LOP_HOBT_DDL | LCX_NULL | | 108 | 3 | 108 | 3 | |\n| LOP_HOBT_DELTA | LCX_NULL | | 9600 | 150 | 9600 | 150 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysallocunits.clust | 456 | 3 | 456 | 3 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.syscolpars.clst | 644 | 4 | 644 | 4 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysidxstats.clst | 180 | 1 | 180 | 1 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysiscols.clst | 104 | 1 | 104 | 1 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysobjvalues.clst | 616 | 5 | 616 | 5 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysrowsets.clust | 136 | 1 | 136 | 1 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysrscols.clst | 544 | 4 | 544 | 4 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysschobjs.clst | 1064 | 6 | 1300 | 6 | 236 |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.syssingleobjrefs.clst | 100 | 1 | | | -100 |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | Unknown Alloc Unit | 135888 | 19 | 135888 | 19 | |\n| LOP_INSERT_ROWS | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 1596 | 19 | 1596 | 19 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysallocunits.nc | 288 | 3 | 288 | 3 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.syscolpars.nc | 500 | 4 | 500 | 4 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysidxstats.nc | 148 | 1 | 148 | 1 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysiscols.nc1 | 92 | 1 | 92 | 1 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc1 | 844 | 6 | 1084 | 6 | 240 |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc2 | 844 | 6 | 1084 | 6 | 240 |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc3 | 504 | 6 | 504 | 6 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.syssingleobjrefs.nc1 | 92 | 1 | | | -92 |\n| LOP_INSERT_ROWS | LCX_TEXT_MIX | Unknown Alloc Unit | 5112 | 71 | 5112 | 71 | |\n| LOP_MARK_SAVEPOINT | LCX_NULL | | 508 | 8 | 508 | 8 | |\n| LOP_MODIFY_COLUMNS | LCX_CLUSTERED | Unknown Alloc Unit | 1560 | 10 | 1560 | 10 | |\n| LOP_MODIFY_HEADER | LCX_HEAP | Unknown Alloc Unit | 3780 | 45 | 3780 | 45 | |\n| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.syscolpars.clst | 384 | 4 | 384 | 4 | |\n| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysidxstats.clst | 100 | 1 | 100 | 1 | |\n| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysrowsets.clust | 92 | 1 | 92 | 1 | |\n| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysschobjs.clst | 1144 | 13 | 1144 | 13 | |\n| LOP_MODIFY_ROW | LCX_IAM | Unknown Alloc Unit | 4224 | 48 | 4224 | 48 | |\n| LOP_MODIFY_ROW | LCX_PFS | Unknown Alloc Unit | 13632 | 169 | 13632 | 169 | |\n| LOP_MODIFY_ROW | LCX_TEXT_MIX | Unknown Alloc Unit | 108640 | 120 | 108640 | 120 | |\n| LOP_ROOT_CHANGE | LCX_CLUSTERED | sys.sysallocunits.clust | 960 | 10 | 960 | 10 | |\n| LOP_SET_BITS | LCX_GAM | Unknown Alloc Unit | 1200 | 20 | 1200 | 20 | |\n| LOP_SET_BITS | LCX_IAM | Unknown Alloc Unit | 1080 | 18 | 1080 | 18 | |\n| LOP_SET_BITS | LCX_SGAM | Unknown Alloc Unit | 120 | 2 | 120 | 2 | |\n| LOP_SHRINK_NOOP | LCX_NULL | | | | 32 | 1 | 32 |\n+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n| Total | | | 410144 | 1095 | 411232 | 1092 | 1088 |\n+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n</code></pre>\n"
},
{
"answer_id": 16298637,
"author": "Kumar Manish",
"author_id": 1051234,
"author_profile": "https://Stackoverflow.com/users/1051234",
"pm_score": 4,
"selected": false,
"text": "<ol>\n<li><p>Temp table: A Temp table is easy to create and back up data.</p>\n<p>Table variable: But the table variable involves the effort when we usually create the normal tables.</p>\n</li>\n<li><p>Temp table: Temp table result can be used by multiple users.</p>\n<p>Table variable: But the table variable can be used by the current user only. </p>\n</li>\n<li><p>Temp table: Temp table will be stored in the tempdb. It will make network traffic. When we have large data in the temp table then it has to work across the database. A Performance issue will exist.</p>\n<p>Table variable: But a table variable will store in the physical memory for some of the data, then later when the size increases it will be moved to the tempdb.</p>\n</li>\n<li><p>Temp table: Temp table can do all the DDL operations. It allows creating the indexes, dropping, altering, etc..,</p>\n<p>Table variable: Whereas table variable won't allow doing the DDL operations. But the table variable allows us to create the clustered index only.</p>\n</li>\n<li><p>Temp table: Temp table can be used for the current session or global. So that a multiple user session can utilize the results in the table.</p>\n<p>Table variable: But the table variable can be used up to that program. (Stored procedure)</p>\n</li>\n<li><p>Temp table: Temp variable cannot use the transactions. When we do the DML operations with the temp table then it can be rollback or commit the transactions.</p>\n<p>Table variable: But we cannot do it for table variable.</p>\n</li>\n<li><p>Temp table: Functions cannot use the temp variable. More over we cannot do the DML operation in the functions .</p>\n<p>Table variable: But the function allows us to use the table variable. But using the table variable we can do that.</p>\n</li>\n<li><p>Temp table: The stored procedure will do the recompilation (can't use same execution plan) when we use the temp variable for every sub sequent calls.</p>\n<p>Table variable: Whereas the table variable won't do like that.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 32400833,
"author": "Teoman shipahi",
"author_id": 929902,
"author_profile": "https://Stackoverflow.com/users/929902",
"pm_score": 3,
"selected": false,
"text": "<p>Quote taken from; <a href=\"https://rads.stackoverflow.com/amzn/click/com/1118177657\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Professional SQL Server 2012 Internals and Troubleshooting</a></p>\n\n<blockquote>\n <p><strong>Statistics</strong>\n The major difference between temp tables and table variables is that\n statistics are not created on table variables. This has two major\n consequences, the fi rst of which is that the Query Optimizer uses a\n fi xed estimation for the number of rows in a table variable\n irrespective of the data it contains. Moreover, adding or removing\n data doesn’t change the estimation.</p>\n \n <p><strong>Indexes</strong> You can’t create indexes on table variables although you can\n create constraints. This means that by creating primary keys or unique\n constraints, you can have indexes (as these are created to support\n constraints) on table variables. Even if you have constraints, and\n therefore indexes that will have statistics, the indexes will not be\n used when the query is compiled because they won’t exist at compile\n time, nor will they cause recompilations.</p>\n \n <p><strong>Schema Modifications</strong> Schema modifications are possible on temporary\n tables but not on table variables. Although schema modifi cations are\n possible on temporary tables, avoid using them because they cause\n recompilations of statements that use the tables.</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/gkH9V.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gkH9V.png\" alt=\"Temporary Tables versus Table Variables\"></a></p>\n\n<p>TABLE VARIABLES ARE NOT CREATED IN MEMORY</p>\n\n<p><strong>There is a common misconception that table variables are in-memory structures\nand as such will perform quicker than temporary tables</strong>. Thanks to a DMV\ncalled sys . dm _ db _ session _ space _ usage , which shows tempdb usage by\nsession, <strong>you can prove that’s not the case</strong>. After restarting SQL Server to clear the\nDMV, run the following script to confi rm that your session _ id returns 0 for\nuser _ objects _ alloc _ page _ count :</p>\n\n<pre><code>SELECT session_id,\ndatabase_id,\nuser_objects_alloc_page_count\nFROM sys.dm_db_session_space_usage\nWHERE session_id > 50 ;\n</code></pre>\n\n<p>Now you can check how much space a temporary table uses by running the following\n script to create a temporary table with one column and populate it with one row:</p>\n\n<pre><code>CREATE TABLE #TempTable ( ID INT ) ;\nINSERT INTO #TempTable ( ID )\nVALUES ( 1 ) ;\nGO\nSELECT session_id,\ndatabase_id,\nuser_objects_alloc_page_count\nFROM sys.dm_db_session_space_usage\nWHERE session_id > 50 ;\n</code></pre>\n\n<p>The results on my server indicate that the table was allocated one page in tempdb.\nNow run the same script but use a table variable\nthis time:</p>\n\n<pre><code>DECLARE @TempTable TABLE ( ID INT ) ;\nINSERT INTO @TempTable ( ID )\nVALUES ( 1 ) ;\nGO\nSELECT session_id,\ndatabase_id,\nuser_objects_alloc_page_count\nFROM sys.dm_db_session_space_usage\nWHERE session_id > 50 ;\n</code></pre>\n\n<p><strong>Which one to Use?</strong></p>\n\n<blockquote>\n <p>Whether or not you use temporary tables or table variables should be\n decided by thorough testing, but <strong>it’s best to lean towards temporary</strong>\n <strong>tables as the default because there are far fewer things that can go</strong>\n <strong>wrong</strong>. </p>\n \n <p>I’ve seen customers develop code using table variables because they\n were dealing with a small amount of rows, and it was quicker than a\n temporary table, but a few years later there were hundreds of \n thousands of rows in the table variable and performance was terrible, \n so try and allow for some capacity planning when you make your \n decision!</p>\n</blockquote>\n"
},
{
"answer_id": 58875211,
"author": "Litisqe Kumar",
"author_id": 5047627,
"author_profile": "https://Stackoverflow.com/users/5047627",
"pm_score": 2,
"selected": false,
"text": "<p>Differences between <code>Temporary Tables (##temp/#temp)</code> and <code>Table Variables (@table)</code> are as:</p>\n<ol>\n<li><p><code>Table variable (@table)</code> is created in the <code>memory</code>. Whereas, a <code>Temporary table (##temp/#temp)</code> is created in the <code>tempdb database</code>. However, if there is a memory pressure the pages belonging to a table variable may be pushed to tempdb.</p>\n</li>\n<li><p><code>Table variables</code> cannot be involved in <code>transactions, logging or locking</code>. This makes <code>@table faster then #temp</code>. So table variable is faster then temporary table.</p>\n</li>\n<li><p><code>Temporary table</code> allows Schema modifications unlike <code>Table variables</code>.</p>\n</li>\n<li><p><code>Temporary tables</code> are visible in the created routine and also in the child routines. Whereas, Table variables are only visible in the created routine.</p>\n</li>\n<li><p><code>Temporary tables</code> are allowed <code>CREATE INDEXes</code> whereas, <code>Table variables</code> aren’t allowed <code>CREATE INDEX</code> instead they can have index by using <code>Primary Key or Unique Constraint</code>.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 60214373,
"author": "Weihui Guo",
"author_id": 4271117,
"author_profile": "https://Stackoverflow.com/users/4271117",
"pm_score": 3,
"selected": false,
"text": "<p>It surprises me that no one mentioned the key difference between these two is that the temp table supports <strong>parallel insert</strong> while the table variable doesn't. You should be able to see the difference from the execution plan. And here is <a href=\"https://channel9.msdn.com/Series/SQL-Workshops/Parallel-Insert-Into-Table-Variable-Vs-Temporary-Table-in-SQL-Server\" rel=\"nofollow noreferrer\">the video from SQL Workshops on Channel 9</a> and <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/data-types/table-transact-sql?redirectedfrom=MSDN&view=sql-server-ver16#limitations-and-restrictions\" rel=\"nofollow noreferrer\">MSDN doc</a>.</p>\n<p>This also explains why you should use a table variable for smaller tables, otherwise a temp table, as <a href=\"https://stackoverflow.com/a/27954/4271117\">SQLMenace answered</a> before.</p>\n"
},
{
"answer_id": 70033739,
"author": "satheesh",
"author_id": 17242923,
"author_profile": "https://Stackoverflow.com/users/17242923",
"pm_score": 1,
"selected": false,
"text": "<p>In SQL the Temporary tables are stored in the TempDB and the local temporary tables are only visible in the current session and it will not be visible in another session. This can be shared between nested stored procedure calls. The Global temporary tables are visible to all other sessions and they are destroyed when the last connection referencing table is closed. For Example,</p>\n<pre><code>Select Dept.DeptName, Dept.DeptId, COUNT(*) as TotalEmployees\ninto #TempEmpCount\nfrom Tbl_EmpDetails Emp\njoin Tbl_Dept Dept\non Emp.DeptId = Dept.DeptId\ngroup by DeptName, Dept.DeptId\n</code></pre>\n<p>Table variables are similar to tempTables, a table variable is also created in TempDB. The scope of a table variable is the batch, stored procedure, or statement block in which it is declared. They can be passed as parameters between procedures. The same query can be written using Table variable by</p>\n<pre><code>Declare @tblEmployeeCount table\n(DeptName nvarchar(20),DeptId int, TotalEmployees int)\nInsert @tblEmployeeCount\nSelect DeptName, Tbl_Dept.DeptId, COUNT(*) as TotalEmployees\nfrom Tbl_EmpDetails\njoin Tbl_Dept\non Tbl_EmpDetails.DeptId = Tbl_Dept.DeptId\ngroup by DeptName, Tbl_Dept.DeptId\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | In SQL Server 2005, we can create temp tables one of two ways:
```
declare @tmp table (Col1 int, Col2 int);
```
or
```
create table #tmp (Col1 int, Col2 int);
```
What are the differences between these two? I have read conflicting opinions on whether @tmp still uses tempdb, or if everything happens in memory.
In which scenarios does one out-perform the other? | There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.
As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)
Some points to consider when choosing between them:
* Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.
* Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) [SQL 2014 has non-unique indexes too](https://stackoverflow.com/questions/886050/sql-server-creating-an-index-on-a-table-variable/17385085#17385085).
* Table variables don't participate in transactions and `SELECT`s are implicitly with `NOLOCK`. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!
* Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.
* You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.
* You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).
* Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.
* Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb ([ref](https://learn.microsoft.com/sql/t-sql/language-elements/declare-local-variable-transact-sql)). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.
* Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.
Some further reading:
* [Martin Smith's great answer](https://dba.stackexchange.com/a/16386) on dba.stackexchange.com
* MSDN FAQ on difference between the two: <https://support.microsoft.com/en-gb/kb/305977>
* MDSN blog article: <https://learn.microsoft.com/archive/blogs/sqlserverstorageengine/tempdb-table-variable-vs-local-temporary-table>
* Article: <https://searchsqlserver.techtarget.com/tip/Temporary-tables-in-SQL-Server-vs-table-variables>
* Unexpected behaviors and performance implications of temp tables and temp variables: [Paul White on SQLblog.com](https://sql.kiwi/2012/08/temporary-tables-in-stored-procedures.html) |
27,899 | <p>Is there a way to make S3 default to an index.html page? E.g.: My bucket object listing:</p>
<pre><code>/index.html
/favicon.ico
/images/logo.gif
</code></pre>
<p>A call to <strong>www.example.com/<em>index.html</em></strong> works great! But if one were to call <strong>www.example.com/</strong> we'd either get a 403 or a REST object listing XML document depending on how bucket-level ACL was configured.</p>
<p>So, the question: Is there a way to have index.html functionality with content hosted on S3?</p>
| [
{
"answer_id": 27922,
"author": "yoavf",
"author_id": 1011,
"author_profile": "https://Stackoverflow.com/users/1011",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest reading <a href=\"http://developer.amazonwebservices.com/connect/thread.jspa?threadID=10849&start=0&tstart=0\" rel=\"nofollow noreferrer\">this thread</a> from 2006 (On Amazon web services developers connection). It seems there's no easy solution to this.</p>\n"
},
{
"answer_id": 2879970,
"author": "nick",
"author_id": 346817,
"author_profile": "https://Stackoverflow.com/users/346817",
"pm_score": 0,
"selected": false,
"text": "<p>you can do it using dns webforwards and cloaking. just forward to the complete path of the index.html</p>\n\n<p>www.example.com forwards to <a href=\"http://www.example.com.s3.amazonaws.com\" rel=\"nofollow noreferrer\">http://www.example.com.s3.amazonaws.com</a> and make sure you cloak the output.</p>\n"
},
{
"answer_id": 3436768,
"author": "Amaroom",
"author_id": 414638,
"author_profile": "https://Stackoverflow.com/users/414638",
"pm_score": 2,
"selected": false,
"text": "<p>Yes. using AWS Cloudfront lets you assign a default file.</p>\n"
},
{
"answer_id": 4474914,
"author": "Naszta",
"author_id": 463680,
"author_profile": "https://Stackoverflow.com/users/463680",
"pm_score": 2,
"selected": false,
"text": "<p>You can easily solve it by Amazon CloudFront <a href=\"http://aws.amazon.com/cloudfront/\" rel=\"nofollow\">link</a>. At Amazon CloudFront you could modify the root object. You can download manager here: m1.mycloudbuddy.com/downloads.html.</p>\n"
},
{
"answer_id": 5040105,
"author": "Alex Jasmin",
"author_id": 162407,
"author_profile": "https://Stackoverflow.com/users/162407",
"pm_score": 6,
"selected": true,
"text": "<p>Amazon S3 now supports <a href=\"http://docs.amazonwebservices.com/AmazonS3/latest/dev/IndexDocumentSupport.html\" rel=\"noreferrer\">Index Documents</a></p>\n\n<p>The <em>index document</em> for a bucket can be set to something like <code>index.html</code>. When accessing the root of the site or a sub-directory containing a document of that name that document is returned.</p>\n\n<p>It is extremely easy to do using the aws cli:</p>\n\n<pre><code>aws s3 website $MY_BUCKET_NAME --index-document index.html\n</code></pre>\n\n<p>You can set the <em>index document</em> from the AWS Management Console:</p>\n\n<p><img src=\"https://i.stack.imgur.com/HALQp.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 24377823,
"author": "fiatjaf",
"author_id": 973380,
"author_profile": "https://Stackoverflow.com/users/973380",
"pm_score": 6,
"selected": false,
"text": "<p>For people still struggling against this after 3 years, let me add some important information:</p>\n\n<p>The URL for your website (and to which you have to point your DNS) is not </p>\n\n<p><code><bucket_name>.s3-us-west-2.amazonaws.com</code>, but</p>\n\n<p><code><bucket_name>.s3-website-us-west-2.amazonaws.com</code>.</p>\n\n<p>If you use the first, it will not work as intended, no matter how much you config the <a href=\"http://docs.aws.amazon.com/AmazonS3/latest/dev/IndexDocumentSupport.html\" rel=\"noreferrer\">Index document</a>.</p>\n\n<p>For a specific example, consider:</p>\n\n<ul>\n<li><a href=\"http://www-example-com.s3.amazonaws.com/index.html\" rel=\"noreferrer\">http://www-example-com.s3.amazonaws.com/index.html</a> works.</li>\n<li><a href=\"http://www-example-com.s3.amazonaws.com/\" rel=\"noreferrer\">http://www-example-com.s3.amazonaws.com/</a> fails with <code>AccessDenied</code>.</li>\n<li><a href=\"http://www-example-com.s3-website-us-west-2.amazonaws.com/\" rel=\"noreferrer\">http://www-example-com.s3-website-us-west-2.amazonaws.com/</a> works!</li>\n</ul>\n\n<p>To get your true website address, go to your <a href=\"https://console.aws.amazon.com/s3/home\" rel=\"noreferrer\">S3 Management Console</a>, select the target bucket, then <code>Properties</code>, then <code>Static Website Hosting</code>. It will show the website URL that will work.</p>\n"
},
{
"answer_id": 44574109,
"author": "bhar1red",
"author_id": 3086531,
"author_profile": "https://Stackoverflow.com/users/3086531",
"pm_score": 2,
"selected": false,
"text": "<p>Since It's been long time, this question being asked, and Amazon S3 changing their Interface. I would like to answer with updated screenshots.</p>\n\n<p>We need to enable 'static web hosting' for S3 to serve as web hosting. \n- Go to Properties -> click on static web hosting -> Select 'use this bucket to host a website' \n- Enter the index document (index.html by default), error document and redirection rules, if any. \n<img src=\"https://i.stack.imgur.com/aoNWq.png\" alt=\"Selecting static web hosting\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/AxdTs.png\" alt=\"use-this-bucket-to-host-a-website\"></p>\n\n<p>As answered in <a href=\"https://stackoverflow.com/a/24377823/3086531\">this answer on Stack Overflow</a>, web hosting link would be: <a href=\"http://bucket-name.s3-website-region.amazonaws.com\" rel=\"nofollow noreferrer\">http://bucket-name.s3-website-region.amazonaws.com</a></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2961/"
] | Is there a way to make S3 default to an index.html page? E.g.: My bucket object listing:
```
/index.html
/favicon.ico
/images/logo.gif
```
A call to **www.example.com/*index.html*** works great! But if one were to call **www.example.com/** we'd either get a 403 or a REST object listing XML document depending on how bucket-level ACL was configured.
So, the question: Is there a way to have index.html functionality with content hosted on S3? | Amazon S3 now supports [Index Documents](http://docs.amazonwebservices.com/AmazonS3/latest/dev/IndexDocumentSupport.html)
The *index document* for a bucket can be set to something like `index.html`. When accessing the root of the site or a sub-directory containing a document of that name that document is returned.
It is extremely easy to do using the aws cli:
```
aws s3 website $MY_BUCKET_NAME --index-document index.html
```
You can set the *index document* from the AWS Management Console:
 |
27,910 | <p>The <a href="http://doi.org/" rel="noreferrer">DOI</a> system places basically no useful limitations on what constitutes <a href="http://doi.org/handbook_2000/enumeration.html#2.2" rel="noreferrer">a reasonable identifier</a>. However, being able to pull DOIs out of PDFs, web pages, etc. is quite useful for citation information, etc.</p>
<p>Is there a reliable way to identify a DOI in a block of text without assuming the 'doi:' prefix? (any language acceptable, regexes preferred, and avoiding false positives a must)</p>
| [
{
"answer_id": 29639,
"author": "Silas Snider",
"author_id": 2933,
"author_profile": "https://Stackoverflow.com/users/2933",
"pm_score": 1,
"selected": false,
"text": "<p>The following regex should do the job (Perl regex syntax):</p>\n\n<pre><code>/(10\\.\\d+\\/\\d+)/\n</code></pre>\n\n<p>You could do some additional sanity checking by opening the urls</p>\n\n<pre><code>http://hdl.handle.net/<doi>\n</code></pre>\n\n<p>and</p>\n\n<pre><code>http://dx.doi.org/<doi>\n</code></pre>\n\n<p>where is the candidate doi,</p>\n\n<p>and testing that you a) get a 200 OK http status, and b) the returned page is not the \"DOI not found\" page for the service.</p>\n"
},
{
"answer_id": 29764,
"author": "Kai",
"author_id": 2963,
"author_profile": "https://Stackoverflow.com/users/2963",
"pm_score": 4,
"selected": false,
"text": "<p>@Silas The sanity checking is a good idea. However, the regex doesn't cover all DOIs. The first element must (currently) be 10, and the second element must (currently) be numeric, but the third element is barely restricted at all:</p>\n\n<blockquote>\n <p>\"Legal characters are the legal graphic characters of Unicode. This specifically excludes the control character ranges 0x00-0x1F and 0x80-0x9F...\" </p>\n</blockquote>\n\n<p>and that's where the real problem lies. In practice, I've never seen whitespace used, but the spec specifically allows for it. Basically, there doesn't seem to be a sensible way of detecting the <em>end</em> of a DOI.</p>\n"
},
{
"answer_id": 1876427,
"author": "rgcb",
"author_id": 8178,
"author_profile": "https://Stackoverflow.com/users/8178",
"pm_score": 2,
"selected": false,
"text": "<p>I'm sure it's not super-helpful for the OP at this point, but I figured I'd post what I am trying in case anyone else like me stumbles upon this:</p>\n\n<pre><code>(10.(\\d)+/(\\S)+)\n</code></pre>\n\n<p>This matches: \"10 dot number slash anything-not-whitespace\" </p>\n\n<p>But for my use (scraping HTML), this was finding false-positives, so I had to match the above, plus get rid of quotes and greater-than/less-than:</p>\n\n<pre><code>(10.(\\d)+/([^(\\s\\>\\\"\\<)])+)\n</code></pre>\n\n<p>I'm still testing these out, but I'm feeling hopeful thus far.</p>\n"
},
{
"answer_id": 10300246,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my go at it:</p>\n\n<pre><code>(10[.][0-9]{4,}[^\\s\"/<>]*/[^\\s\"<>]+)\n</code></pre>\n\n<p>And a couple of valid edge cases where this doesn't fail, but others seem to do:</p>\n\n<ul>\n<li><a href=\"http://dx.doi.org/10.1007/978-3-642-28108-2_19\" rel=\"nofollow noreferrer\"><code>10.1007/978-3-642-28108-2_19</code></a></li>\n<li><code>10.1007.10/978-3-642-28108-2_19</code> (fictitious example, see <a href=\"https://stackoverflow.com/a/1876427/89771\">@Ju9OR comment</a>)</li>\n<li><a href=\"http://dx.doi.org/10.1016/S0735-1097%2898%2900347-7\" rel=\"nofollow noreferrer\"><code>10.1016/S0735-1097(98)00347-7</code></a></li>\n<li><a href=\"http://dx.doi.org/10.1579/0044-7447%282006%2935%5B89:RDUICP%5D2.0.CO;2\" rel=\"nofollow noreferrer\"><code>10.1579/0044-7447(2006)35\\[89:RDUICP\\]2.0.CO;2</code></a></li>\n</ul>\n\n<p>Also, correctly discards some falsy (X|HT)ML stuff like:</p>\n\n<ul>\n<li><code><geo coords=\"10.4515260,51.1656910\"></geo></code></li>\n</ul>\n"
},
{
"answer_id": 10324802,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 7,
"selected": true,
"text": "<p>Ok, I'm currently extracting thousands of DOIs from free form text (XML) and I realized that <a href=\"https://stackoverflow.com/a/10300246/89771\">my previous approach</a> had a few problems, namely regarding encoded entities and trailing punctuation, so I went on reading <a href=\"http://www.doi.org/doi_handbook/2_Numbering.html\" rel=\"nofollow noreferrer\">the specification</a> and this is the best I could come with.</p>\n<hr />\n<blockquote>\n<p>The DOI prefix shall be composed of a directory indicator followed by\na registrant code. These two components shall be separated by a full\nstop (period).</p>\n<p>The directory indicator shall be "10". The directory indicator\ndistinguishes the entire set of character strings (prefix and suffix)\nas digital object identifiers within the resolution system.</p>\n</blockquote>\n<p>Easy enough, the initial <code>\\b</code> prevents us from "matching" a "DOI" that doesn't start with <code>10.</code>:</p>\n<pre><code>$pattern = '\\b(10[.]';\n</code></pre>\n<hr />\n<blockquote>\n<p>The second element of the DOI prefix shall be the registrant code. The\nregistrant code is a unique string assigned to a registrant.</p>\n</blockquote>\n<p>Also, all assigned registrant code are numeric, and at least 4 digits long, so:</p>\n<pre><code>$pattern = '\\b(10[.][0-9]{4,}';\n</code></pre>\n<hr />\n<blockquote>\n<p>The registrant code may be further divided into sub-elements for\nadministrative convenience if desired. Each sub-element of the\nregistrant code shall be preceded by a full stop.</p>\n</blockquote>\n<p><code>$pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*';</code></p>\n<hr />\n<blockquote>\n<p>The DOI syntax shall be made up of a DOI prefix and a DOI suffix\nseparated by a forward slash.</p>\n</blockquote>\n<p>However, this isn't absolutely necessary, section 2.2.3 states that uncommon suffix systems may use other conventions (such as <code>10.1000.123456</code> instead of <code>10.1000/123456</code>), but lets cut some slack.</p>\n<p><code>$pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/';</code></p>\n<hr />\n<blockquote>\n<p>The DOI name is case-insensitive and can incorporate any printable\ncharacters from the legal graphic characters of Unicode. The DOI\nsuffix shall consist of a character string of any length chosen by the\nregistrant. Each suffix shall be unique to the prefix element that\nprecedes it. The unique suffix can be a sequential number, or it might\nincorporate an identifier generated from or based on another system.</p>\n</blockquote>\n<p>Now this is where it gets trickier, from all the DOIs I have processed, I saw the following characters (besides <code>[0-9a-zA-Z]</code> of course) in their <strong>suffixes</strong>: <code>.-()/:-</code> -- so, while it doesn't exist, the DOI <code>10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7</code> is completely plausible.</p>\n<p>The logical choice would be to use <code>\\S</code> or the <code>[[:graph:]]</code> PCRE POSIX class, so lets do that:</p>\n<p><code>$pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/\\S+'; // or</code></p>\n<p><code>$pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/[[:graph:]]+';</code></p>\n<hr />\n<p>Now we have a difficult problem, the <code>[[:graph:]]</code> class is a super-set of the <code>[[:punct:]]</code> class, which includes characters easily found in free text or any markup language: <code>"'&<></code> among others.</p>\n<p>Lets just filter the markup ones for now using a negative lookahead:</p>\n<p><code>$pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\\'<>])\\S)+'; // or</code></p>\n<p><code>$pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\\'<>])[[:graph:]])+';</code></p>\n<hr />\n<p>The above should cover encoded entities (<code>&</code>), attribute quotes (<code>["']</code>) and open / close tags (<code>[<>]</code>).</p>\n<p>Unlike markup languages, free text usually doesn't employ punctuation characters unless they are bounded by at least one space <em><strong>or</strong></em> placed at the end of a sentence, for instance:</p>\n<blockquote>\n<p>This is a long DOI:\n<code>10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7</code><strong>!!!</strong></p>\n</blockquote>\n<p>The solution here is to close our capture group and assert another word boundary:</p>\n<p><code>$pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\\'<>])\\S)+)\\b'; // or</code></p>\n<p><code>$pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\\'<>])[[:graph:]])+)\\b';</code></p>\n<p>And <em>voilá</em>, <a href=\"http://regexpal.com/?flags=g&regex=%5Cb(10%5B.%5D%5B0-9%5D%7B4%2C%7D(%3F%3A%5B.%5D%5B0-9%5D%2B)*%2F(%3F%3A(%3F!%5B%22%26%5C%27%3C%3E%5D)%5CS)%2B)%5Cb&input=This%20is%20a%20short%20DOI%3A%2010.1000%2F123456.%0AThis%20is%20NOT%20a%20DOI%3A%204210.1000%2F123456.%0AThis%20is%20a%20long%20DOI%3A%2010.1016.12.31%2Fnature.S0735-1097(98)2000%2F12%2F31%2F34%3A7-7!!!%0A%0A10.1007%2F978-3-642-28108-2_19%0A10.1007.10%2F978-3-642-28108-2_19%20(fictitious%20example%2C%20see%20%40Ju9OR%20comment)%0A10.1016%2FS0735-1097(98)00347-7%0A10.1579%2F0044-7447(2006)35%5C%5B89%3ARDUICP%5C%5D2.0.CO%3B2%0A%0AAlso%2C%20correctly%20discards%20some%20falsy%20(X%7CHT)ML%20stuff%20like%3A%0A%0A%3Cgeo%20coords%3D%2210.4515260%2C51.1656910%22%3E%3C%2Fgeo%3E\" rel=\"nofollow noreferrer\">here is a demo</a>.</p>\n"
},
{
"answer_id": 24246270,
"author": "hobwell",
"author_id": 1781344,
"author_profile": "https://Stackoverflow.com/users/1781344",
"pm_score": 2,
"selected": false,
"text": "<p>This is a really old and answered question, but here's another potential substitute.</p>\n<p><code>\\b10\\.(\\d+\\.*)+[\\/](([^\\s\\.])+\\.*)+\\b</code></p>\n<p>This assumes that white space is not part of the DOI.</p>\n<p>Haven't tested this for false positives, but it seems to be able to find all the edge cases mentioned in this page.</p>\n"
},
{
"answer_id": 48524047,
"author": "Katrin Leinweber",
"author_id": 4341322,
"author_profile": "https://Stackoverflow.com/users/4341322",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://www.crossref.org/blog/dois-and-matching-regular-expressions/\" rel=\"noreferrer\">CrossRef has a recommendation</a>, that they tested successfully on 99.3% of DOIs (known to them):</p>\n\n<pre><code>/^10.\\d{4,9}/[-._;()/:A-Z0-9]+$/i\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2963/"
] | The [DOI](http://doi.org/) system places basically no useful limitations on what constitutes [a reasonable identifier](http://doi.org/handbook_2000/enumeration.html#2.2). However, being able to pull DOIs out of PDFs, web pages, etc. is quite useful for citation information, etc.
Is there a reliable way to identify a DOI in a block of text without assuming the 'doi:' prefix? (any language acceptable, regexes preferred, and avoiding false positives a must) | Ok, I'm currently extracting thousands of DOIs from free form text (XML) and I realized that [my previous approach](https://stackoverflow.com/a/10300246/89771) had a few problems, namely regarding encoded entities and trailing punctuation, so I went on reading [the specification](http://www.doi.org/doi_handbook/2_Numbering.html) and this is the best I could come with.
---
>
> The DOI prefix shall be composed of a directory indicator followed by
> a registrant code. These two components shall be separated by a full
> stop (period).
>
>
> The directory indicator shall be "10". The directory indicator
> distinguishes the entire set of character strings (prefix and suffix)
> as digital object identifiers within the resolution system.
>
>
>
Easy enough, the initial `\b` prevents us from "matching" a "DOI" that doesn't start with `10.`:
```
$pattern = '\b(10[.]';
```
---
>
> The second element of the DOI prefix shall be the registrant code. The
> registrant code is a unique string assigned to a registrant.
>
>
>
Also, all assigned registrant code are numeric, and at least 4 digits long, so:
```
$pattern = '\b(10[.][0-9]{4,}';
```
---
>
> The registrant code may be further divided into sub-elements for
> administrative convenience if desired. Each sub-element of the
> registrant code shall be preceded by a full stop.
>
>
>
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*';`
---
>
> The DOI syntax shall be made up of a DOI prefix and a DOI suffix
> separated by a forward slash.
>
>
>
However, this isn't absolutely necessary, section 2.2.3 states that uncommon suffix systems may use other conventions (such as `10.1000.123456` instead of `10.1000/123456`), but lets cut some slack.
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/';`
---
>
> The DOI name is case-insensitive and can incorporate any printable
> characters from the legal graphic characters of Unicode. The DOI
> suffix shall consist of a character string of any length chosen by the
> registrant. Each suffix shall be unique to the prefix element that
> precedes it. The unique suffix can be a sequential number, or it might
> incorporate an identifier generated from or based on another system.
>
>
>
Now this is where it gets trickier, from all the DOIs I have processed, I saw the following characters (besides `[0-9a-zA-Z]` of course) in their **suffixes**: `.-()/:-` -- so, while it doesn't exist, the DOI `10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7` is completely plausible.
The logical choice would be to use `\S` or the `[[:graph:]]` PCRE POSIX class, so lets do that:
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/\S+'; // or`
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/[[:graph:]]+';`
---
Now we have a difficult problem, the `[[:graph:]]` class is a super-set of the `[[:punct:]]` class, which includes characters easily found in free text or any markup language: `"'&<>` among others.
Lets just filter the markup ones for now using a negative lookahead:
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+'; // or`
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+';`
---
The above should cover encoded entities (`&`), attribute quotes (`["']`) and open / close tags (`[<>]`).
Unlike markup languages, free text usually doesn't employ punctuation characters unless they are bounded by at least one space ***or*** placed at the end of a sentence, for instance:
>
> This is a long DOI:
> `10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7`**!!!**
>
>
>
The solution here is to close our capture group and assert another word boundary:
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b'; // or`
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b';`
And *voilá*, [here is a demo](http://regexpal.com/?flags=g®ex=%5Cb(10%5B.%5D%5B0-9%5D%7B4%2C%7D(%3F%3A%5B.%5D%5B0-9%5D%2B)*%2F(%3F%3A(%3F!%5B%22%26%5C%27%3C%3E%5D)%5CS)%2B)%5Cb&input=This%20is%20a%20short%20DOI%3A%2010.1000%2F123456.%0AThis%20is%20NOT%20a%20DOI%3A%204210.1000%2F123456.%0AThis%20is%20a%20long%20DOI%3A%2010.1016.12.31%2Fnature.S0735-1097(98)2000%2F12%2F31%2F34%3A7-7!!!%0A%0A10.1007%2F978-3-642-28108-2_19%0A10.1007.10%2F978-3-642-28108-2_19%20(fictitious%20example%2C%20see%20%40Ju9OR%20comment)%0A10.1016%2FS0735-1097(98)00347-7%0A10.1579%2F0044-7447(2006)35%5C%5B89%3ARDUICP%5C%5D2.0.CO%3B2%0A%0AAlso%2C%20correctly%20discards%20some%20falsy%20(X%7CHT)ML%20stuff%20like%3A%0A%0A%3Cgeo%20coords%3D%2210.4515260%2C51.1656910%22%3E%3C%2Fgeo%3E). |
27,921 | <p>Story: The user uploads an image that will be added to a photo gallery. As part of the upload process, we need to A) store the image on the web server's hard drive and B) store a thumbnail of the image on the web server's hard drive.</p>
<p>"Best" here is defined as </p>
<ul>
<li>Relatively easy to implement, understand, and maintain</li>
<li>Results in a thumbnail of reasonable quality</li>
</ul>
<p>Performance and high-quality thumbnails are secondary.</p>
| [
{
"answer_id": 27938,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 5,
"selected": true,
"text": "<p>I suppose your best solution would be using the <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx\" rel=\"noreferrer\">GetThumbnailImage </a> from the .NET <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx\" rel=\"noreferrer\">Image</a> class.</p>\n\n<pre><code>// Example in C#, should be quite alike in ASP.NET\n// Assuming filename as the uploaded file\nusing ( Image bigImage = new Bitmap( filename ) )\n{\n // Algorithm simplified for purpose of example.\n int height = bigImage.Height / 10;\n int width = bigImage.Width / 10;\n\n // Now create a thumbnail\n using ( Image smallImage = image.GetThumbnailImage( width, \n height,\n new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero) )\n {\n smallImage.Save(\"thumbnail.jpg\", ImageFormat.Jpeg);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27939,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an extension method in VB.NET for the Image Class</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Imports System.Runtime.CompilerServices\n\nNamespace Extensions\n ''' <summary>\n ''' Extensions for the Image class.\n ''' </summary>\n ''' <remarks>Several usefull extensions for the image class.</remarks>\n Public Module ImageExtensions\n\n ''' <summary>\n ''' Extends the image class so that it is easier to get a thumbnail from an image\n ''' </summary>\n ''' <param name=\"Input\">Th image that is inputted, not really a parameter</param>\n ''' <param name=\"MaximumSize\">The maximumsize the thumbnail must be if keepaspectratio is set to true then the highest number of width or height is used and the other is calculated accordingly. </param>\n ''' <param name=\"KeepAspectRatio\">If set false width and height will be the same else the highest number of width or height is used and the other is calculated accordingly.</param>\n ''' <returns>A thumbnail as image.</returns>\n ''' <remarks>\n ''' <example>Can be used as such. \n ''' <code>\n ''' Dim _NewImage as Image \n ''' Dim _Graphics As Graphics\n ''' _Image = New Bitmap(100, 100)\n ''' _Graphics = Graphics.FromImage(_Image)\n ''' _Graphics.FillRectangle(Brushes.Blue, New Rectangle(0, 0, 100, 100))\n ''' _Graphics.DrawLine(Pens.Black, 10, 0, 10, 100)\n ''' Assert.IsNotNull(_Image)\n ''' _NewImage = _Image.ToThumbnail(10)\n ''' </code>\n ''' </example>\n ''' </remarks>\n <Extension()> _\n Public Function ToThumbnail(ByVal Input As Image, ByVal MaximumSize As Integer, Optional ByVal KeepAspectRatio As Boolean = True) As Image\n Dim ReturnImage As Image\n Dim _Callback As Image.GetThumbnailImageAbort = Nothing\n Dim _OriginalHeight As Double\n Dim _OriginalWidth As Double\n Dim _NewHeight As Double\n Dim _NewWidth As Double\n Dim _NormalImage As Image\n Dim _Graphics As Graphics\n\n _NormalImage = New Bitmap(Input.Width, Input.Height)\n _Graphics = Graphics.FromImage(_NormalImage)\n _Graphics.DrawImage(Input, 0, 0, Input.Width, Input.Height)\n _OriginalHeight = _NormalImage.Height\n _OriginalWidth = _NormalImage.Width\n If KeepAspectRatio = True Then\n If _OriginalHeight > _OriginalWidth Then\n If _OriginalHeight > MaximumSize Then\n _NewHeight = MaximumSize\n _NewWidth = _OriginalWidth / _OriginalHeight * MaximumSize\n Else\n _NewHeight = _OriginalHeight\n _NewWidth = _OriginalWidth\n End If\n Else\n If _OriginalWidth > MaximumSize Then\n _NewWidth = MaximumSize\n _NewHeight = _OriginalHeight / _OriginalWidth * MaximumSize\n Else\n _NewHeight = _OriginalHeight\n _NewWidth = _OriginalWidth\n End If\n End If\n Else\n _NewHeight = MaximumSize\n _NewWidth = MaximumSize\n End If\n ReturnImage = _\n _NormalImage.GetThumbnailImage(Convert.ToInt32(_NewWidth), Convert.ToInt32(_NewHeight), _Callback, _\n IntPtr.Zero)\n _NormalImage.Dispose()\n _NormalImage = Nothing\n _Graphics.Dispose()\n _Graphics = Nothing\n _Callback = Nothing\n Return ReturnImage\n End Function\n End Module\nEnd Namespace\n</code></pre>\n\n<p>Sorry the code tag doesn't like vb.net code.</p>\n"
},
{
"answer_id": 27940,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the Image.GetThumbnailImage function to do it for you.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx</a> (.NET 3.5)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage(VS.80).aspx</a> (.NET 2.0)</p>\n\n<pre><code>public bool ThumbnailCallback()\n{\n return false;\n}\n\npublic void Example_GetThumb(PaintEventArgs e)\n{\n Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);\n Bitmap myBitmap = new Bitmap(\"Climber.jpg\");\n Image myThumbnail = myBitmap.GetThumbnailImage(40, 40, myCallback, IntPtr.Zero);\n e.Graphics.DrawImage(myThumbnail, 150, 75);\n}\n</code></pre>\n"
},
{
"answer_id": 27950,
"author": "Sean Chambers",
"author_id": 2993,
"author_profile": "https://Stackoverflow.com/users/2993",
"pm_score": 5,
"selected": false,
"text": "<p>GetThumbnailImage would work, but if you want a little better quality you can specify your image options for the BitMap class and save your loaded image into there. Here is some sample code:</p>\n\n<pre><code>Image photo; // your uploaded image\n\nBitmap bmp = new Bitmap(resizeToWidth, resizeToHeight);\ngraphic = Graphics.FromImage(bmp);\ngraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;\ngraphic.SmoothingMode = SmoothingMode.HighQuality;\ngraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;\ngraphic.CompositingQuality = CompositingQuality.HighQuality;\ngraphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);\nimageToSave = bmp;\n</code></pre>\n\n<p>This provides better quality than GetImageThumbnail would out of the box</p>\n"
},
{
"answer_id": 266640,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Avoid GetThumbnailImage - it will provide very unpredictable results, since it tries to use the embedded JPEG thumbnail if available - even if the embedded thumbnail is entirely the wrong size. DrawImage() is a much better solution.</p>\n\n<p>Wrap your bitmap in a using{} clause - you don't want leaked handles floating around...</p>\n\n<p>Also, you'll want to set your Jpeg encoding quality to 90, which is where GDI+ seems to shine the best:</p>\n\n<pre><code>System.Drawing.Imaging.ImageCodecInfo[] info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();\nSystem.Drawing.Imaging.EncoderParameters encoderParameters;\nencoderParameters = new System.Drawing.Imaging.EncoderParameters(1);\nencoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);\n\nthumb.Save(ms, info[1], encoderParameters);\n</code></pre>\n"
},
{
"answer_id": 944282,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Using an example above and some from a couple of other places, here is an easy function to just drop in (thanks to Nathanael Jones and others here). </p>\n\n<pre><code>using System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.IO;\n\npublic static void ResizeImage(string FileNameInput, string FileNameOutput, double ResizeHeight, double ResizeWidth, ImageFormat OutputFormat)\n{\n using (System.Drawing.Image photo = new Bitmap(FileNameInput))\n {\n double aspectRatio = (double)photo.Width / photo.Height;\n double boxRatio = ResizeWidth / ResizeHeight;\n double scaleFactor = 0;\n\n if (photo.Width < ResizeWidth && photo.Height < ResizeHeight)\n {\n // keep the image the same size since it is already smaller than our max width/height\n scaleFactor = 1.0;\n }\n else\n {\n if (boxRatio > aspectRatio)\n scaleFactor = ResizeHeight / photo.Height;\n else\n scaleFactor = ResizeWidth / photo.Width;\n }\n\n int newWidth = (int)(photo.Width * scaleFactor);\n int newHeight = (int)(photo.Height * scaleFactor);\n\n using (Bitmap bmp = new Bitmap(newWidth, newHeight))\n {\n using (Graphics g = Graphics.FromImage(bmp))\n {\n g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n g.SmoothingMode = SmoothingMode.HighQuality;\n g.CompositingQuality = CompositingQuality.HighQuality;\n g.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\n g.DrawImage(photo, 0, 0, newWidth, newHeight);\n\n if (ImageFormat.Png.Equals(OutputFormat))\n {\n bmp.Save(FileNameOutput, OutputFormat);\n }\n else if (ImageFormat.Jpeg.Equals(OutputFormat))\n {\n ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();\n EncoderParameters encoderParameters;\n using (encoderParameters = new System.Drawing.Imaging.EncoderParameters(1))\n {\n // use jpeg info[1] and set quality to 90\n encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);\n bmp.Save(FileNameOutput, info[1], encoderParameters);\n }\n }\n }\n }\n }\n}\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/308/"
] | Story: The user uploads an image that will be added to a photo gallery. As part of the upload process, we need to A) store the image on the web server's hard drive and B) store a thumbnail of the image on the web server's hard drive.
"Best" here is defined as
* Relatively easy to implement, understand, and maintain
* Results in a thumbnail of reasonable quality
Performance and high-quality thumbnails are secondary. | I suppose your best solution would be using the [GetThumbnailImage](http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx) from the .NET [Image](http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx) class.
```
// Example in C#, should be quite alike in ASP.NET
// Assuming filename as the uploaded file
using ( Image bigImage = new Bitmap( filename ) )
{
// Algorithm simplified for purpose of example.
int height = bigImage.Height / 10;
int width = bigImage.Width / 10;
// Now create a thumbnail
using ( Image smallImage = image.GetThumbnailImage( width,
height,
new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero) )
{
smallImage.Save("thumbnail.jpg", ImageFormat.Jpeg);
}
}
``` |
27,928 | <p>How do I calculate the distance between two points specified by latitude and longitude?</p>
<p>For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available.</p>
| [
{
"answer_id": 27943,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 11,
"selected": true,
"text": "<p>This <a href=\"http://www.movable-type.co.uk/scripts/latlong.html\" rel=\"noreferrer\">link</a> might be helpful to you, as it details the use of the <a href=\"http://en.wikipedia.org/wiki/Haversine_formula\" rel=\"noreferrer\">Haversine formula</a> to calculate the distance.</p>\n\n<p>Excerpt:</p>\n\n\n\n<blockquote>\n <p>This script [in Javascript] calculates great-circle distances between the two points –\n that is, the shortest distance over the earth’s surface – using the\n ‘Haversine’ formula.</p>\n</blockquote>\n\n<pre class=\"lang-js prettyprint-override\"><code>function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {\n var R = 6371; // Radius of the earth in km\n var dLat = deg2rad(lat2-lat1); // deg2rad below\n var dLon = deg2rad(lon2-lon1); \n var a = \n Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * \n Math.sin(dLon/2) * Math.sin(dLon/2)\n ; \n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n var d = R * c; // Distance in km\n return d;\n}\n\nfunction deg2rad(deg) {\n return deg * (Math.PI/180)\n}\n</code></pre>\n"
},
{
"answer_id": 215848,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>To calculate the distance between two points on a sphere you need to do the <a href=\"http://en.wikipedia.org/wiki/Great-circle_distance\" rel=\"nofollow noreferrer\">Great Circle calculation</a>. </p>\n\n<p>There are a number of C/C++ libraries to help with map projection at <a href=\"http://www.maptools.org/\" rel=\"nofollow noreferrer\">MapTools</a> if you need to reproject your distances to a flat surface. To do this you will need the projection string of the various coordinate systems.</p>\n\n<p>You may also find <a href=\"http://www.mapwindow.org/\" rel=\"nofollow noreferrer\">MapWindow</a> a useful tool to visualise the points. Also as its open source its a useful guide to how to use the proj.dll library, which appears to be the core open source projection library.</p>\n"
},
{
"answer_id": 215849,
"author": "jaircazarin-old-account",
"author_id": 20915,
"author_profile": "https://Stackoverflow.com/users/20915",
"pm_score": 6,
"selected": false,
"text": "<p>Here is a C# Implementation:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>static class DistanceAlgorithm\n{\n const double PIx = 3.141592653589793;\n const double RADIUS = 6378.16;\n\n /// <summary>\n /// Convert degrees to Radians\n /// </summary>\n /// <param name=\"x\">Degrees</param>\n /// <returns>The equivalent in radians</returns>\n public static double Radians(double x)\n {\n return x * PIx / 180;\n }\n\n /// <summary>\n /// Calculate the distance between two places.\n /// </summary>\n /// <param name=\"lon1\"></param>\n /// <param name=\"lat1\"></param>\n /// <param name=\"lon2\"></param>\n /// <param name=\"lat2\"></param>\n /// <returns></returns>\n public static double DistanceBetweenPlaces(\n double lon1,\n double lat1,\n double lon2,\n double lat2)\n {\n double dlon = Radians(lon2 - lon1);\n double dlat = Radians(lat2 - lat1);\n\n double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(Radians(lat1)) * Math.Cos(Radians(lat2)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));\n double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));\n return angle * RADIUS;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 4377364,
"author": "Stephen Watson",
"author_id": 485514,
"author_profile": "https://Stackoverflow.com/users/485514",
"pm_score": 5,
"selected": false,
"text": "<p>Thanks very much for all this. I used the following code in my Objective-C iPhone app:</p>\n\n\n\n<pre class=\"lang-c prettyprint-override\"><code>const double PIx = 3.141592653589793;\nconst double RADIO = 6371; // Mean radius of Earth in Km\n\ndouble convertToRadians(double val) {\n\n return val * PIx / 180;\n}\n\n-(double)kilometresBetweenPlace1:(CLLocationCoordinate2D) place1 andPlace2:(CLLocationCoordinate2D) place2 {\n\n double dlon = convertToRadians(place2.longitude - place1.longitude);\n double dlat = convertToRadians(place2.latitude - place1.latitude);\n\n double a = ( pow(sin(dlat / 2), 2) + cos(convertToRadians(place1.latitude))) * cos(convertToRadians(place2.latitude)) * pow(sin(dlon / 2), 2);\n double angle = 2 * asin(sqrt(a));\n\n return angle * RADIO;\n}\n</code></pre>\n\n<p>Latitude and Longitude are in decimal. I didn't use min() for the asin() call as the distances that I'm using are so small that they don't require it.</p>\n\n<p>It gave incorrect answers until I passed in the values in Radians - now it's pretty much the same as the values obtained from Apple's Map app :-)</p>\n\n<p>Extra update:</p>\n\n<p>If you are using iOS4 or later then Apple provide some methods to do this so the same functionality would be achieved with:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>-(double)kilometresBetweenPlace1:(CLLocationCoordinate2D) place1 andPlace2:(CLLocationCoordinate2D) place2 {\n\n MKMapPoint start, finish;\n\n\n start = MKMapPointForCoordinate(place1);\n finish = MKMapPointForCoordinate(place2);\n\n return MKMetersBetweenMapPoints(start, finish) / 1000;\n}\n</code></pre>\n"
},
{
"answer_id": 9676337,
"author": "conualfy",
"author_id": 703474,
"author_profile": "https://Stackoverflow.com/users/703474",
"pm_score": 5,
"selected": false,
"text": "<p>I post here my working example.</p>\n\n<p>List all points in table having distance between a designated point (we use a random point - lat:45.20327, long:23.7806) less than 50 KM, with latitude & longitude, in MySQL (the table fields are coord_lat and coord_long):</p>\n\n<p><strong>List all having DISTANCE<50, in Kilometres (considered Earth radius 6371 KM):</strong></p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT denumire, (6371 * acos( cos( radians(45.20327) ) * cos( radians( coord_lat ) ) * cos( radians( 23.7806 ) - radians(coord_long) ) + sin( radians(45.20327) ) * sin( radians(coord_lat) ) )) AS distanta \nFROM obiective \nWHERE coord_lat<>'' \n AND coord_long<>'' \nHAVING distanta<50 \nORDER BY distanta desc\n</code></pre>\n\n<p>The above example was tested in MySQL 5.0.95 and 5.5.16 (Linux). </p>\n"
},
{
"answer_id": 11178145,
"author": "tony gil",
"author_id": 1166727,
"author_profile": "https://Stackoverflow.com/users/1166727",
"pm_score": 5,
"selected": false,
"text": "<p>This is a simple PHP function that will give a very reasonable approximation (under +/-1% error margin). </p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\nfunction distance($lat1, $lon1, $lat2, $lon2) {\n\n $pi80 = M_PI / 180;\n $lat1 *= $pi80;\n $lon1 *= $pi80;\n $lat2 *= $pi80;\n $lon2 *= $pi80;\n\n $r = 6372.797; // mean radius of Earth in km\n $dlat = $lat2 - $lat1;\n $dlon = $lon2 - $lon1;\n $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);\n $c = 2 * atan2(sqrt($a), sqrt(1 - $a));\n $km = $r * $c;\n\n //echo '<br/>'.$km;\n return $km;\n}\n?>\n</code></pre>\n\n<p>As said before; the earth is NOT a sphere. It is like an old, old baseball that Mark McGwire decided to practice with - it is full of dents and bumps. The simpler calculations (like this) treat it like a sphere.</p>\n\n<p>Different methods may be more or less precise according to where you are on this irregular ovoid AND how far apart your points are (the closer they are the smaller the absolute error margin). The more precise your expectation, the more complex the math.</p>\n\n<p>For more info: <a href=\"http://en.wikipedia.org/wiki/Geographical_distance\" rel=\"noreferrer\">wikipedia geographic distance</a></p>\n"
},
{
"answer_id": 12600225,
"author": "whostolebenfrog",
"author_id": 599936,
"author_profile": "https://Stackoverflow.com/users/599936",
"pm_score": 6,
"selected": false,
"text": "<p>Here is a java implementation of the Haversine formula.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public final static double AVERAGE_RADIUS_OF_EARTH_KM = 6371;\npublic int calculateDistanceInKilometer(double userLat, double userLng,\n double venueLat, double venueLng) {\n\n double latDistance = Math.toRadians(userLat - venueLat);\n double lngDistance = Math.toRadians(userLng - venueLng);\n\n double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)\n + Math.cos(Math.toRadians(userLat)) * Math.cos(Math.toRadians(venueLat))\n * Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2);\n\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n return (int) (Math.round(AVERAGE_RADIUS_OF_EARTH_KM * c));\n}\n</code></pre>\n\n<p>Note that here we are rounding the answer to the nearest km.</p>\n"
},
{
"answer_id": 12930877,
"author": "bherto39",
"author_id": 1531382,
"author_profile": "https://Stackoverflow.com/users/1531382",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a simple javascript function that may be useful from this <a href=\"http://www.movable-type.co.uk/scripts/latlong.html\" rel=\"nofollow\">link</a>.. somehow related but we're using google earth javascript plugin instead of maps</p>\n\n<pre><code>function getApproximateDistanceUnits(point1, point2) {\n\n var xs = 0;\n var ys = 0;\n\n xs = point2.getX() - point1.getX();\n xs = xs * xs;\n\n ys = point2.getY() - point1.getY();\n ys = ys * ys;\n\n return Math.sqrt(xs + ys);\n}\n</code></pre>\n\n<p>The units tho are not in distance but in terms of a ratio relative to your coordinates. There are other computations related you can substitute for the getApproximateDistanceUnits function <a href=\"http://www.movable-type.co.uk/scripts/latlong.html\" rel=\"nofollow\">link here</a></p>\n\n<p>Then I use this function to see if a latitude longitude is within the radius</p>\n\n<pre><code>function isMapPlacemarkInRadius(point1, point2, radi) {\n if (point1 && point2) {\n return getApproximateDistanceUnits(point1, point2) <= radi;\n } else {\n return 0;\n }\n}\n</code></pre>\n\n<p>point may be defined as</p>\n\n<pre><code> $$.getPoint = function(lati, longi) {\n var location = {\n x: 0,\n y: 0,\n getX: function() { return location.x; },\n getY: function() { return location.y; }\n };\n location.x = lati;\n location.y = longi;\n\n return location;\n };\n</code></pre>\n\n<p>then you can do your thing to see if a point is within a region with a radius say:</p>\n\n<pre><code> //put it on the map if within the range of a specified radi assuming 100,000,000 units\n var iconpoint = Map.getPoint(pp.latitude, pp.longitude);\n var centerpoint = Map.getPoint(Settings.CenterLatitude, Settings.CenterLongitude);\n\n //approx ~200 units to show only half of the globe from the default center radius\n if (isMapPlacemarkInRadius(centerpoint, iconpoint, 120)) {\n addPlacemark(pp.latitude, pp.longitude, pp.name);\n }\n else {\n otherSidePlacemarks.push({\n latitude: pp.latitude,\n longitude: pp.longitude,\n name: pp.name\n });\n\n }\n</code></pre>\n"
},
{
"answer_id": 14329945,
"author": "ayalcinkaya",
"author_id": 1589731,
"author_profile": "https://Stackoverflow.com/users/1589731",
"pm_score": 2,
"selected": false,
"text": "<p>there is a good example in here to calculate distance with PHP <a href=\"http://www.geodatasource.com/developers/php\" rel=\"nofollow\">http://www.geodatasource.com/developers/php</a> :</p>\n\n<pre><code> function distance($lat1, $lon1, $lat2, $lon2, $unit) {\n\n $theta = $lon1 - $lon2;\n $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));\n $dist = acos($dist);\n $dist = rad2deg($dist);\n $miles = $dist * 60 * 1.1515;\n $unit = strtoupper($unit);\n\n if ($unit == \"K\") {\n return ($miles * 1.609344);\n } else if ($unit == \"N\") {\n return ($miles * 0.8684);\n } else {\n return $miles;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 15759519,
"author": "Taiseer Joudeh",
"author_id": 3625265,
"author_profile": "https://Stackoverflow.com/users/3625265",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the implementation VB.NET, this implementation will give you the result in KM or Miles based on an Enum value you pass.</p>\n\n<pre><code>Public Enum DistanceType\n Miles\n KiloMeters\nEnd Enum\n\nPublic Structure Position\n Public Latitude As Double\n Public Longitude As Double\nEnd Structure\n\nPublic Class Haversine\n\n Public Function Distance(Pos1 As Position,\n Pos2 As Position,\n DistType As DistanceType) As Double\n\n Dim R As Double = If((DistType = DistanceType.Miles), 3960, 6371)\n\n Dim dLat As Double = Me.toRadian(Pos2.Latitude - Pos1.Latitude)\n\n Dim dLon As Double = Me.toRadian(Pos2.Longitude - Pos1.Longitude)\n\n Dim a As Double = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(Me.toRadian(Pos1.Latitude)) * Math.Cos(Me.toRadian(Pos2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)\n\n Dim c As Double = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)))\n\n Dim result As Double = R * c\n\n Return result\n\n End Function\n\n Private Function toRadian(val As Double) As Double\n\n Return (Math.PI / 180) * val\n\n End Function\n\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 17078193,
"author": "Kache",
"author_id": 234593,
"author_profile": "https://Stackoverflow.com/users/234593",
"pm_score": 2,
"selected": false,
"text": "<p>I condensed the computation down by simplifying the formula.</p>\n\n<p>Here it is in Ruby:</p>\n\n<pre><code>include Math\nearth_radius_mi = 3959\nradians = lambda { |deg| deg * PI / 180 }\ncoord_radians = lambda { |c| { :lat => radians[c[:lat]], :lng => radians[c[:lng]] } }\n\n# from/to = { :lat => (latitude_in_degrees), :lng => (longitude_in_degrees) }\ndef haversine_distance(from, to)\n from, to = coord_radians[from], coord_radians[to]\n cosines_product = cos(to[:lat]) * cos(from[:lat]) * cos(from[:lng] - to[:lng])\n sines_product = sin(to[:lat]) * sin(from[:lat])\n return earth_radius_mi * acos(cosines_product + sines_product)\nend\n</code></pre>\n"
},
{
"answer_id": 17315408,
"author": "Andre Cytryn",
"author_id": 1165337,
"author_profile": "https://Stackoverflow.com/users/1165337",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the build in CLLocationDistance to calculate this:</p>\n\n<pre><code>CLLocation *location1 = [[CLLocation alloc] initWithLatitude:latitude1 longitude:longitude1];\nCLLocation *location2 = [[CLLocation alloc] initWithLatitude:latitude2 longitude:longitude2];\n[self distanceInMetersFromLocation:location1 toLocation:location2]\n\n- (int)distanceInMetersFromLocation:(CLLocation*)location1 toLocation:(CLLocation*)location2 {\n CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];\n return distanceInMeters;\n}\n</code></pre>\n\n<p>In your case if you want kilometers just divide by 1000.</p>\n"
},
{
"answer_id": 19772119,
"author": "Arturo Hernandez",
"author_id": 937703,
"author_profile": "https://Stackoverflow.com/users/937703",
"pm_score": 4,
"selected": false,
"text": "<p>The haversine is definitely a good formula for probably most cases, other answers already include it so I am not going to take the space. But it is important to note that no matter what formula is used (yes not just one). Because of the huge range of accuracy possible as well as the computation time required. The choice of formula requires a bit more thought than a simple no brainer answer. </p>\n\n<p>This posting from a person at nasa, is the best one I found at discussing the options</p>\n\n<p><a href=\"http://www.cs.nyu.edu/visual/home/proj/tiger/gisfaq.html\" rel=\"noreferrer\">http://www.cs.nyu.edu/visual/home/proj/tiger/gisfaq.html</a></p>\n\n<p>For example, if you are just sorting rows by distance in a 100 miles radius. The flat earth formula will be much faster than the haversine.</p>\n\n<pre><code>HalfPi = 1.5707963;\nR = 3956; /* the radius gives you the measurement unit*/\n\na = HalfPi - latoriginrad;\nb = HalfPi - latdestrad;\nu = a * a + b * b;\nv = - 2 * a * b * cos(longdestrad - longoriginrad);\nc = sqrt(abs(u + v));\nreturn R * c;\n</code></pre>\n\n<p>Notice there is just one cosine and one square root. Vs 9 of them on the Haversine formula.</p>\n"
},
{
"answer_id": 19852967,
"author": "MPaulo",
"author_id": 1105558,
"author_profile": "https://Stackoverflow.com/users/1105558",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2,units) {\n var R = 6371; // Radius of the earth in km\n var dLat = deg2rad(lat2-lat1); // deg2rad below\n var dLon = deg2rad(lon2-lon1); \n var a = \n Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * \n Math.sin(dLon/2) * Math.sin(dLon/2)\n ; \n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n var d = R * c; \n var miles = d / 1.609344; \n\nif ( units == 'km' ) { \nreturn d; \n } else {\nreturn miles;\n}}\n</code></pre>\n\n<p>Chuck's solution, valid for miles also.</p>\n"
},
{
"answer_id": 21623206,
"author": "Salvador Dali",
"author_id": 1090562,
"author_profile": "https://Stackoverflow.com/users/1090562",
"pm_score": 9,
"selected": false,
"text": "<p>I needed to calculate a lot of distances between the points for my project, so I went ahead and tried to optimize the code, I have found here. On average in different browsers my new implementation <strong>runs 2 times faster</strong> than the most upvoted answer.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function distance(lat1, lon1, lat2, lon2) {\n var p = 0.017453292519943295; // Math.PI / 180\n var c = Math.cos;\n var a = 0.5 - c((lat2 - lat1) * p)/2 + \n c(lat1 * p) * c(lat2 * p) * \n (1 - c((lon2 - lon1) * p))/2;\n\n return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km\n}\n</code></pre>\n<p>You can play with my jsPerf and see the <a href=\"http://jsperf.com/haversine-salvador/8\" rel=\"noreferrer\">results here</a>.</p>\n<p>Recently I needed to do the same in python, so here is a <strong>python implementation</strong>:</p>\n<pre class=\"lang-python prettyprint-override\"><code>from math import cos, asin, sqrt, pi\n\ndef distance(lat1, lon1, lat2, lon2):\n p = pi/180\n a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2\n return 12742 * asin(sqrt(a)) #2*R*asin...\n</code></pre>\n<p>And for the sake of completeness: <a href=\"https://en.wikipedia.org/wiki/Haversine_formula\" rel=\"noreferrer\">Haversine</a> on Wikipedia.</p>\n"
},
{
"answer_id": 21739328,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my java implementation for calculation distance via decimal degrees after some search. I used mean radius of world (from wikipedia) in km. İf you want result miles then use world radius in miles.</p>\n\n<pre><code>public static double distanceLatLong2(double lat1, double lng1, double lat2, double lng2) \n{\n double earthRadius = 6371.0d; // KM: use mile here if you want mile result\n\n double dLat = toRadian(lat2 - lat1);\n double dLng = toRadian(lng2 - lng1);\n\n double a = Math.pow(Math.sin(dLat/2), 2) + \n Math.cos(toRadian(lat1)) * Math.cos(toRadian(lat2)) * \n Math.pow(Math.sin(dLng/2), 2);\n\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\n return earthRadius * c; // returns result kilometers\n}\n\npublic static double toRadian(double degrees) \n{\n return (degrees * Math.PI) / 180.0d;\n}\n</code></pre>\n"
},
{
"answer_id": 23095329,
"author": "Jaap",
"author_id": 2204410,
"author_profile": "https://Stackoverflow.com/users/2204410",
"pm_score": 5,
"selected": false,
"text": "<p>In the other answers an implementation in <a href=\"/questions/tagged/r\" class=\"post-tag\" title=\"show questions tagged 'r'\" rel=\"tag\">r</a> is missing.</p>\n\n<p>Calculating the distance between two point is quite straightforward with the <code>distm</code> function from the <code>geosphere</code> package:</p>\n\n<pre><code>distm(p1, p2, fun = distHaversine)\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>p1 = longitude/latitude for point(s)\np2 = longitude/latitude for point(s)\n# type of distance calculation\nfun = distCosine / distHaversine / distVincentySphere / distVincentyEllipsoid \n</code></pre>\n\n<p>As the earth is not perfectly spherical, the <a href=\"http://en.wikipedia.org/wiki/Vincenty%27s_formulae\" rel=\"noreferrer\">Vincenty formula for ellipsoids</a> is probably the best way to calculate distances. Thus in the <code>geosphere</code> package you use then:</p>\n\n<pre><code>distm(p1, p2, fun = distVincentyEllipsoid)\n</code></pre>\n\n<hr>\n\n<p>Off course you don't necessarily have to use <code>geosphere</code> package, you can also calculate the distance in base <code>R</code> with a function:</p>\n\n<pre><code>hav.dist <- function(long1, lat1, long2, lat2) {\n R <- 6371\n diff.long <- (long2 - long1)\n diff.lat <- (lat2 - lat1)\n a <- sin(diff.lat/2)^2 + cos(lat1) * cos(lat2) * sin(diff.long/2)^2\n b <- 2 * asin(pmin(1, sqrt(a))) \n d = R * b\n return(d)\n}\n</code></pre>\n"
},
{
"answer_id": 23907104,
"author": "shanavascet",
"author_id": 2286174,
"author_profile": "https://Stackoverflow.com/users/2286174",
"pm_score": 2,
"selected": false,
"text": "<p>In Mysql use the following function pass the parameters as using <code>POINT(LONG,LAT)</code></p>\n\n<pre><code>CREATE FUNCTION `distance`(a POINT, b POINT)\n RETURNS double\n DETERMINISTIC\nBEGIN\n\nRETURN\n\nGLength( LineString(( PointFromWKB(a)), (PointFromWKB(b)))) * 100000; -- To Make the distance in meters\n\nEND;\n</code></pre>\n"
},
{
"answer_id": 24058134,
"author": "borchvm",
"author_id": 3115822,
"author_profile": "https://Stackoverflow.com/users/3115822",
"pm_score": 0,
"selected": false,
"text": "<pre><code>//JAVA\n public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {\n final int RADIUS_EARTH = 6371;\n\n double dLat = getRad(latitude2 - latitude1);\n double dLong = getRad(longitude2 - longitude1);\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n return (RADIUS_EARTH * c) * 1000;\n }\n\n private Double getRad(Double x) {\n return x * Math.PI / 180;\n }\n</code></pre>\n"
},
{
"answer_id": 24846150,
"author": "Steven Christenson",
"author_id": 2723552,
"author_profile": "https://Stackoverflow.com/users/2723552",
"pm_score": 3,
"selected": false,
"text": "<p>I don't like adding yet another answer, but the Google maps API v.3 has spherical geometry (and more). After converting your WGS84 to decimal degrees you can do this:</p>\n\n<pre><code><script src=\"http://maps.google.com/maps/api/js?sensor=false&libraries=geometry\" type=\"text/javascript\"></script> \n\ndistance = google.maps.geometry.spherical.computeDistanceBetween(\n new google.maps.LatLng(fromLat, fromLng), \n new google.maps.LatLng(toLat, toLng));\n</code></pre>\n\n<p>No word about how accurate Google's calculations are or even what model is used (though it does say \"spherical\" rather than \"geoid\". By the way, the \"straight line\" distance will obviously be different from the distance if one travels on the surface of the earth which is what everyone seems to be presuming.</p>\n"
},
{
"answer_id": 25266454,
"author": "Jorik",
"author_id": 1346170,
"author_profile": "https://Stackoverflow.com/users/1346170",
"pm_score": 0,
"selected": false,
"text": "<p>I've created this small Javascript LatLng object, might be useful for somebody.</p>\n\n<pre><code>var latLng1 = new LatLng(5, 3);\nvar latLng2 = new LatLng(6, 7);\nvar distance = latLng1.distanceTo(latLng2); \n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>/**\n * latLng point\n * @param {Number} lat\n * @param {Number} lng\n * @returns {LatLng}\n * @constructor\n */\nfunction LatLng(lat,lng) {\n this.lat = parseFloat(lat);\n this.lng = parseFloat(lng);\n\n this.__cache = {};\n}\n\nLatLng.prototype = {\n toString: function() {\n return [this.lat, this.lng].join(\",\");\n },\n\n /**\n * calculate distance in km to another latLng, with caching\n * @param {LatLng} latLng\n * @returns {Number} distance in km\n */\n distanceTo: function(latLng) {\n var cacheKey = latLng.toString();\n if(cacheKey in this.__cache) {\n return this.__cache[cacheKey];\n }\n\n // the fastest way to calculate the distance, according to this jsperf test;\n // http://jsperf.com/haversine-salvador/8\n // http://stackoverflow.com/questions/27928\n var deg2rad = 0.017453292519943295; // === Math.PI / 180\n var lat1 = this.lat * deg2rad;\n var lng1 = this.lng * deg2rad;\n var lat2 = latLng.lat * deg2rad;\n var lng2 = latLng.lng * deg2rad;\n var a = (\n (1 - Math.cos(lat2 - lat1)) +\n (1 - Math.cos(lng2 - lng1)) * Math.cos(lat1) * Math.cos(lat2)\n ) / 2;\n var distance = 12742 * Math.asin(Math.sqrt(a)); // Diameter of the earth in km (2 * 6371)\n\n // cache the distance\n this.__cache[cacheKey] = distance;\n\n return distance;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 27218153,
"author": "Eric Walsh",
"author_id": 2577822,
"author_profile": "https://Stackoverflow.com/users/2577822",
"pm_score": 1,
"selected": false,
"text": "<p>Had an issue with math.deg in LUA... if anyone knows a fix please clean up this code! </p>\n\n<p>In the meantime here's an implementation of the Haversine in LUA (use this with Redis!)</p>\n\n<pre><code>function calcDist(lat1, lon1, lat2, lon2)\n lat1= lat1*0.0174532925\n lat2= lat2*0.0174532925\n lon1= lon1*0.0174532925\n lon2= lon2*0.0174532925\n\n dlon = lon2-lon1\n dlat = lat2-lat1\n\n a = math.pow(math.sin(dlat/2),2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(dlon/2),2)\n c = 2 * math.asin(math.sqrt(a))\n dist = 6371 * c -- multiply by 0.621371 to convert to miles\n return dist\nend\n</code></pre>\n\n<p>cheers!</p>\n"
},
{
"answer_id": 29946545,
"author": "Raphael C",
"author_id": 1872349,
"author_profile": "https://Stackoverflow.com/users/1872349",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function getDistanceFromLatLonInKm(position1, position2) {\n "use strict";\n var deg2rad = function (deg) { return deg * (Math.PI / 180); },\n R = 6371,\n dLat = deg2rad(position2.lat - position1.lat),\n dLng = deg2rad(position2.lng - position1.lng),\n a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n + Math.cos(deg2rad(position1.lat))\n * Math.cos(deg2rad(position2.lat))\n * Math.sin(dLng / 2) * Math.sin(dLng / 2),\n c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n return R * c;\n}\n\nconsole.log(getDistanceFromLatLonInKm(\n {lat: 48.7931459, lng: 1.9483572},\n {lat: 48.827167, lng: 2.2459745}\n));\n</code></pre>\n"
},
{
"answer_id": 31398615,
"author": "invoketheshell",
"author_id": 4930264,
"author_profile": "https://Stackoverflow.com/users/4930264",
"pm_score": 3,
"selected": false,
"text": "<p><code>pip install haversine</code></p>\n<p>Python implementation</p>\n<p>Origin is the center of the contiguous United States.</p>\n<pre><code>from haversine import haversine, Unit\norigin = (39.50, 98.35)\nparis = (48.8567, 2.3508)\nhaversine(origin, paris, unit=Unit.MILES)\n</code></pre>\n<p>To get the answer in kilometers simply set <code>unit=Unit.KILOMETERS</code> (that's the default).</p>\n"
},
{
"answer_id": 33090122,
"author": "Eduardo Naveda",
"author_id": 1472511,
"author_profile": "https://Stackoverflow.com/users/1472511",
"pm_score": 2,
"selected": false,
"text": "<p>Here's the accepted answer implementation ported to Java in case anyone needs it.</p>\n\n<pre><code>package com.project529.garage.util;\n\n\n/**\n * Mean radius.\n */\nprivate static double EARTH_RADIUS = 6371;\n\n/**\n * Returns the distance between two sets of latitudes and longitudes in meters.\n * <p/>\n * Based from the following JavaScript SO answer:\n * http://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula,\n * which is based on https://en.wikipedia.org/wiki/Haversine_formula (error rate: ~0.55%).\n */\npublic double getDistanceBetween(double lat1, double lon1, double lat2, double lon2) {\n double dLat = toRadians(lat2 - lat1);\n double dLon = toRadians(lon2 - lon1);\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *\n Math.sin(dLon / 2) * Math.sin(dLon / 2);\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n double d = EARTH_RADIUS * c;\n\n return d;\n}\n\npublic double toRadians(double degrees) {\n return degrees * (Math.PI / 180);\n}\n</code></pre>\n"
},
{
"answer_id": 34241873,
"author": "Sel",
"author_id": 2706338,
"author_profile": "https://Stackoverflow.com/users/2706338",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a <strong>typescript</strong> implementation of the Haversine formula</p>\n\n<pre><code>static getDistanceFromLatLonInKm(lat1: number, lon1: number, lat2: number, lon2: number): number {\n var deg2Rad = deg => {\n return deg * Math.PI / 180;\n }\n\n var r = 6371; // Radius of the earth in km\n var dLat = deg2Rad(lat2 - lat1); \n var dLon = deg2Rad(lon2 - lon1);\n var a =\n Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(deg2Rad(lat1)) * Math.cos(deg2Rad(lat2)) *\n Math.sin(dLon / 2) * Math.sin(dLon / 2);\n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n var d = r * c; // Distance in km\n return d;\n}\n</code></pre>\n"
},
{
"answer_id": 35309170,
"author": "Meymann",
"author_id": 361169,
"author_profile": "https://Stackoverflow.com/users/361169",
"pm_score": 3,
"selected": false,
"text": "<p>There could be a simpler solution, and more correct: The perimeter of earth is 40,000Km at the equator, about 37,000 on Greenwich (or any longitude) cycle. Thus:</p>\n\n<pre><code>pythagoras = function (lat1, lon1, lat2, lon2) {\n function sqr(x) {return x * x;}\n function cosDeg(x) {return Math.cos(x * Math.PI / 180.0);}\n\n var earthCyclePerimeter = 40000000.0 * cosDeg((lat1 + lat2) / 2.0);\n var dx = (lon1 - lon2) * earthCyclePerimeter / 360.0;\n var dy = 37000000.0 * (lat1 - lat2) / 360.0;\n\n return Math.sqrt(sqr(dx) + sqr(dy));\n};\n</code></pre>\n\n<p>I agree that it should be fine-tuned as, I myself said that it's an ellipsoid, so the radius to be multiplied by the cosine varies. But it's a bit more accurate. Compared with Google Maps and it did reduce the error significantly.</p>\n"
},
{
"answer_id": 37870363,
"author": "Keerthana Gopalakrishnan",
"author_id": 4400634,
"author_profile": "https://Stackoverflow.com/users/4400634",
"pm_score": 3,
"selected": false,
"text": "<p>There is some errors in the code provided, I've fixed it below.</p>\n<p>All the above answers assumes the earth is a sphere. However, a more accurate approximation would be that of an oblate spheroid.</p>\n<pre><code>a= 6378.137#equitorial radius in km\nb= 6356.752#polar radius in km\n\ndef Distance(lat1, lons1, lat2, lons2):\n lat1=math.radians(lat1)\n lons1=math.radians(lons1)\n R1=(((((a**2)*math.cos(lat1))**2)+(((b**2)*math.sin(lat1))**2))/((a*math.cos(lat1))**2+(b*math.sin(lat1))**2))**0.5 #radius of earth at lat1\n x1=R1*math.cos(lat1)*math.cos(lons1)\n y1=R1*math.cos(lat1)*math.sin(lons1)\n z1=R1*math.sin(lat1)\n\n lat2=math.radians(lat2)\n lons2=math.radians(lons2)\n R2=(((((a**2)*math.cos(lat2))**2)+(((b**2)*math.sin(lat2))**2))/((a*math.cos(lat2))**2+(b*math.sin(lat2))**2))**0.5 #radius of earth at lat2\n x2=R2*math.cos(lat2)*math.cos(lons2)\n y2=R2*math.cos(lat2)*math.sin(lons2)\n z2=R2*math.sin(lat2)\n \n return ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5\n</code></pre>\n"
},
{
"answer_id": 41257416,
"author": "fla",
"author_id": 2598693,
"author_profile": "https://Stackoverflow.com/users/2598693",
"pm_score": 2,
"selected": false,
"text": "<p>here is an example in <strong>postgres</strong> sql (in km, for miles version, replace 1.609344 by 0.8684 version)</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION public.geodistance(alat float, alng float, blat \n\nfloat, blng float)\n RETURNS float AS\n$BODY$\nDECLARE\n v_distance float;\nBEGIN\n\n v_distance = asin( sqrt(\n sin(radians(blat-alat)/2)^2 \n + (\n (sin(radians(blng-alng)/2)^2) *\n cos(radians(alat)) *\n cos(radians(blat))\n )\n )\n ) * cast('7926.3352' as float) * cast('1.609344' as float) ;\n\n\n RETURN v_distance;\nEND \n$BODY$\nlanguage plpgsql VOLATILE SECURITY DEFINER;\nalter function geodistance(alat float, alng float, blat float, blng float)\nowner to postgres;\n</code></pre>\n"
},
{
"answer_id": 42360739,
"author": "Er.Subhendu Kumar Pati",
"author_id": 7596912,
"author_profile": "https://Stackoverflow.com/users/7596912",
"pm_score": 3,
"selected": false,
"text": "<p>This script [in PHP] calculates distances between the two points.</p>\n\n<pre><code>public static function getDistanceOfTwoPoints($source, $dest, $unit='K') {\n $lat1 = $source[0];\n $lon1 = $source[1];\n $lat2 = $dest[0];\n $lon2 = $dest[1];\n\n $theta = $lon1 - $lon2;\n $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));\n $dist = acos($dist);\n $dist = rad2deg($dist);\n $miles = $dist * 60 * 1.1515;\n $unit = strtoupper($unit);\n\n if ($unit == \"K\") {\n return ($miles * 1.609344);\n }\n else if ($unit == \"M\")\n {\n return ($miles * 1.609344 * 1000);\n }\n else if ($unit == \"N\") {\n return ($miles * 0.8684);\n } \n else {\n return $miles;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 46771383,
"author": "aldrien.h",
"author_id": 2534479,
"author_profile": "https://Stackoverflow.com/users/2534479",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another converted to <strong>Ruby</strong> code:</p>\n\n<pre><code>include Math\n#Note: from/to = [lat, long]\n\ndef get_distance_in_km(from, to)\n radians = lambda { |deg| deg * Math.PI / 180 }\n radius = 6371 # Radius of the earth in kilometer\n dLat = radians[to[0]-from[0]]\n dLon = radians[to[1]-from[1]]\n\n cosines_product = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(radians[from[0]]) * Math.cos(radians[to[1]]) * Math.sin(dLon/2) * Math.sin(dLon/2)\n\n c = 2 * Math.atan2(Math.sqrt(cosines_product), Math.sqrt(1-cosines_product)) \n return radius * c # Distance in kilometer\nend\n</code></pre>\n"
},
{
"answer_id": 49916544,
"author": "Chong Lip Phang",
"author_id": 2435020,
"author_profile": "https://Stackoverflow.com/users/2435020",
"pm_score": 3,
"selected": false,
"text": "<p>As pointed out, an accurate calculation should take into account that the earth is not a perfect sphere. Here are some comparisons of the various algorithms offered here:</p>\n\n<pre><code>geoDistance(50,5,58,3)\nHaversine: 899 km\nMaymenn: 833 km\nKeerthana: 897 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 900 km\n\ngeoDistance(50,5,-58,-3)\nHaversine: 12030 km\nMaymenn: 11135 km\nKeerthana: 10310 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 12044 km\n\ngeoDistance(.05,.005,.058,.003)\nHaversine: 0.9169 km\nMaymenn: 0.851723 km\nKeerthana: 0.917964 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 0.917964 km\n\ngeoDistance(.05,80,.058,80.3)\nHaversine: 33.37 km\nMaymenn: 33.34 km\nKeerthana: 33.40767 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 33.40770 km\n</code></pre>\n\n<p>Over small distances, Keerthana's algorithm does seem to coincide with that of Google Maps. Google Maps does not seem to follow any simple algorithm, suggesting that it may be the most accurate method here.</p>\n\n<p>Anyway, here is a Javascript implementation of Keerthana's algorithm:</p>\n\n<pre><code>function geoDistance(lat1, lng1, lat2, lng2){\n const a = 6378.137; // equitorial radius in km\n const b = 6356.752; // polar radius in km\n\n var sq = x => (x*x);\n var sqr = x => Math.sqrt(x);\n var cos = x => Math.cos(x);\n var sin = x => Math.sin(x);\n var radius = lat => sqr((sq(a*a*cos(lat))+sq(b*b*sin(lat)))/(sq(a*cos(lat))+sq(b*sin(lat))));\n\n lat1 = lat1 * Math.PI / 180;\n lng1 = lng1 * Math.PI / 180;\n lat2 = lat2 * Math.PI / 180;\n lng2 = lng2 * Math.PI / 180;\n\n var R1 = radius(lat1);\n var x1 = R1*cos(lat1)*cos(lng1);\n var y1 = R1*cos(lat1)*sin(lng1);\n var z1 = R1*sin(lat1);\n\n var R2 = radius(lat2);\n var x2 = R2*cos(lat2)*cos(lng2);\n var y2 = R2*cos(lat2)*sin(lng2);\n var z2 = R2*sin(lat2);\n\n return sqr(sq(x1-x2)+sq(y1-y2)+sq(z1-z2));\n}\n</code></pre>\n"
},
{
"answer_id": 50866722,
"author": "Ryan",
"author_id": 3355222,
"author_profile": "https://Stackoverflow.com/users/3355222",
"pm_score": 1,
"selected": false,
"text": "<p>FSharp version, using miles: </p>\n\n<pre><code>let radialDistanceHaversine location1 location2 : float = \n let degreeToRadian degrees = degrees * System.Math.PI / 180.0\n let earthRadius = 3959.0\n let deltaLat = location2.Latitude - location1.Latitude |> degreeToRadian\n let deltaLong = location2.Longitude - location1.Longitude |> degreeToRadian\n let a =\n (deltaLat / 2.0 |> sin) ** 2.0\n + (location1.Latitude |> degreeToRadian |> cos)\n * (location2.Latitude |> degreeToRadian |> cos)\n * (deltaLong / 2.0 |> sin) ** 2.0\n atan2 (a |> sqrt) (1.0 - a |> sqrt)\n * 2.0\n * earthRadius\n</code></pre>\n"
},
{
"answer_id": 52718561,
"author": "Kiran Maniya",
"author_id": 8203357,
"author_profile": "https://Stackoverflow.com/users/8203357",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the SQL Implementation to calculate the distance in km,</p>\n\n<pre><code>SELECT UserId, ( 3959 * acos( cos( radians( your latitude here ) ) * cos( radians(latitude) ) * \ncos( radians(longitude) - radians( your longitude here ) ) + sin( radians( your latitude here ) ) * \nsin( radians(latitude) ) ) ) AS distance FROM user HAVING\ndistance < 5 ORDER BY distance LIMIT 0 , 5;\n</code></pre>\n\n<p>For further details in the implementation by programming langugage, you can just go through the php script given <a href=\"https://www.geodatasource.com/developers/php\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 54448795,
"author": "ak-j",
"author_id": 5925898,
"author_profile": "https://Stackoverflow.com/users/5925898",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Java implementation in according <a href=\"https://en.wikipedia.org/wiki/Haversine_formula\" rel=\"nofollow noreferrer\">Haversine formula</a></p>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>double calculateDistance(double latPoint1, double lngPoint1, \n double latPoint2, double lngPoint2) {\n if(latPoint1 == latPoint2 && lngPoint1 == lngPoint2) {\n return 0d;\n }\n\n final double EARTH_RADIUS = 6371.0; //km value;\n\n //converting to radians\n latPoint1 = Math.toRadians(latPoint1);\n lngPoint1 = Math.toRadians(lngPoint1);\n latPoint2 = Math.toRadians(latPoint2);\n lngPoint2 = Math.toRadians(lngPoint2);\n\n double distance = Math.pow(Math.sin((latPoint2 - latPoint1) / 2.0), 2) \n + Math.cos(latPoint1) * Math.cos(latPoint2)\n * Math.pow(Math.sin((lngPoint2 - lngPoint1) / 2.0), 2);\n distance = 2.0 * EARTH_RADIUS * Math.asin(Math.sqrt(distance));\n\n return distance; //km value\n}\n</code></pre>\n"
},
{
"answer_id": 55455344,
"author": "Ramprasath Selvam",
"author_id": 8079610,
"author_profile": "https://Stackoverflow.com/users/8079610",
"pm_score": 2,
"selected": false,
"text": "<p>One of the main challenges to calculating distances - especially large ones - is accounting for the curvature of the Earth. If only the Earth were flat, calculating the distance between two points would be as simple as for that of a straight line! The Haversine formula includes a constant (it's the R variable below) that represents the radius of the Earth. Depending on whether you are measuring in miles or kilometers, it would equal 3956 mi or 6367 km respectively.<br><br>\nThe basic formula is:<br><br></p>\n<blockquote>\n<pre><code>dlon = lon2 - lon1\ndlat = lat2 - lat1\na = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2\nc = 2 * atan2( sqrt(a), sqrt(1-a) )\ndistance = R * c (where R is the radius of the Earth)\n \nR = 6367 km OR 3956 mi\n</code></pre>\n</blockquote>\n<pre><code> lat1, lon1: The Latitude and Longitude of point 1 (in decimal degrees)\n lat2, lon2: The Latitude and Longitude of point 2 (in decimal degrees)\n unit: The unit of measurement in which to calculate the results where:\n 'M' is statute miles (default)\n 'K' is kilometers\n 'N' is nautical miles\n</code></pre>\n<p>Sample</p>\n<pre><code>function distance(lat1, lon1, lat2, lon2, unit) {\n try {\n var radlat1 = Math.PI * lat1 / 180\n var radlat2 = Math.PI * lat2 / 180\n var theta = lon1 - lon2\n var radtheta = Math.PI * theta / 180\n var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);\n dist = Math.acos(dist)\n dist = dist * 180 / Math.PI\n dist = dist * 60 * 1.1515\n if (unit == "K") {\n dist = dist * 1.609344\n }\n if (unit == "N") {\n dist = dist * 0.8684\n }\n return dist\n } catch (err) {\n console.log(err);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59646977,
"author": "Oleg Khalidov",
"author_id": 2450439,
"author_profile": "https://Stackoverflow.com/users/2450439",
"pm_score": 1,
"selected": false,
"text": "<p>Dart lang:</p>\n\n<pre class=\"lang-dart prettyprint-override\"><code>import 'dart:math' show cos, sqrt, asin;\n\ndouble calculateDistance(LatLng l1, LatLng l2) {\n const p = 0.017453292519943295;\n final a = 0.5 -\n cos((l2.latitude - l1.latitude) * p) / 2 +\n cos(l1.latitude * p) *\n cos(l2.latitude * p) *\n (1 - cos((l2.longitude - l1.longitude) * p)) /\n 2;\n return 12742 * asin(sqrt(a));\n}\n</code></pre>\n"
},
{
"answer_id": 59656546,
"author": "Oleg Medvedyev",
"author_id": 3044692,
"author_profile": "https://Stackoverflow.com/users/3044692",
"pm_score": 2,
"selected": false,
"text": "<p>As this is the most popular discussion of the topic I'll add my experience from late 2019-early 2020 here. To add to the existing answers - my focus was to find an accurate AND fast (i.e. vectorized) solution.</p>\n<p>Let's start with what is mostly used by answers here - the Haversine approach. It is trivial to vectorize, see example in python below:</p>\n<pre><code>def haversine(lat1, lon1, lat2, lon2):\n """\n Calculate the great circle distance between two points\n on the earth (specified in decimal degrees)\n\n All args must be of equal length.\n Distances are in meters.\n \n Ref:\n https://stackoverflow.com/questions/29545704/fast-haversine-approximation-python-pandas\n https://ipython.readthedocs.io/en/stable/interactive/magics.html\n """\n Radius = 6.371e6\n lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])\n\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2\n\n c = 2 * np.arcsin(np.sqrt(a))\n s12 = Radius * c\n \n # initial azimuth in degrees\n y = np.sin(lon2-lon1) * np.cos(lat2)\n x = np.cos(lat1)*np.sin(lat2) - np.sin(lat1)*np.cos(lat2)*np.cos(dlon)\n azi1 = np.arctan2(y, x)*180./math.pi\n\n return {'s12':s12, 'azi1': azi1}\n</code></pre>\n<p>Accuracy-wise, it is least accurate. Wikipedia states 0.5% of relative deviation on average without any sources. My experiments show less of a deviation. Below is the comparison ran on 100,000 random points vs my library, which should be accurate to millimeter levels:</p>\n<pre><code>np.random.seed(42)\nlats1 = np.random.uniform(-90,90,100000)\nlons1 = np.random.uniform(-180,180,100000)\nlats2 = np.random.uniform(-90,90,100000)\nlons2 = np.random.uniform(-180,180,100000)\nr1 = inverse(lats1, lons1, lats2, lons2)\nr2 = haversine(lats1, lons1, lats2, lons2)\nprint("Max absolute error: {:4.2f}m".format(np.max(r1['s12']-r2['s12'])))\nprint("Mean absolute error: {:4.2f}m".format(np.mean(r1['s12']-r2['s12'])))\nprint("Max relative error: {:4.2f}%".format(np.max((r2['s12']/r1['s12']-1)*100)))\nprint("Mean relative error: {:4.2f}%".format(np.mean((r2['s12']/r1['s12']-1)*100)))\n</code></pre>\n<p>Output:</p>\n<pre><code>Max absolute error: 26671.47m\nMean absolute error: -2499.84m\nMax relative error: 0.55%\nMean relative error: -0.02%\n</code></pre>\n<p>So on average 2.5km deviation on 100,000 random pairs of coordinates, which may be good for majority of cases.</p>\n<p>Next option is Vincenty's formulae which is accurate up to millimeters, depending on convergence criteria and can be vectorized as well. It does have the issue with convergence near antipodal points. You can make it converge at those points by relaxing convergence criteria, but accuracy drops to 0.25% and more. Outside of antipodal points Vincenty will provide results close to Geographiclib within relative error of less than 1.e-6 on average.</p>\n<p>Geographiclib, mentioned here, is really the current golden standard. It has several implementations and fairly fast, especially if you are using C++ version.</p>\n<p>Now, if you are planning to use Python for anything above 10k points I'd suggest to consider my vectorized implementation. I created a <a href=\"https://pypi.org/project/geovectorslib/\" rel=\"nofollow noreferrer\">geovectorslib</a> library with vectorized Vincenty routine for my own needs, which uses Geographiclib as fallback for near antipodal points. Below is the comparison vs Geographiclib for 100k points. As you can see it provides up to <strong>20x improvement for inverse and 100x for direct</strong> methods for 100k points and the gap will grow with number of points. Accuracy-wise it will be within 1.e-5 rtol of Georgraphiclib.</p>\n<pre><code>Direct method for 100,000 points\n94.9 ms ± 25 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n9.79 s ± 1.4 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nInverse method for 100,000 points\n1.5 s ± 504 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n24.2 s ± 3.91 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n"
},
{
"answer_id": 59682648,
"author": "WapShivam",
"author_id": 9629819,
"author_profile": "https://Stackoverflow.com/users/9629819",
"pm_score": 1,
"selected": false,
"text": "<p>You can calculate it by using Haversine formula which is:</p>\n\n<pre><code>a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)\nc = 2 ⋅ atan2( √a, √(1−a) )\nd = R ⋅ c\n</code></pre>\n\n<p>An example to calculate distance between two points is given below</p>\n\n<p>Suppose i have to calculate distance between New Delhi to London, so how can i use this formula :</p>\n\n<pre><code>New delhi co-ordinates= 28.7041° N, 77.1025° E\nLondon co-ordinates= 51.5074° N, 0.1278° W\n\nvar R = 6371e3; // metres\nvar φ1 = 28.7041.toRadians();\nvar φ2 = 51.5074.toRadians();\nvar Δφ = (51.5074-28.7041).toRadians();\nvar Δλ = (0.1278-77.1025).toRadians();\n\nvar a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +\n Math.cos(φ1) * Math.cos(φ2) *\n Math.sin(Δλ/2) * Math.sin(Δλ/2);\nvar c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\nvar d = R * c; // metres\nd = d/1000; // km\n</code></pre>\n"
},
{
"answer_id": 60159168,
"author": "Korayem",
"author_id": 80434,
"author_profile": "https://Stackoverflow.com/users/80434",
"pm_score": 2,
"selected": false,
"text": "<p>For those looking for an Excel formula based on WGS-84 & GRS-80 standards:</p>\n\n<pre><code>=ACOS(COS(RADIANS(90-Lat1))*COS(RADIANS(90-Lat2))+SIN(RADIANS(90-Lat1))*SIN(RADIANS(90-Lat2))*COS(RADIANS(Long1-Long2)))*6371\n</code></pre>\n\n<p><a href=\"https://bluemm.blogspot.com/2007/01/excel-formula-to-calculate-distance.html\" rel=\"nofollow noreferrer\">Source</a></p>\n"
},
{
"answer_id": 62139010,
"author": "Kristian K",
"author_id": 13505403,
"author_profile": "https://Stackoverflow.com/users/13505403",
"pm_score": 1,
"selected": false,
"text": "<p>The functions needed for an accurate calculation of distance between lat-long points are complex, and the pitfalls are many. I would not recomend haversine or other spherical solutions due to the big inaccuracies (the earth is not a perfect sphere). The <a href=\"https://en.wikipedia.org/wiki/Vincenty%27s_formulae\" rel=\"nofollow noreferrer\">vincenty formula</a> is better, but will in some cases throw errors, even when coded correctly.</p>\n\n<p>Instead of coding the functions yourself I suggest using <a href=\"https://geopy.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">geopy</a> which have implemented the very accurate <a href=\"https://geographiclib.sourceforge.io/html/python/\" rel=\"nofollow noreferrer\">geographiclib</a> for distance calculations (<a href=\"https://link.springer.com/content/pdf/10.1007/s00190-012-0578-z.pdf\" rel=\"nofollow noreferrer\">paper from author</a>). </p>\n\n<pre><code>#pip install geopy\nfrom geopy.distance import geodesic\nNY = [40.71278,-74.00594]\nBeijing = [39.90421,116.40739]\nprint(\"WGS84: \",geodesic(NY, Beijing).km) #WGS84 is Standard\nprint(\"Intl24: \",geodesic(NY, Beijing, ellipsoid='Intl 1924').km) #geopy includes different ellipsoids\nprint(\"Custom ellipsoid: \",geodesic(NY, Beijing, ellipsoid=(6377., 6356., 1 / 297.)).km) #custom ellipsoid\n\n#supported ellipsoids:\n#model major (km) minor (km) flattening\n#'WGS-84': (6378.137, 6356.7523142, 1 / 298.257223563)\n#'GRS-80': (6378.137, 6356.7523141, 1 / 298.257222101)\n#'Airy (1830)': (6377.563396, 6356.256909, 1 / 299.3249646)\n#'Intl 1924': (6378.388, 6356.911946, 1 / 297.0)\n#'Clarke (1880)': (6378.249145, 6356.51486955, 1 / 293.465)\n#'GRS-67': (6378.1600, 6356.774719, 1 / 298.25)\n</code></pre>\n\n<p>The only drawback with this library is that it doesn't support vectorized calculations.\nFor vectorized calculations you can use the new <a href=\"https://pypi.org/project/geovectorslib/\" rel=\"nofollow noreferrer\">geovectorslib</a>.</p>\n\n<pre><code>#pip install geovectorslib\nfrom geovectorslib import inverse\nprint(inverse(lats1,lons1,lats2,lons2)['s12'])\n</code></pre>\n\n<p>lats and lons are numpy arrays. Geovectorslib is very accurate and extremly fast! I haven't found a solution for changing ellipsoids though. The WGS84 ellipsoid is used as standard, which is the best choice for most uses.</p>\n"
},
{
"answer_id": 64214020,
"author": "sourav karwa",
"author_id": 5022656,
"author_profile": "https://Stackoverflow.com/users/5022656",
"pm_score": 2,
"selected": false,
"text": "<p>I made a custom function in R to calculate haversine distance(km) between two spatial points using functions available in R base package.</p>\n<pre><code>custom_hav_dist <- function(lat1, lon1, lat2, lon2) {\nR <- 6371\nRadian_factor <- 0.0174533\nlat_1 <- (90-lat1)*Radian_factor\nlat_2 <- (90-lat2)*Radian_factor\ndiff_long <-(lon1-lon2)*Radian_factor\n\ndistance_in_km <- 6371*acos((cos(lat_1)*cos(lat_2))+ \n (sin(lat_1)*sin(lat_2)*cos(diff_long)))\nrm(lat1, lon1, lat2, lon2)\nreturn(distance_in_km)\n}\n</code></pre>\n<p>Sample output</p>\n<pre><code>custom_hav_dist(50.31,19.08,54.14,19.39)\n[1] 426.3987\n</code></pre>\n<p>PS: To calculate distances in miles, substitute R in function (6371) with 3958.756 (and for nautical miles, use 3440.065).</p>\n"
},
{
"answer_id": 64696900,
"author": "Irfan wani",
"author_id": 13789135,
"author_profile": "https://Stackoverflow.com/users/13789135",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using python;\npip install geopy</p>\n<pre><code>from geopy.distance import geodesic\n\n\norigin = (30.172705, 31.526725) # (latitude, longitude) don't confuse\ndestination = (30.288281, 31.732326)\n\nprint(geodesic(origin, destination).meters) # 23576.805481751613\nprint(geodesic(origin, destination).kilometers) # 23.576805481751613\nprint(geodesic(origin, destination).miles) # 14.64994773134371\n</code></pre>\n"
},
{
"answer_id": 65109214,
"author": "Renato Probst",
"author_id": 1713345,
"author_profile": "https://Stackoverflow.com/users/1713345",
"pm_score": 2,
"selected": false,
"text": "<p>If you want the driving distance/route (posting it here because this is the first result for the distance between two points on google but for most people the driving distance is more useful), you can use <a href=\"https://developers.google.com/maps/documentation/javascript/distancematrix\" rel=\"nofollow noreferrer\">Google Maps Distance Matrix Service</a>:</p>\n<pre><code>getDrivingDistanceBetweenTwoLatLong(origin, destination) {\n\n return new Observable(subscriber => {\n let service = new google.maps.DistanceMatrixService();\n service.getDistanceMatrix(\n {\n origins: [new google.maps.LatLng(origin.lat, origin.long)],\n destinations: [new google.maps.LatLng(destination.lat, destination.long)],\n travelMode: 'DRIVING'\n }, (response, status) => {\n if (status !== google.maps.DistanceMatrixStatus.OK) {\n console.log('Error:', status);\n subscriber.error({error: status, status: status});\n } else {\n console.log(response);\n try {\n let valueInMeters = response.rows[0].elements[0].distance.value;\n let valueInKms = valueInMeters / 1000;\n subscriber.next(valueInKms);\n subscriber.complete();\n }\n catch(error) {\n subscriber.error({error: error, status: status});\n }\n }\n });\n});\n}\n</code></pre>\n"
},
{
"answer_id": 66994120,
"author": "Anurag",
"author_id": 10665583,
"author_profile": "https://Stackoverflow.com/users/10665583",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function distance($lat1, $lon1, $lat2, $lon2) { \n $pi80 = M_PI / 180; \n $lat1 *= $pi80; $lon1 *= $pi80; $lat2 *= $pi80; $lon2 *= $pi80; \n $dlat = $lat2 - $lat1; \n $dlon = $lon2 - $lon1; \n $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2); \n $km = 6372.797 * 2 * atan2(sqrt($a), sqrt(1 - $a)); \n return $km; \n}\n</code></pre>\n"
},
{
"answer_id": 67357990,
"author": "Aaron Lelevier",
"author_id": 1913888,
"author_profile": "https://Stackoverflow.com/users/1913888",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the Erlang implementation</p>\n<pre class=\"lang-erlang prettyprint-override\"><code>lat_lng({Lat1, Lon1}=_Point1, {Lat2, Lon2}=_Point2) ->\n P = math:pi() / 180,\n R = 6371, % Radius of Earth in KM\n A = 0.5 - math:cos((Lat2 - Lat1) * P) / 2 +\n math:cos(Lat1 * P) * math:cos(Lat2 * P) * (1 - math:cos((Lon2 - Lon1) * P))/2,\n R * 2 * math:asin(math:sqrt(A)).\n</code></pre>\n"
},
{
"answer_id": 68985288,
"author": "Arthur Ronconi",
"author_id": 2272598,
"author_profile": "https://Stackoverflow.com/users/2272598",
"pm_score": 2,
"selected": false,
"text": "<p>You could use a module like geolib too:</p>\n<p>How to install:</p>\n<pre><code>$ npm install geolib\n</code></pre>\n<p>How to use:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { getDistance } from 'geolib'\n\nconst distance = getDistance(\n { latitude: 51.5103, longitude: 7.49347 },\n { latitude: "51° 31' N", longitude: "7° 28' E" }\n)\n\nconsole.log(distance)\n</code></pre>\n<p>Documentation:\n<a href=\"https://www.npmjs.com/package/geolib\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/geolib</a></p>\n"
},
{
"answer_id": 70532052,
"author": "Remis Haroon - رامز",
"author_id": 1843011,
"author_profile": "https://Stackoverflow.com/users/1843011",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a Scala implementation:</p>\n<pre><code> def calculateHaversineDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double = {\n val long2 = lon2 * math.Pi / 180\n val lat2 = lat2 * math.Pi / 180\n val long1 = lon1 * math.Pi / 180\n val lat1 = lat1 * math.Pi / 180\n\n val dlon = long2 - long1\n val dlat = lat2 - lat1\n val a = math.pow(math.sin(dlat / 2), 2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(dlon / 2), 2)\n val c = 2 * math.atan2(Math.sqrt(a), math.sqrt(1 - a))\n val haversineDistance = 3961 * c // 3961 = radius of earth in miles\n haversineDistance\n }\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1456/"
] | How do I calculate the distance between two points specified by latitude and longitude?
For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available. | This [link](http://www.movable-type.co.uk/scripts/latlong.html) might be helpful to you, as it details the use of the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to calculate the distance.
Excerpt:
>
> This script [in Javascript] calculates great-circle distances between the two points –
> that is, the shortest distance over the earth’s surface – using the
> ‘Haversine’ formula.
>
>
>
```js
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
``` |
27,972 | <p>JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site? </p>
<p><em>Edit:</em> Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option?</p>
<p><em>Edit 2:</em> Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, <strong>what is the point of HttpOnly</strong>?</p>
<p><em>Edit 3:</em> Here is a quote from Wikipedia:</p>
<blockquote>
<p>When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The <code>HttpOnly</code> flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33].</p>
</blockquote>
<p>I understand that <code>document.cookie</code> is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only? </p>
<p>In your example, I cannot write to your <code>document.cookie</code>, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.</p>
<pre><code><script type="text/javascript">
var req = null;
try { req = new XMLHttpRequest(); } catch(e) {}
if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
req.open('GET', 'http://stackoverflow.com/', false);
req.send(null);
alert(req.getAllResponseHeaders());
</script>
</code></pre>
<p><em>Edit 4:</em> Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...</p>
<p><em>Final Edit:</em> Ahh, apparently both sites are wrong, this is actually a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=380418" rel="noreferrer">bug in FireFox</a>. IE6 & 7 are actually the only browsers that currently fully support HttpOnly.</p>
<p>To reiterate everything I've learned:</p>
<ul>
<li>HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers)</li>
<li>HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7.</li>
<li>XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.</li>
</ul>
<p><em>edit: This information is likely no longer up to date.</em></p>
| [
{
"answer_id": 28000,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "<p>Not necessarily, it depends what you want to do. Could you elaborate a bit? AJAX doesn't need access to cookies to work, it can make requests on its own to extract information, the page request that the AJAX call makes could access the cookie data & pass that back to the calling script without Javascript having to directly access the cookies</p>\n"
},
{
"answer_id": 28010,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 0,
"selected": false,
"text": "<p>No, the page that the AJAX call requests has access to cookies too & that's what checks whether you're logged in.</p>\n\n<p>You can do other authentication with the Javascript, but I wouldn't trust it, I always prefer putting any sort of authentication checking in the back-end.</p>\n"
},
{
"answer_id": 28021,
"author": "pkchukiss",
"author_id": 2504504,
"author_profile": "https://Stackoverflow.com/users/2504504",
"pm_score": 1,
"selected": false,
"text": "<p>Cookies are automatically handled by the browser when you make an AJAX call, so there's no need for your Javascript to mess around with cookies.</p>\n"
},
{
"answer_id": 28031,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p>Therefore I am assuming JavaScript needs access to your cookies.</p>\n </blockquote>\n</blockquote>\n\n<p>All HTTP requests from your browser transmit your cookie information for the site in question. JavaScript can both set and read cookies. Cookies are not by definition required for Ajax applications, but they are required for most web applications to maintain user state.</p>\n\n<p>The formal answer to your question as phrased - \"Does JavaScript need access to cookies if AJAX is used?\" - is therefore \"no\". Think of enhanced search fields that use Ajax requests to provide auto-suggest options, for example. There is no need of cookie information in that case.</p>\n"
},
{
"answer_id": 28032,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "<p>As clarification - from the server's perspective, the page that is requested by an AJAX request is essentially no different to a standard HTTP get request done by the user clicking on a link. All the normal request properties: user-agent, ip, session, cookies, etc. are passed to the server.</p>\n"
},
{
"answer_id": 29092,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 6,
"selected": false,
"text": "<p>Yes, HTTP-Only cookies would be fine for this functionality. They will still be provided with the XmlHttpRequest's request to the server.</p>\n\n<p>In the case of Stack Overflow, the cookies are automatically provided as part of the XmlHttpRequest request. I don't know the implementation details of the Stack Overflow authentication provider, but that cookie data is probably automatically used to verify your identity at a lower level than the \"vote\" controller method.</p>\n\n<p>More generally, cookies are <strong>not</strong> required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required.</p>\n\n<p>However, if you want to provide security for AJAX enabled functionality, then the same rules apply as with traditional sites. You need some method for identifying the user behind each request, and cookies are almost always the means to that end.</p>\n\n<blockquote>\n <p>In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.</p>\n</blockquote>\n\n<p>XmlHttpRequest won't make cross-domain requests (for exactly the sorts of reasons you're touching on).</p>\n\n<p>You could normally inject script to send the cookie to your domain using iframe remoting or JSONP, but then HTTP-Only protects the cookie again since it's inaccessible.</p>\n\n<p>Unless you had compromised StackOverflow.com on the server side, you wouldn't be able to steal my cookie.</p>\n\n<blockquote>\n <p>Edit 2: Question 2. If the purpose of Http-Only is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of Http-Only?</p>\n</blockquote>\n\n<p>Consider this scenario:</p>\n\n<ul>\n<li>I find an avenue to inject JavaScript code into the page.</li>\n<li>Jeff loads the page and my malicious JavaScript modifies his cookie to match mine.</li>\n<li>Jeff submits a stellar answer to your question.</li>\n<li>Because he submits it with my cookie data instead of his, the answer will become mine.</li>\n<li>You vote up \"my\" stellar answer.</li>\n<li>My real account gets the point.</li>\n</ul>\n\n<p>With HTTP-Only cookies, the second step would be impossible, thereby defeating my XSS attempt.</p>\n\n<blockquote>\n <p>Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...</p>\n</blockquote>\n\n<p>That's correct. You can still session hijack that way. It does significantly thin the herd of people who can successfully execute even that XSS hack against you though.</p>\n\n<p>However, if you go back to my example scenario, you can see where HTTP-Only <em>does</em> successfully cut off the XSS attacks which rely on modifying the client's cookies (not uncommon).</p>\n\n<p>It boils down to the fact that a) no single improvement will solve <em>all</em> vulnerabilities and b) no system will <em>ever</em> be completely secure. HTTP-Only <strong>is</strong> a useful tool in shoring up against XSS.</p>\n\n<p>Similarly, even though the cross domain restriction on XmlHttpRequest isn't 100% successful in preventing all XSS exploits, you'd still never dream of removing the restriction.</p>\n"
},
{
"answer_id": 590311,
"author": "thomasrutter",
"author_id": 53212,
"author_profile": "https://Stackoverflow.com/users/53212",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, they are a viable option for an Ajax based site. Authentication cookies aren't for manipulation by scripts, but are simply included by the browser on all HTTP requests made to the server.</p>\n\n<p>Scripts don't need to worry about what the session cookie says - as long as you are authenticated, then any requests to the server initiated by either a user or the script will include the appropriate cookies. The fact that the scripts cannot themselves know the content of the cookies doesn't matter.</p>\n\n<p>For any cookies that are used for purposes other than authentication, these can be set without the HTTP only flag, if you want script to be able to modify or read these. You can pick and choose which cookies should be HTTP only, so for example anything non-sensitive like UI preferences (sort order, collapse left hand pane or not) can be shared in cookies with the scripts.</p>\n\n<p>I really like the HTTP only cookies - it's one of those proprietary browser extensions that was a really neat idea.</p>\n"
},
{
"answer_id": 673871,
"author": "Jay",
"author_id": 79737,
"author_profile": "https://Stackoverflow.com/users/79737",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, cookies are very useful for Ajax.</p>\n\n<p>Putting the authentication in the request URL is bad practice. There was a news item last week about getting the authentication tokens in the URL's from the google cache.</p>\n\n<p>No, there is no way to prevent attacks. Older browsers still allow trivial access to cookies via javascript. You can bypass http only, etc. Whatever you come up with can be gotten around given enough effort. The trick is to make it too much effort to be worthwhile.</p>\n\n<p>If you want to make your site more secure (there is no perfect security) you could use an authentication cookie that expires. Then, if the cookie is stolen, the attacker must use it before it expires. If they don't then you have a good indication there's suspicious activity on that account. The shorter the time window the better for security but the more load it puts on your server generating and maintaining keys.</p>\n"
},
{
"answer_id": 975881,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 2,
"selected": false,
"text": "<p>There's a bit more to this.</p>\n\n<p>Ajax doesn't strictly require cookies, but they can be useful as other posters have mentioned. Marking a cookie HTTPOnly to hide it from scripts only partially works, because not all browsers support it, but also because there are common workarounds.</p>\n\n<p>It's odd that the XMLHTTPresponse headers are giving the cookie, technically the server doesn't have to return the cookie with the response. Once it's set on the client, it stays set until it expires. Though there are schemes in which the cookie is changed with every request to prevent re-use. So you may be able to avoid that workaround by changing the server to not provide the cookie on the XMLHTTP responses.</p>\n\n<p>In general though, I think HTTPOnly should be used with some caution. There are cross site scripting attacks where an attacker arranges for a user to submit an ajax-like request originating from another site, using simple post forms, without the use of XMLHTTP, and your browser's still-active cookie would authenticate the request.</p>\n\n<p>If you want to be sure that an AJAX request is authenticated, the request itself AND the HTTP headers need to contain the cookie. Eg through the use of scripts or unique hidden inputs. HTTPOnly would hinder that.</p>\n\n<p>Usually the interesting reason to want HTTPOnly is to prevent third-party content included on your webpage from stealing cookies. But there are many interesting reasons to be very cautious about including third-party content, and filter it aggressively.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site?
*Edit:* Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option?
*Edit 2:* Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, **what is the point of HttpOnly**?
*Edit 3:* Here is a quote from Wikipedia:
>
> When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The `HttpOnly` flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33].
>
>
>
I understand that `document.cookie` is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only?
In your example, I cannot write to your `document.cookie`, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.
```
<script type="text/javascript">
var req = null;
try { req = new XMLHttpRequest(); } catch(e) {}
if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
req.open('GET', 'http://stackoverflow.com/', false);
req.send(null);
alert(req.getAllResponseHeaders());
</script>
```
*Edit 4:* Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...
*Final Edit:* Ahh, apparently both sites are wrong, this is actually a [bug in FireFox](https://bugzilla.mozilla.org/show_bug.cgi?id=380418). IE6 & 7 are actually the only browsers that currently fully support HttpOnly.
To reiterate everything I've learned:
* HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers)
* HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7.
* XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.
*edit: This information is likely no longer up to date.* | Yes, HTTP-Only cookies would be fine for this functionality. They will still be provided with the XmlHttpRequest's request to the server.
In the case of Stack Overflow, the cookies are automatically provided as part of the XmlHttpRequest request. I don't know the implementation details of the Stack Overflow authentication provider, but that cookie data is probably automatically used to verify your identity at a lower level than the "vote" controller method.
More generally, cookies are **not** required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required.
However, if you want to provide security for AJAX enabled functionality, then the same rules apply as with traditional sites. You need some method for identifying the user behind each request, and cookies are almost always the means to that end.
>
> In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.
>
>
>
XmlHttpRequest won't make cross-domain requests (for exactly the sorts of reasons you're touching on).
You could normally inject script to send the cookie to your domain using iframe remoting or JSONP, but then HTTP-Only protects the cookie again since it's inaccessible.
Unless you had compromised StackOverflow.com on the server side, you wouldn't be able to steal my cookie.
>
> Edit 2: Question 2. If the purpose of Http-Only is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of Http-Only?
>
>
>
Consider this scenario:
* I find an avenue to inject JavaScript code into the page.
* Jeff loads the page and my malicious JavaScript modifies his cookie to match mine.
* Jeff submits a stellar answer to your question.
* Because he submits it with my cookie data instead of his, the answer will become mine.
* You vote up "my" stellar answer.
* My real account gets the point.
With HTTP-Only cookies, the second step would be impossible, thereby defeating my XSS attempt.
>
> Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...
>
>
>
That's correct. You can still session hijack that way. It does significantly thin the herd of people who can successfully execute even that XSS hack against you though.
However, if you go back to my example scenario, you can see where HTTP-Only *does* successfully cut off the XSS attacks which rely on modifying the client's cookies (not uncommon).
It boils down to the fact that a) no single improvement will solve *all* vulnerabilities and b) no system will *ever* be completely secure. HTTP-Only **is** a useful tool in shoring up against XSS.
Similarly, even though the cross domain restriction on XmlHttpRequest isn't 100% successful in preventing all XSS exploits, you'd still never dream of removing the restriction. |
27,983 | <p>I have a table of tags and want to get the highest count tags from the list.</p>
<p>Sample data looks like this</p>
<pre><code>id (1) tag ('night')
id (2) tag ('awesome')
id (3) tag ('night')
</code></pre>
<p>using</p>
<pre><code>SELECT COUNT(*), `Tag` from `images-tags`
GROUP BY `Tag`
</code></pre>
<p>gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so.</p>
<p>I tried this...</p>
<pre><code>SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
</code></pre>
<p>and I keep getting an "Invalid use of group function - ErrNr 1111"</p>
<p>What am I doing wrong?</p>
<p>I'm using MySQL 4.1.25-Debian</p>
| [
{
"answer_id": 27992,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 6,
"selected": false,
"text": "<p>MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.</p>\n\n<p>You can get around this limit with the deprecated syntax:</p>\n\n<pre><code>SELECT COUNT(id), `Tag` from `images-tags`\nGROUP BY `Tag`\nORDER BY 1 DESC\nLIMIT 20\n</code></pre>\n\n<p>1, since it's the first column you want to group on.</p>\n"
},
{
"answer_id": 27994,
"author": "jerhinesmith",
"author_id": 1108,
"author_profile": "https://Stackoverflow.com/users/1108",
"pm_score": 4,
"selected": false,
"text": "<p>I don't know about MySQL, but in MS SQL, you can use the column index in the <code>order by</code> clause. I've done this before when doing counts with <code>group by</code>s as it tends to be easier to work with.</p>\n\n<p>So</p>\n\n<pre><code>SELECT COUNT(id), `Tag` from `images-tags`\nGROUP BY `Tag`\nORDER BY COUNT(id) DESC\nLIMIT 20\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>SELECT COUNT(id), `Tag` from `images-tags`\nGROUP BY `Tag`\nORDER 1 DESC\nLIMIT 20\n</code></pre>\n"
},
{
"answer_id": 28686,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 3,
"selected": false,
"text": "<p>In Oracle, something like this works nicely to separate your counting and ordering a little better. I'm not sure if it will work in MySql 4.</p>\n\n<pre><code>select 'Tag', counts.cnt\nfrom\n (\n select count(*) as cnt, 'Tag'\n from 'images-tags'\n group by 'tag'\n ) counts\norder by counts.cnt desc\n</code></pre>\n"
},
{
"answer_id": 30503,
"author": "Scott Noyes",
"author_id": 3254,
"author_profile": "https://Stackoverflow.com/users/3254",
"pm_score": 9,
"selected": true,
"text": "<p>In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:</p>\n\n<pre><code>SELECT COUNT(id) AS theCount, `Tag` from `images-tags`\nGROUP BY `Tag`\nORDER BY theCount DESC\nLIMIT 20\n</code></pre>\n"
},
{
"answer_id": 31380216,
"author": "Ashutosh Gupta",
"author_id": 4527338,
"author_profile": "https://Stackoverflow.com/users/4527338",
"pm_score": -1,
"selected": false,
"text": "<p>Try this query</p>\n\n<pre><code> SELECT data_collector_id , count (data_collector_id ) as frequency \n from rent_flats \n where is_contact_person_landlord = 'True' \n GROUP BY data_collector_id \n ORDER BY count(data_collector_id) DESC\n</code></pre>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/27983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477/"
] | I have a table of tags and want to get the highest count tags from the list.
Sample data looks like this
```
id (1) tag ('night')
id (2) tag ('awesome')
id (3) tag ('night')
```
using
```
SELECT COUNT(*), `Tag` from `images-tags`
GROUP BY `Tag`
```
gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so.
I tried this...
```
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
```
and I keep getting an "Invalid use of group function - ErrNr 1111"
What am I doing wrong?
I'm using MySQL 4.1.25-Debian | In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:
```
SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20
``` |
28,002 | <p>I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.</p>
<pre><code>MyClass *m = (MyClass *)ptr;
</code></pre>
<p>all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?</p>
<pre><code>MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast<MyClass *>(ptr);
MyClass *m = dynamic_cast<MyClass *>(ptr);
</code></pre>
| [
{
"answer_id": 28020,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 4,
"selected": false,
"text": "<p><code>dynamic_cast</code> has runtime type checking and only works with references and pointers, whereas <code>static_cast</code> does not offer runtime type checking. For complete information, see the MSDN article <em><a href=\"http://msdn.microsoft.com/en-us/library/c36yw7x9(VS.80).aspx\" rel=\"noreferrer\">static_cast Operator</a></em>.</p>\n"
},
{
"answer_id": 28026,
"author": "TJ Seabrooks",
"author_id": 3022,
"author_profile": "https://Stackoverflow.com/users/3022",
"pm_score": 7,
"selected": false,
"text": "<p>You should look at the article <em><a href=\"http://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Statements/Variables/Type_Casting\" rel=\"noreferrer\">C++ Programming/Type Casting</a></em>.</p>\n\n<p>It contains a good description of all of the different cast types. The following taken from the above link:</p>\n\n<blockquote>\n <p>const_cast</p>\n \n <p>const_cast(expression) The const_cast<>() is used to add/remove\n const(ness) (or volatile-ness) of a variable.</p>\n \n <p>static_cast</p>\n \n <p>static_cast(expression) The static_cast<>() is used to cast between\n the integer types. 'e.g.' char->long, int->short etc.</p>\n \n <p>Static cast is also used to cast pointers to related types, for\n example casting void* to the appropriate type.</p>\n \n <p>dynamic_cast</p>\n \n <p>Dynamic cast is used to convert pointers and references at run-time,\n generally for the purpose of casting a pointer or reference up or down\n an inheritance chain (inheritance hierarchy).</p>\n \n <p>dynamic_cast(expression)</p>\n \n <p>The target type must be a pointer or reference type, and the\n expression must evaluate to a pointer or reference. Dynamic cast works\n only when the type of object to which the expression refers is\n compatible with the target type and the base class has at least one\n virtual member function. If not, and the type of expression being cast\n is a pointer, NULL is returned, if a dynamic cast on a reference\n fails, a bad_cast exception is thrown. When it doesn't fail, dynamic\n cast returns a pointer or reference of the target type to the object\n to which expression referred.</p>\n \n <p>reinterpret_cast</p>\n \n <p>Reinterpret cast simply casts one type bitwise to another. Any pointer\n or integral type can be casted to any other with reinterpret cast,\n easily allowing for misuse. For instance, with reinterpret cast one\n might, unsafely, cast an integer pointer to a string pointer.</p>\n</blockquote>\n"
},
{
"answer_id": 28052,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 4,
"selected": false,
"text": "<p>C-style casts conflate const_cast, static_cast, and reinterpret_cast.</p>\n\n<p>I wish C++ didn't have C-style casts. C++ casts stand out properly (as they should; casts are normally indicative of doing something bad) and properly distinguish between the different kinds of conversion that casts perform. They also permit similar-looking functions to be written, e.g. boost::lexical_cast, which is quite nice from a consistency perspective.</p>\n"
},
{
"answer_id": 28054,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 5,
"selected": false,
"text": "<p>FYI, I believe Bjarne Stroustrup is quoted as saying that C-style casts are to be avoided and that you should use static_cast or dynamic_cast if at all possible.</p>\n\n<p><a href=\"http://www.stroustrup.com/bs_faq2.html\" rel=\"noreferrer\">Barne Stroustrup's C++ style FAQ</a></p>\n\n<p>Take that advice for what you will. I'm far from being a C++ guru.</p>\n"
},
{
"answer_id": 103914,
"author": "ugasoft",
"author_id": 10120,
"author_profile": "https://Stackoverflow.com/users/10120",
"pm_score": 5,
"selected": false,
"text": "<p>Avoid using C-Style casts.</p>\n\n<p>C-style casts are a mix of const and reinterpret cast, and it's difficult to find-and-replace in your code. A C++ application programmer should avoid C-style cast.</p>\n"
},
{
"answer_id": 1255015,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 12,
"selected": true,
"text": "<h2>static_cast</h2>\n<p><code>static_cast</code> is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. <code>static_cast</code> performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:</p>\n<pre><code>void func(void *data) {\n // Conversion from MyClass* -> void* is implicit\n MyClass *c = static_cast<MyClass*>(data);\n ...\n}\n\nint main() {\n MyClass c;\n start_thread(&func, &c) // func(&c) will be called\n .join();\n}\n</code></pre>\n<p>In this example, you know that you passed a <code>MyClass</code> object, and thus there isn't any need for a runtime check to ensure this.</p>\n<h2>dynamic_cast</h2>\n<p><code>dynamic_cast</code> is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a <code>bad_cast</code> exception is thrown in that case).</p>\n<pre><code>if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {\n ...\n} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {\n ...\n}\n</code></pre>\n<p>You can <strong>not</strong> use <code>dynamic_cast</code> for downcast (casting to a derived class) <strong>if</strong> the argument type is not polymorphic. For example, the following code is not valid, because <code>Base</code> doesn't contain any virtual function:</p>\n<pre><code>struct Base { };\nstruct Derived : Base { };\nint main() {\n Derived d; Base *b = &d;\n dynamic_cast<Derived*>(b); // Invalid\n}\n</code></pre>\n<p>An "up-cast" (cast to the base class) is always valid with both <code>static_cast</code> and <code>dynamic_cast</code>, and also without any cast, as an "up-cast" is an implicit conversion (assuming the base class is accessible, i.e. it's a <code>public</code> inheritance).</p>\n<h2>Regular Cast</h2>\n<p>These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering <code>dynamic_cast</code>. Needless to say, this is much more powerful as it combines all of <code>const_cast</code>, <code>static_cast</code> and <code>reinterpret_cast</code>, but it's also unsafe, because it does not use <code>dynamic_cast</code>.</p>\n<p>In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" <code>static_cast</code> sequence would give you a compile-time error for that.</p>\n<p>Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.</p>\n"
},
{
"answer_id": 9151168,
"author": "larsmoa",
"author_id": 167251,
"author_profile": "https://Stackoverflow.com/users/167251",
"pm_score": 4,
"selected": false,
"text": "<p><code>dynamic_cast</code> only supports pointer and reference types. It returns <code>NULL</code> if the cast is impossible if the type is a pointer or throws an exception if the type is a reference type. Hence, <code>dynamic_cast</code> can be used to check if an object is of a given type, <code>static_cast</code> cannot (you will simply end up with an invalid value).</p>\n\n<p>C-style (and other) casts have been covered in the other answers. </p>\n"
},
{
"answer_id": 18414172,
"author": "Hossein",
"author_id": 2736559,
"author_profile": "https://Stackoverflow.com/users/2736559",
"pm_score": 8,
"selected": false,
"text": "<h2>Static cast</h2> \n \nThe static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.\n<pre><code>char c = 10; // 1 byte\nint *p = (int*)&c; // 4 bytes\n</code></pre>\n<p>Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.</p>\n<pre><code>*p = 5; // run-time error: stack corruption\n</code></pre>\n<p>In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.</p>\n<pre><code>int *q = static_cast<int*>(&c); // compile-time error\n</code></pre>\n<h2>Reinterpret cast</h2>\n<p>To force the pointer conversion, in the same way as the C-style cast does in the background, the reinterpret cast would be used instead.</p>\n<pre><code>int *r = reinterpret_cast<int*>(&c); // forced conversion\n</code></pre>\n<p>This cast handles conversions between certain unrelated types, such as from one pointer type to another incompatible pointer type. It will simply perform a binary copy of the data without altering the underlying bit pattern. Note that the result of such a low-level operation is system-specific and therefore not portable. It should be used with caution if it cannot be avoided altogether.</p>\n<h2>Dynamic cast</h2>\n<p>This one is only used to convert object pointers and object references into other pointer or reference types in the inheritance hierarchy. It is the only cast that makes sure that the object pointed to can be converted, by performing a run-time check that the pointer refers to a complete object of the destination type. For this run-time check to be possible the object must be polymorphic. That is, the class must define or inherit at least one virtual function. This is because the compiler will only generate the needed run-time type information for such objects.</p>\n<p><strong>Dynamic cast examples</strong></p>\n<p>In the example below, a <code>MyChild</code> pointer is converted into a <code>MyBase</code> pointer using a dynamic cast. This derived-to-base conversion succeeds, because the Child object includes a complete Base object.</p>\n<pre><code>class MyBase \n{ \n public:\n virtual void test() {}\n};\nclass MyChild : public MyBase {};\n\n\n\nint main()\n{\n MyChild *child = new MyChild();\n MyBase *base = dynamic_cast<MyBase*>(child); // ok\n}\n</code></pre>\n<p>The next example attempts to convert a <code>MyBase</code> pointer to a <code>MyChild</code> pointer. Since the Base object does not contain a complete Child object this pointer conversion will fail. To indicate this, the dynamic cast returns a null pointer. This gives a convenient way to check whether or not a conversion has succeeded during run-time.</p>\n<pre><code>MyBase *base = new MyBase();\nMyChild *child = dynamic_cast<MyChild*>(base);\n\n \nif (child == 0) \nstd::cout << "Null pointer returned";\n</code></pre>\n<p>If a reference is converted instead of a pointer, the dynamic cast will then fail by throwing a <code>bad_cast</code> exception. This needs to be handled using a <code>try-catch</code> statement.</p>\n<pre><code>#include <exception>\n// … \ntry\n{ \n MyChild &child = dynamic_cast<MyChild&>(*base);\n}\ncatch(std::bad_cast &e) \n{ \n std::cout << e.what(); // bad dynamic_cast\n}\n</code></pre>\n<h2>Dynamic or static cast</h2>\n<p>The advantage of using a dynamic cast is that it allows the programmer to check whether or not a conversion has succeeded during run-time. The disadvantage is that there is a performance overhead associated with doing this check. For this reason using a static cast would have been preferable in the first example, because a derived-to-base conversion will never fail.</p>\n<pre><code>MyBase *base = static_cast<MyBase*>(child); // ok\n</code></pre>\n<p>However, in the second example the conversion may either succeed or fail. It will fail if the <code>MyBase</code> object contains a <code>MyBase</code> instance and it will succeed if it contains a <code>MyChild</code> instance. In some situations this may not be known until run-time. When this is the case dynamic cast is a better choice than static cast.</p>\n<pre><code>// Succeeds for a MyChild object\nMyChild *child = dynamic_cast<MyChild*>(base);\n</code></pre>\n<p>If the base-to-derived conversion had been performed using a static cast instead of a dynamic cast the conversion would not have failed. It would have returned a pointer that referred to an incomplete object. Dereferencing such a pointer can lead to run-time errors.</p>\n<pre><code>// Allowed, but invalid\nMyChild *child = static_cast<MyChild*>(base);\n \n// Incomplete MyChild object dereferenced\n(*child);\n</code></pre>\n<h2>Const cast</h2>\n<p>This one is primarily used to add or remove the <code>const</code> modifier of a variable.</p>\n<pre><code>const int myConst = 5;\nint *nonConst = const_cast<int*>(&myConst); // removes const\n</code></pre>\n<p>Although <code>const</code> cast allows the value of a constant to be changed, doing so is still invalid code that may cause a run-time error. This could occur for example if the constant was located in a section of read-only memory.</p>\n<pre><code>*nonConst = 10; // potential run-time error\n</code></pre>\n<p><code>const</code> cast is instead used mainly when there is a function that takes a non-constant pointer argument, even though it does not modify the pointee.</p>\n<pre><code>void print(int *p) \n{\n std::cout << *p;\n}\n</code></pre>\n<p>The function can then be passed a constant variable by using a <code>const</code> cast.</p>\n<pre><code>print(&myConst); // error: cannot convert \n // const int* to int*\n \nprint(nonConst); // allowed\n</code></pre>\n<p><a href=\"https://web.archive.org/web/20140104001826/http://www.pvtuts.com/cpp/cpp-type-conversion-ii\" rel=\"noreferrer\">Source and More Explanations</a></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/28002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1821/"
] | I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.
```
MyClass *m = (MyClass *)ptr;
```
all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?
```
MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast<MyClass *>(ptr);
MyClass *m = dynamic_cast<MyClass *>(ptr);
``` | static\_cast
------------
`static_cast` is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. `static_cast` performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:
```
void func(void *data) {
// Conversion from MyClass* -> void* is implicit
MyClass *c = static_cast<MyClass*>(data);
...
}
int main() {
MyClass c;
start_thread(&func, &c) // func(&c) will be called
.join();
}
```
In this example, you know that you passed a `MyClass` object, and thus there isn't any need for a runtime check to ensure this.
dynamic\_cast
-------------
`dynamic_cast` is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a `bad_cast` exception is thrown in that case).
```
if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
...
}
```
You can **not** use `dynamic_cast` for downcast (casting to a derived class) **if** the argument type is not polymorphic. For example, the following code is not valid, because `Base` doesn't contain any virtual function:
```
struct Base { };
struct Derived : Base { };
int main() {
Derived d; Base *b = &d;
dynamic_cast<Derived*>(b); // Invalid
}
```
An "up-cast" (cast to the base class) is always valid with both `static_cast` and `dynamic_cast`, and also without any cast, as an "up-cast" is an implicit conversion (assuming the base class is accessible, i.e. it's a `public` inheritance).
Regular Cast
------------
These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering `dynamic_cast`. Needless to say, this is much more powerful as it combines all of `const_cast`, `static_cast` and `reinterpret_cast`, but it's also unsafe, because it does not use `dynamic_cast`.
In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" `static_cast` sequence would give you a compile-time error for that.
Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking. |
28,003 | <p>I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server.</p>
<p>I want to do something like:</p>
<pre><code>select [table]
from [db]
where table [has column 'classtypeid']
</code></pre>
<p>How can I do something like this?</p>
| [
{
"answer_id": 28008,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 4,
"selected": true,
"text": "<p>Use the ANSI information_schema views, this will also work in MySQL</p>\n\n<pre><code>select table_name \nfrom information_schema.columns \nwhere column_name = 'classtypeid'\n</code></pre>\n"
},
{
"answer_id": 28012,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>SELECT C.TABLE_NAME\nFROM INFORMATION_SCHEMA.COLUMNS AS C\n INNER JOIN INFORMATION_SCHEMA.TABLES AS T ON C.TABLE_NAME = T.TABLE_NAME\n AND C.TABLE_SCHEMA = T.TABLE_SCHEMA\nWHERE C.COLUMN_NAME = 'classtypeid'\n AND T.TABLE_TYPE = 'BASE TABLE'\n</code></pre>\n\n<hr>\n\n<p><strong>Edit</strong>: Note that this will not list views based on any tables with that column. If you only query INFORMATION_SCHEMA.COLUMNS you will also get back views.</p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/28003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server.
I want to do something like:
```
select [table]
from [db]
where table [has column 'classtypeid']
```
How can I do something like this? | Use the ANSI information\_schema views, this will also work in MySQL
```
select table_name
from information_schema.columns
where column_name = 'classtypeid'
``` |
28,029 | <p>How can I have it so Visual Studio doesn't keep re-creating this folder that I never use. It's annoying ot keep looking and unnecessary.</p>
| [
{
"answer_id": 29442,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": true,
"text": "<pre><code>Tools->Options->Addin/Macro Security\n</code></pre>\n\n<p>Change Paths there.</p>\n"
},
{
"answer_id": 10627752,
"author": "Răzvan Flavius Panda",
"author_id": 750216,
"author_profile": "https://Stackoverflow.com/users/750216",
"pm_score": 2,
"selected": false,
"text": "<p>Add a trailing slash to the default projects location:</p>\n\n<p><a href=\"http://rerrify.wordpress.com/2012/03/22/get-rid-of-the-annoying-vsmacros80-folder-5/\" rel=\"nofollow\">Get Rid of the Annoying VSMacros80 Folder</a></p>\n"
},
{
"answer_id": 22527972,
"author": "FearlessCoward",
"author_id": 3441182,
"author_profile": "https://Stackoverflow.com/users/3441182",
"pm_score": 0,
"selected": false,
"text": "<p>Just add \"/\" on the end of your \"Projects location\". (Tested on 2010 SP1.)</p>\n\n<p><a href=\"https://stackoverflow.com/questions/70377/remove-vsmacros80-directory\">Remove VSMacros80 directory</a></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/28029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
] | How can I have it so Visual Studio doesn't keep re-creating this folder that I never use. It's annoying ot keep looking and unnecessary. | ```
Tools->Options->Addin/Macro Security
```
Change Paths there. |
28,092 | <p>I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style?</p>
<p>Here is my style (affected code only):</p>
<pre><code><Style x:Key="UsersTimeOffList" TargetType="{x:Type ListBoxItem}">
...
<Grid>
<Button x:Name="btnRemove" Content="Remove" Margin="0,10,40,0" Click="btnRemove_Click" />
</Grid>
</Style>
</code></pre>
<p>Thanks! </p>
| [
{
"answer_id": 28187,
"author": "Jas",
"author_id": 777,
"author_profile": "https://Stackoverflow.com/users/777",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a user control (.ascx) to house the listbox. Then add a public event for the page.</p>\n\n<pre><code>Public Event btnRemove()\n</code></pre>\n\n<p>Then on the button click event in the usercontrol</p>\n\n<pre><code>RaiseEvent btnRemove()\n</code></pre>\n\n<p>You can also pass objects through the event just like any other method. This will allow your user control to tell your page what to delete.</p>\n"
},
{
"answer_id": 28252,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 4,
"selected": true,
"text": "<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx\" rel=\"noreferrer\">RoutedCommand</a>s.</p>\n\n<p>Define your command in myclass somewhere as follows:</p>\n\n<pre><code> public static readonly RoutedCommand Login = new RoutedCommand();\n</code></pre>\n\n<p>Now define your button with this command:</p>\n\n<pre><code> <Button Command=\"{x:Static myclass.Login}\" /> \n</code></pre>\n\n<p>You can use CommandParameter for extra information..</p>\n\n<p>Now last but not least, start listening to your command:</p>\n\n<p>In the constructor of the class you wish to do some nice stuff, you place:</p>\n\n<pre><code> CommandBindings.Add(new CommandBinding(myclass.Login, ExecuteLogin));\n</code></pre>\n\n<p>or in XAML:</p>\n\n<pre><code> <UserControl.CommandBindings>\n <CommandBinding Command=\"{x:Static myclass.Login}\" Executed=\"ExecuteLogin\" />\n </UserControl.CommandBindings>\n</code></pre>\n\n<p>And you implement the delegate the CommandBinding needs:</p>\n\n<pre><code> private void ExecuteLogin(object sender, ExecutedRoutedEventArgs e)\n {\n //Your code goes here... e has your parameter!\n }\n</code></pre>\n\n<p>You can start listening to this command everywhere in your visual tree!</p>\n\n<p>Hope this helps</p>\n\n<p>PS You can also define the CommandBinding with a CanExecute delegate which will even disable your command if the CanExecute says so :)</p>\n\n<p>PPS Here is another example: <a href=\"http://www.wpfwiki.com/Default.aspx?Page=WPF%20Q13.8&AspxAutoDetectCookieSupport=1\" rel=\"noreferrer\">RoutedCommands in WPF</a></p>\n"
},
{
"answer_id": 190051,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>As Arcturus posted, RoutedCommands are a great way to achieve this. However, if there's only the one button in your DataTemplate then this might be a bit simpler:</p>\n\n<p>You can actually handle any button's Click event from the host ListBox, like this:</p>\n\n<pre><code><ListBox Button.Click=\"removeButtonClick\" ... />\n</code></pre>\n\n<p>Any buttons contained within the ListBox will fire that event when they're clicked on. From within the event handler you can use e.OriginalSource to get a reference back to the button that was clicked on.</p>\n\n<p>Obviously this is too simplistic if your ListBoxItems have more than one button, but in many cases it works just fine. </p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/28092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] | I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style?
Here is my style (affected code only):
```
<Style x:Key="UsersTimeOffList" TargetType="{x:Type ListBoxItem}">
...
<Grid>
<Button x:Name="btnRemove" Content="Remove" Margin="0,10,40,0" Click="btnRemove_Click" />
</Grid>
</Style>
```
Thanks! | Take a look at [RoutedCommand](http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx)s.
Define your command in myclass somewhere as follows:
```
public static readonly RoutedCommand Login = new RoutedCommand();
```
Now define your button with this command:
```
<Button Command="{x:Static myclass.Login}" />
```
You can use CommandParameter for extra information..
Now last but not least, start listening to your command:
In the constructor of the class you wish to do some nice stuff, you place:
```
CommandBindings.Add(new CommandBinding(myclass.Login, ExecuteLogin));
```
or in XAML:
```
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static myclass.Login}" Executed="ExecuteLogin" />
</UserControl.CommandBindings>
```
And you implement the delegate the CommandBinding needs:
```
private void ExecuteLogin(object sender, ExecutedRoutedEventArgs e)
{
//Your code goes here... e has your parameter!
}
```
You can start listening to this command everywhere in your visual tree!
Hope this helps
PS You can also define the CommandBinding with a CanExecute delegate which will even disable your command if the CanExecute says so :)
PPS Here is another example: [RoutedCommands in WPF](http://www.wpfwiki.com/Default.aspx?Page=WPF%20Q13.8&AspxAutoDetectCookieSupport=1) |
28,098 | <p>How do I convert the value of a PHP variable to string?</p>
<p>I was looking for something better than concatenating with an empty string:</p>
<pre><code>$myText = $myVar . '';
</code></pre>
<p>Like the <code>ToString()</code> method in Java or .NET.</p>
| [
{
"answer_id": 28101,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "<p>Putting it in double quotes should work:</p>\n\n<pre><code>$myText = \"$myVar\";\n</code></pre>\n"
},
{
"answer_id": 28104,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>You can always create a method named .ToString($in) that returns</p>\n\n<pre><code>$in . ''; \n</code></pre>\n"
},
{
"answer_id": 28108,
"author": "Chris",
"author_id": 2134,
"author_profile": "https://Stackoverflow.com/users/2134",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>How do I convert the value of a PHP\n variable to string?</p>\n</blockquote>\n\n<p>A value can be converted to a string using the <a href=\"http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting\" rel=\"nofollow noreferrer\">(string) cast</a> or the <a href=\"http://ca.php.net/strval\" rel=\"nofollow noreferrer\">strval()</a> function. (Edit: As <a href=\"https://stackoverflow.com/users/2314/thomas-g-mayfield\">Thomas</a> also stated).</p>\n\n<p>It also should be automatically casted for you when you use it as a string.</p>\n"
},
{
"answer_id": 28111,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 11,
"selected": true,
"text": "<p>You can use the <a href=\"http://us3.php.net/manual/en/language.types.type-juggling.php\" rel=\"noreferrer\">casting operators</a>:</p>\n\n<pre><code>$myText = (string)$myVar;\n</code></pre>\n\n<p>There are more details for string casting and conversion in the <a href=\"http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting\" rel=\"noreferrer\">Strings section</a> of the PHP manual, including special handling for booleans and nulls.</p>\n"
},
{
"answer_id": 28115,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>If you're converting anything other than simple types like integers or booleans, you'd need to write your own function/method for the type that you're trying to convert, otherwise PHP will just print the type (such as array, GoogleSniffer, or Bidet).</p>\n"
},
{
"answer_id": 28119,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 1,
"selected": false,
"text": "<p>PHP is dynamically typed, so like Chris Fournier said, \"If you use it like a string it becomes a string\". If you're looking for more control over the format of the string then <a href=\"http://dk1.php.net/printf\" rel=\"nofollow noreferrer\">printf</a> is your answer.</p>\n"
},
{
"answer_id": 28131,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 8,
"selected": false,
"text": "<p>This is done with typecasting:</p>\n\n<pre><code>$strvar = (string) $var; // Casts to string\necho $var; // Will cast to string implicitly\nvar_dump($var); // Will show the true type of the variable\n</code></pre>\n\n<p>In a class you can define what is output by using the magical method <a href=\"http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring\" rel=\"noreferrer\"><code>__toString</code></a>. An example is below:</p>\n\n<pre><code>class Bottles {\n public function __toString()\n {\n return 'Ninety nine green bottles';\n }\n}\n\n$ex = new Bottles;\nvar_dump($ex, (string) $ex);\n// Returns: instance of Bottles and \"Ninety nine green bottles\"\n</code></pre>\n\n<p>Some more type casting examples:</p>\n\n<pre><code>$i = 1;\n\n// int 1\nvar_dump((int) $i);\n\n// bool true\nvar_dump((bool) $i);\n\n// string \"1\"\nvar_dump((string) 1);\n</code></pre>\n"
},
{
"answer_id": 28152,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 4,
"selected": false,
"text": "<p>For primitives just use <code>(string)$var</code> or print this variable straight away. PHP is dynamically typed language and variable will be casted to string on the fly.</p>\n\n<p>If you want to convert objects to strings you will need to define <code>__toString()</code> method that returns string. This method is forbidden to throw exceptions.</p>\n"
},
{
"answer_id": 1936122,
"author": "opensas",
"author_id": 47633,
"author_profile": "https://Stackoverflow.com/users/47633",
"pm_score": 5,
"selected": false,
"text": "<p>You are looking for <a href=\"http://php.net/manual/en/function.strval.php\" rel=\"noreferrer\">strval</a>:</p>\n<blockquote>\n<h3><code>string strval ( mixed $var )</code></h3>\n<p>Get the string value of a variable.\nSee the documentation on string for\nmore information on converting to\nstring.</p>\n<p>This function performs no formatting\non the returned value. If you are\nlooking for a way to format a numeric\nvalue as a string, please see\nsprintf() or number_format().</p>\n</blockquote>\n"
},
{
"answer_id": 1991021,
"author": "Joel Larson",
"author_id": 242230,
"author_profile": "https://Stackoverflow.com/users/242230",
"pm_score": 6,
"selected": false,
"text": "<p>You can either use typecasting:</p>\n\n<pre><code>$var = (string)$varname;\n</code></pre>\n\n<p>or StringValue:</p>\n\n<pre><code>$var = strval($varname);\n</code></pre>\n\n<p>or SetType:</p>\n\n<pre><code>$success = settype($varname, 'string');\n// $varname itself becomes a string\n</code></pre>\n\n<p>They all work for the same thing in terms of Type-Juggling.</p>\n"
},
{
"answer_id": 3559247,
"author": "Cedric",
"author_id": 278739,
"author_profile": "https://Stackoverflow.com/users/278739",
"pm_score": 7,
"selected": false,
"text": "<p>Use <a href=\"https://www.php.net/manual/en/function.print-r.php\" rel=\"nofollow noreferrer\"><strong>print_r</strong></a>:</p>\n\n<pre><code>$myText = print_r($myVar,true);\n</code></pre>\n\n<p>You can also use it like: </p>\n\n<pre><code>$myText = print_r($myVar,true).\"foo bar\";\n</code></pre>\n\n<p>This will set <code>$myText</code> to a string, like:</p>\n\n<pre><code>array (\n 0 => '11',\n)foo bar\n</code></pre>\n\n<p>Use <a href=\"https://www.php.net/manual/en/function.var-export.php\" rel=\"nofollow noreferrer\"><strong>var_export</strong></a> to get a little bit more info (with types of variable,...):</p>\n\n<pre><code>$myText = var_export($myVar,true);\n</code></pre>\n"
},
{
"answer_id": 5219818,
"author": "Justin Weeks",
"author_id": 598548,
"author_profile": "https://Stackoverflow.com/users/598548",
"pm_score": 3,
"selected": false,
"text": "<p>Another option is to use the built in <a href=\"http://us3.php.net/manual/en/function.settype.php\" rel=\"noreferrer\">settype</a> function:</p>\n\n<pre><code><?php\n$foo = \"5bar\"; // string\n$bar = true; // boolean\n\nsettype($foo, \"integer\"); // $foo is now 5 (integer)\nsettype($bar, \"string\"); // $bar is now \"1\" (string)\n?>\n</code></pre>\n\n<p>This actually performs a conversion on the variable unlike typecasting and allows you to have a general way of converting to multiple types.</p>\n"
},
{
"answer_id": 6891412,
"author": "Flak DiNenno",
"author_id": 589655,
"author_profile": "https://Stackoverflow.com/users/589655",
"pm_score": 1,
"selected": false,
"text": "<p>Double quotes should work too... it should create a string, then it should APPEND/INSERT the casted STRING value of $myVar in between 2 empty strings.</p>\n"
},
{
"answer_id": 10473070,
"author": "Yauhen Yakimovich",
"author_id": 544463,
"author_profile": "https://Stackoverflow.com/users/544463",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to the answer given by Thomas G. Mayfield: </p>\n\n<p>If you follow the link to the string casting manual, there is a special case which is quite important to understand:</p>\n\n<p>(string) cast is preferable especially if your variable <strong>$a</strong> is an object, because PHP will follow the casting <a href=\"http://ch.php.net/manual/en/language.oop5.magic.php#object.tostring\">protocol</a> according to its object model by calling <strong>__toString()</strong> magic method (if such is defined in the class of which $a is instantiated from).</p>\n\n<p>PHP does something similar to</p>\n\n<pre><code>function castToString($instance) \n{ \n if (is_object($instance) && method_exists($instance, '__toString')) {\n return call_user_func_array(array($instance, '__toString'));\n }\n}\n</code></pre>\n\n<p>The <em>(string)</em> casting operation is a recommended technique for PHP5+ programming making code more Object-Oriented. IMO this is a nice example of design similarity (difference) to other OOP languages like Java/C#/etc., i.e. in its own special PHP way (whenever it's for the good or for the worth).</p>\n"
},
{
"answer_id": 15794348,
"author": "Archimedes Trajano",
"author_id": 242042,
"author_profile": "https://Stackoverflow.com/users/242042",
"pm_score": 0,
"selected": false,
"text": "<p>For objects, you may not be able to use the cast operator. Instead, I use the <code>json_encode()</code> method.</p>\n\n<p>For example, the following will output contents to the error log:</p>\n\n<pre><code>error_log(json_encode($args));\n</code></pre>\n"
},
{
"answer_id": 20011937,
"author": "DarthKotik",
"author_id": 2964871,
"author_profile": "https://Stackoverflow.com/users/2964871",
"pm_score": 2,
"selected": false,
"text": "<p>The documentation says that you can also do:</p>\n\n<pre><code>$str = \"$foo\";\n</code></pre>\n\n<p>It's the same as cast, but I think it looks prettier.</p>\n\n<p>Source:</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/ru/language.types.type-juggling.php\" rel=\"nofollow\">Russian</a> </li>\n<li><a href=\"http://us3.php.net/manual/en/language.types.type-juggling.php\" rel=\"nofollow\">English</a></li>\n</ul>\n"
},
{
"answer_id": 22016653,
"author": "mikikg",
"author_id": 783354,
"author_profile": "https://Stackoverflow.com/users/783354",
"pm_score": 0,
"selected": false,
"text": "<p>Try this little strange, but working, approach to convert the textual part of stdClass to string type:</p>\n\n<pre><code>$my_std_obj_result = $SomeResponse->return->data; // Specific to object/implementation\n\n$my_string_result = implode ((array)$my_std_obj_result); // Do conversion\n</code></pre>\n"
},
{
"answer_id": 22028490,
"author": "Daan",
"author_id": 987864,
"author_profile": "https://Stackoverflow.com/users/987864",
"pm_score": 4,
"selected": false,
"text": "<p>I think it is worth mentioning that you can catch any output (like <code>print_r</code>, <code>var_dump</code>) in a variable by using output buffering:</p>\n\n<pre><code><?php\n ob_start();\n var_dump($someVar);\n $result = ob_get_clean();\n?>\n</code></pre>\n\n<p>Thanks to:\n<em><a href=\"https://stackoverflow.com/questions/139474/how-can-i-capture-the-result-of-var-dump-to-a-string/139491#139491\">How can I capture the result of var_dump to a string?</a></em></p>\n"
},
{
"answer_id": 23732710,
"author": "user1587439",
"author_id": 1587439,
"author_profile": "https://Stackoverflow.com/users/1587439",
"pm_score": 3,
"selected": false,
"text": "<p>Some, if not all, of the methods in the previous answers fail when the intended string variable has a <em>leading zero</em>, for example, <em>077543</em>.</p>\n\n<p>An attempt to convert such a variable fails to get the intended string, because the variable is converted to <em>base 8 (octal)</em>.</p>\n\n<p>All these will make <code>$str</code> have a value of <em>32611</em>:</p>\n\n<pre><code>$no = 077543\n$str = (string)$no;\n$str = \"$no\";\n$str = print_r($no,true);\n$str = strval($no);\n$str = settype($no, \"integer\");\n</code></pre>\n"
},
{
"answer_id": 31942656,
"author": "Aby W",
"author_id": 2802318,
"author_profile": "https://Stackoverflow.com/users/2802318",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use the <a href=\"http://php.net/manual/en/function.var-export.php\" rel=\"nofollow noreferrer\">var_export</a> PHP function.</p>\n"
},
{
"answer_id": 33391476,
"author": "ling",
"author_id": 405042,
"author_profile": "https://Stackoverflow.com/users/405042",
"pm_score": -1,
"selected": false,
"text": "<p>I use <a href=\"https://github.com/lingtalfi/VariableToString\" rel=\"nofollow noreferrer\">variableToString</a>. It handles every PHP type and is flexible (you can extend it if you want).</p>\n"
},
{
"answer_id": 37725483,
"author": "Daniel Adenew",
"author_id": 2281472,
"author_profile": "https://Stackoverflow.com/users/2281472",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$parent_category_name = \"new clothes & shoes\";\n\n// To make it to string option one\n$parent_category = strval($parent_category_name);\n\n// Or make it a string by concatenating it with 'new clothes & shoes'\n// It is useful for database queries\n$parent_category = \"'\" . strval($parent_category_name) . \"'\";\n</code></pre>\n"
},
{
"answer_id": 39259207,
"author": "jimp",
"author_id": 791265,
"author_profile": "https://Stackoverflow.com/users/791265",
"pm_score": 3,
"selected": false,
"text": "<p>As others have mentioned, objects need a <code>__toString</code> method to be cast to a string. An object that doesn't define that method can still produce a string representation using the <a href=\"http://php.net/manual/en/function.spl-object-hash.php\" rel=\"nofollow noreferrer\">spl_object_hash</a> function.</p>\n\n<blockquote>\n <p>This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.</p>\n</blockquote>\n\n<p>I have a base Object class with a <code>__toString</code> method that defaults to calling <code>md5(spl_object_hash($this))</code> to make the output clearly unique, since the output from spl_object_hash can look very similar between objects.</p>\n\n<p>This is particularly helpful for debugging code where a variable initializes as an Object and later in the code it is suspected to have changed to a different Object. Simply echoing the variables to the log can reveal the change from the object hash (or not).</p>\n"
},
{
"answer_id": 53883743,
"author": "Xanlantos",
"author_id": 4693430,
"author_profile": "https://Stackoverflow.com/users/4693430",
"pm_score": 3,
"selected": false,
"text": "<p>I think this question is a bit misleading since,\ntoString() in Java isn't just a way to cast something to a String. That is what <a href=\"http://us3.php.net/manual/en/language.types.type-juggling.php\" rel=\"nofollow noreferrer\">casting</a> via (string) or String.valueOf() does, and it works as well in PHP.</p>\n\n<pre><code>// Java\nString myText = (string) myVar;\n\n// PHP\n$myText = (string) $myVar;\n</code></pre>\n\n<p>Note that this can be problematic as Java is type-safe (<a href=\"https://stackoverflow.com/questions/16815279/difference-between-casting-to-string-and-string-valueof\">see here for more details</a>).</p>\n\n<p>But as I said, this is casting and therefore not the equivalent of Java's toString().</p>\n\n<p>toString in Java <strong>doesn't just cast an object to a String. It instead will give you the String representation</strong>. And that's what <a href=\"https://www.php.net/manual/en/language.oop5.magic.php#object.tostring\" rel=\"nofollow noreferrer\">__toString()</a> in PHP does.</p>\n\n<pre><code>// Java\nclass SomeClass{\n public String toString(){\n return \"some string representation\";\n }\n}\n\n// PHP\nclass SomeClass{\n public function __toString()\n {\n return \"some string representation\";\n }\n}\n</code></pre>\n\n<p>And from the other side:</p>\n\n<pre><code>// Java\nnew SomeClass().toString(); // \"Some string representation\"\n\n// PHP\nstrval(new SomeClass); // \"Some string representation\"\n</code></pre>\n\n<p>What do I mean by \"giving the String representation\"?\nImagine a class for a library with millions of books.</p>\n\n<ul>\n<li>Casting that class to a String would (by default) convert the data, here all books, into a string so the String would be very long and most of the time not very useful either.</li>\n<li>To String instead will give you the String representation, i.e., only the name of the library. This is shorter and therefore gives you less, but more important information.</li>\n</ul>\n\n<p>These are both valid approaches but with very different goals, neither is a perfect solution for every case and you have to chose wisely which fits better for your needs.</p>\n\n<p><strong>Sure, there are even more options:</strong></p>\n\n<pre><code>$no = 421337 // A number in PHP\n$str = \"$no\"; // In PHP, stuff inside \"\" is calculated and variables are replaced\n$str = print_r($no, true); // Same as String.format();\n$str = settype($no, 'string'); // Sets $no to the String Type\n$str = strval($no); // Get the string value of $no\n$str = $no . ''; // As you said concatenate an empty string works too\n</code></pre>\n\n<p>All of these methods will return a String, some of them using __toString internally and some others will fail on Objects. Take a look at the <a href=\"http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting\" rel=\"nofollow noreferrer\">PHP documentation</a> for more details.</p>\n"
},
{
"answer_id": 64322954,
"author": "dılo sürücü",
"author_id": 5582655,
"author_profile": "https://Stackoverflow.com/users/5582655",
"pm_score": 0,
"selected": false,
"text": "<p>__toString method or (string) cast</p>\n<pre class=\"lang-php prettyprint-override\"><code>$string=(string)$variable; //force make string \n</code></pre>\n<p>you can treat an object as a string</p>\n<pre class=\"lang-php prettyprint-override\"><code>\nclass Foo\n{\n\n public function __toString()\n {\n return "foo";\n }\n\n}\n\necho new Foo(); //foo\n</code></pre>\n<p>also, have another trick, ı assume ı have int variable ı want to make string it</p>\n<pre class=\"lang-php prettyprint-override\"><code>\n$string=''.$intvariable;\n</code></pre>\n"
},
{
"answer_id": 72723752,
"author": "JSON",
"author_id": 1246037,
"author_profile": "https://Stackoverflow.com/users/1246037",
"pm_score": 0,
"selected": false,
"text": "<p>This can be difficult in PHP because of the way data types are handled internally. Assuming that you don't mean complex types such as objects or resources, generic casting to strings may still result in incorrect conversion. In some cases pack/unpack may even be required, and then you still have the possibility of problems with string encoding. I know this might sound like a stretch but these are the type of cases where standard type juggling such as <code>$myText = $my_var .'';</code> and <code>$myText = (string)$my_var;</code> (and similar) may not work. Otherwise I would suggest a generic cast, or using serialize() or json_encode(), but again it depends on what you plan on doing with the string.</p>\n<p>The primary difference is that Java and .NET have better facilities with handling binary data and primitive types, and converting to/from specific types and then to string from there, even if a specific case is abstracted away from the user. It's a different story with PHP where even handling hex can leave you scratching your head until you get the hang of it.</p>\n<p>I can't think of a better way to answer this which is comparable to Java/.NET where _toString() and such methods are usually implemented in a way that's <strong>specific to the object or data type</strong>. In that way the magic methods __toString() and __serialize()/__unserialize() may be the best comparison.</p>\n<p>Also keep in mind that PHP doesn't have the same concepts of primitive data types. In essence every data type in PHP can be considered an object, and their internal handlers try to make them somewhat universal, even if it means loosing accuracy such as when converting a float to int. You can't deal with types as you can in Java unless your working with their zvals within a native extension.</p>\n<p>While PHP userspace doesn't define int, char, bool, or float as an objects, everything is stored in a zval structure which is as close to an object that you can find in C, with generic functions for handling the data within the zval. Every possible way to access data within PHP goes down to the zval structure and the way the zend vm allows you to handles them without converting them to native types and structures. With Java types you have finer grained access to their data and more ways to to manipulate them, but also greater complexity, hence the strong type vs weak type argument.</p>\n<p>These links my be helpful:</p>\n<p><a href=\"https://www.php.net/manual/en/language.types.type-juggling.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/language.types.type-juggling.php</a>\n<a href=\"https://www.php.net/manual/en/language.oop5.magic.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/language.oop5.magic.php</a></p>\n"
}
] | 2008/08/26 | [
"https://Stackoverflow.com/questions/28098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680/"
] | How do I convert the value of a PHP variable to string?
I was looking for something better than concatenating with an empty string:
```
$myText = $myVar . '';
```
Like the `ToString()` method in Java or .NET. | You can use the [casting operators](http://us3.php.net/manual/en/language.types.type-juggling.php):
```
$myText = (string)$myVar;
```
There are more details for string casting and conversion in the [Strings section](http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting) of the PHP manual, including special handling for booleans and nulls. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.