qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
253,446
<p>How does one add a comment to an MS Access Query, to provide a description of what it does?</p> <p>Once added, how can one retrieve such comments programmatically?</p>
[ { "answer_id": 253714, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 4, "selected": false, "text": "<p>It is not possible to add comments to 'normal' Access queries, that is, a QueryDef in an mdb, which is why a number of people recommend storing the sql for queries in a table.</p>\n" }, { "answer_id": 253784, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 5, "selected": true, "text": "<p><strong>NOTE:</strong> Confirmed with Access 2003, don't know about earlier versions.</p>\n\n<p>For a query in an MDB you can right-click in the query designer (anywhere in the empty space where the tables are), select Properties from the context menu, and enter text in the <em>Description</em> property. </p>\n\n<p>You're limited to 256 characters, but it's better than nothing.</p>\n\n<p>You can get at the description programatically with something like this:</p>\n\n<pre><code>Dim db As Database\nDim qry As QueryDef\n\nSet db = Application.CurrentDb\nSet qry = db.QueryDefs(\"myQuery\")\n\nDebug.Print qry.Properties(\"Description\")\n</code></pre>\n" }, { "answer_id": 4763339, "author": "JTR", "author_id": 585005, "author_profile": "https://Stackoverflow.com/users/585005", "pm_score": 2, "selected": false, "text": "<p>You can add a comment to an MSAccess query as follows: Create a dummy field in the query. Not elegant but is self-documentating and contained in the query, which makes cheking it into source code control alot more feasible! Jere's an example. Go into SQL view and add the dummy field (you can do from design view too):</p>\n\n<pre><code>SELECT \"2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;\" as qryHISTORY, ...rest of query here...\n</code></pre>\n\n<p>Run the query:</p>\n\n<pre><code>qryHISTORY FIELD01 FIELD02 ...\n2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;\" 0000001 ABCDEF ...\n</code></pre>\n\n<p>Note the use of \";\" as field delimiter in qryHISTORY field, and \";;\" as an end of comment, and use of ISO date format and intials, as well as comment. Have tested this with up to 646 characters in the qryHISTORY field.</p>\n" }, { "answer_id": 5391483, "author": "iDevlop", "author_id": 78522, "author_profile": "https://Stackoverflow.com/users/78522", "pm_score": 2, "selected": false, "text": "<p>I know this question is very old, but I would like to add a few points, strangely omitted: </p>\n\n<ol>\n<li>you can right-click the query in the container, and click properties, and fill that with your description. The text you input that way is also accessible in design view, in the Descrption property</li>\n<li>Each field can be documented as well. Just make sure the properties window is open, then click the query field you want to document, and fill the Description (just above the too little known Format property) </li>\n</ol>\n\n<p>It's a bit sad that no product (I know of) documents these query fields descriptions and expressions.</p>\n" }, { "answer_id": 12311190, "author": "Patrick Boylan", "author_id": 1653616, "author_profile": "https://Stackoverflow.com/users/1653616", "pm_score": 2, "selected": false, "text": "<p>The first answer mentioned how to get the description property programatically. If you're going to bother with program anyway, since the comments in the query are so kludgy, instead of trying to put the comments in the query, maybe it's better to put them in a program and use the program to make all your queries</p>\n\n<pre><code>Dim dbs As DAO.Database\nDim qry As DAO.QueryDef\n\nSet dbs = CurrentDb\n'put your comments wherever in your program makes the most sense\ndbs.QueryDefs(\"qryName\").SQL = \"SELECT whatever.fields FROM whatever_table;\"\nDoCmd.OpenQuery \"qryname\"\n</code></pre>\n" }, { "answer_id": 12448538, "author": "Jarad Pillemer", "author_id": 1675906, "author_profile": "https://Stackoverflow.com/users/1675906", "pm_score": 1, "selected": false, "text": "<p>If you have a query with a lot of criteria, it can be tricky to remember what each one does. \nI add a text field into the original table - call it \"comments\" or \"documentation\".\nThen I include it in the query with a comment for each criteria.</p>\n\n<p>Comments need to be written like like this so that all relevant rows are returned.\nUnfortunately, as I'm a new poster, I can't add a screenshot!</p>\n\n<p>So here goes without</p>\n\n<pre><code>Field: | Comment |ContractStatus | ProblemDealtWith | ...... |\n\nTable: | ElecContracts |ElecContracts | ElecContracts | ...... |\n\nSort: \n\nShow: \n\nCriteria | &lt;&gt; \"all problems are | \"objection\" Or |\n\n | picked up with this | \"rejected\" Or |\n\n | criteria\" OR Is Null | \"rolled\" |\n\n | OR \"\"\n</code></pre>\n\n<p><code>&lt;&gt;</code> tells the query to choose rows that are not equal to the text you entered, otherwise it will only pick up fields that have text equal to your comment i.e. none!</p>\n\n<p>\" \" enclose your comment in quotes</p>\n\n<p>OR Is Null OR \"\" tells your query to include any rows that have no data in the comments field , otherwise it won't return anything!</p>\n" }, { "answer_id": 28096339, "author": "Dan", "author_id": 839501, "author_profile": "https://Stackoverflow.com/users/839501", "pm_score": 5, "selected": false, "text": "<p>I decided to add a condition to the <code>Where</code> Clause that always evaluates true but allows the coder to find your comment.</p>\n\n<pre><code>Select\n ...\nFrom\n ...\nWhere\n ....\n And \"Comment: FYI, Access doesn't support normal comments!\"&lt;&gt;\"\"\n</code></pre>\n\n<p>The last line always evaluates to true so it doesn't affect the data returned but allows you to leave a comment for the next guy.</p>\n" }, { "answer_id": 44283416, "author": "mschoular", "author_id": 8091632, "author_profile": "https://Stackoverflow.com/users/8091632", "pm_score": 0, "selected": false, "text": "<p>if you are trying to add a general note to the overall object (query or table etc..)</p>\n\n<p>Access 2016\ngo to navigation pane, highlight object, right click, select object / table properties, add a note in the description window i.e. inventory \"table last last updated 05/31/17\"</p>\n" }, { "answer_id": 48116214, "author": "steveapa", "author_id": 9178109, "author_profile": "https://Stackoverflow.com/users/9178109", "pm_score": 0, "selected": false, "text": "<p>In the query design: </p>\n\n<ul>\n<li>add a column</li>\n<li>enter your comment (in quotes) in the field</li>\n<li>uncheck <strong>Show</strong></li>\n<li>sort in assending.</li>\n</ul>\n\n<p><strong>Note:</strong></p>\n\n<p>If you don't sort, the field will be removed by access. So, make sure you've unchecked show and sorted the column.</p>\n" }, { "answer_id": 66747336, "author": "NewSites", "author_id": 5803910, "author_profile": "https://Stackoverflow.com/users/5803910", "pm_score": 1, "selected": false, "text": "<p>I've been using the method in the answer by @Dan above for five years, and now realized there's a similar way that allows a comment adjacent to the relevant code, not separated away in a <code>WHERE</code> clause:</p>\n<p>A comment can be added in the field code using <code>iif()</code>. For example, if the field code is:</p>\n<pre><code>A / B\n</code></pre>\n<p>then it can be commented like so:</p>\n<pre><code>iif(&quot;Comment: B is never 0.&quot; = &quot;&quot;, &quot;&quot;, A / B)\n</code></pre>\n<p>or</p>\n<pre><code>iif(false, &quot;Comment: B is never 0.&quot;, A / B)\n</code></pre>\n<p>or</p>\n<pre><code>iif(0, &quot;Comment: B is never 0.&quot;, A / B)\n</code></pre>\n<p>Like Dan's solution, it's kludgy, but that's SQL's fault.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6613/" ]
How does one add a comment to an MS Access Query, to provide a description of what it does? Once added, how can one retrieve such comments programmatically?
**NOTE:** Confirmed with Access 2003, don't know about earlier versions. For a query in an MDB you can right-click in the query designer (anywhere in the empty space where the tables are), select Properties from the context menu, and enter text in the *Description* property. You're limited to 256 characters, but it's better than nothing. You can get at the description programatically with something like this: ``` Dim db As Database Dim qry As QueryDef Set db = Application.CurrentDb Set qry = db.QueryDefs("myQuery") Debug.Print qry.Properties("Description") ```
253,468
<p>For my apps, I store some configuration file in xml along with the assembly(exe), and something other temporary files for proccessing purpose. </p> <p>I found some quirk with <code>".\\"</code> and <code>Application.StartupPath</code>.</p> <p>I've been using </p> <pre><code>String configPath = ".\\config.xml"; </code></pre> <p>It works fine until I called <code>OpenFIleDialog</code> to open some files in other folders, the statement above failed. Apparently ".\" is referring to "CurrentDirectory", which changes every time when we browse to another folder.</p> <p>At some point, I was using </p> <pre><code>String configPath = Path.Combine(Application.StartupPath + "config.xml"); </code></pre> <p>At some point, when I need to execute this assembly from another folder by using <code>Process.Start()</code>, things start to fall apart. Apparently the working directory is not set properly, and <code>Application.StartupPath</code> is actually referring to working directory instead of the directory of which the assembly is executing, as I've assumed. So I have to resort to using ProcessInfo to setup the working directory to the assembly's directory. I also had problem with this when I was writing VSTO.</p> <p>So, my question is, what's the best, simplest and most assured way to get the current directory that the assembly is executing, without those quirks(or misunderstanding) that I've just mentioned?</p> <p>EDIT: I meant to get the directory which the assembly reside</p> <p>EDIT: According to MSDN on <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.basedirectory.aspx" rel="noreferrer">AppDomain.BaseDirectory</a>, it seems that it can be changes during runtime, which is what I don't want(Just to clarify, not that I don't want to allow changing BaseDirectory, but rather, when I retrieve it without knowing for sure whether it's been changed)</p> <p>EDIT: I've notice that a related question was posted much earlier. <a href="https://stackoverflow.com/questions/158219/what-would-cause-the-current-directory-of-an-executing-app-to-change">What would cause the current directory of an executing app to change?</a></p> <p>Thanks guys for the answer.</p>
[ { "answer_id": 253486, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Do you want the actual working directory, or the directory containing the assembly? It's not entirely clear.</p>\n\n<p>There's <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx\" rel=\"noreferrer\"><code>Environment.CurrentDirectory</code></a> if you want the working directory, or <code>Path.GetDirectoryName(typeof(Foo).Assembly.ManifestModule.FullyQualifiedName)</code> to find the location of an assembly (or at least its manifest module, which will be the same thing in almost all cases).</p>\n" }, { "answer_id": 253500, "author": "tafa", "author_id": 22186, "author_profile": "https://Stackoverflow.com/users/22186", "pm_score": 3, "selected": false, "text": "<p>There is also,</p>\n\n<pre><code>System.Reflection.Assembly.GetExecutingAssembly().CodeBase\n</code></pre>\n" }, { "answer_id": 253502, "author": "GalacticCowboy", "author_id": 29638, "author_profile": "https://Stackoverflow.com/users/29638", "pm_score": 1, "selected": false, "text": "<p>How about </p>\n\n<pre><code>string currentAssemblyFile = System.Reflection.Assembly.GetExecutingAssembly().Location;\n</code></pre>\n\n<p>and then figure it out from there...</p>\n" }, { "answer_id": 253504, "author": "korro", "author_id": 22650, "author_profile": "https://Stackoverflow.com/users/22650", "pm_score": 7, "selected": true, "text": "<pre><code>System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))\n</code></pre>\n" }, { "answer_id": 253505, "author": "Mat Nadrofsky", "author_id": 26853, "author_profile": "https://Stackoverflow.com/users/26853", "pm_score": 2, "selected": false, "text": "<p>I'd try something like this from the following <a href=\"http://msdn.microsoft.com/en-us/library/aa457089.aspx\" rel=\"nofollow noreferrer\">link</a>:</p>\n\n<pre><code>string path;\npath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );\nMessageBox.Show( path );\n</code></pre>\n" }, { "answer_id": 253513, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 3, "selected": false, "text": "<p>A tad shorter:</p>\n\n<pre><code>AppDomain.Current.BaseDirectory\n</code></pre>\n" }, { "answer_id": 284435, "author": "John Sibly", "author_id": 1078, "author_profile": "https://Stackoverflow.com/users/1078", "pm_score": 4, "selected": false, "text": "<p>Try the implementation below. The CodeBase property is the most reliable way to get the location, and then the rest of the code converts it into standard Windows format (instead of a URI).</p>\n\n<pre><code>static public string AssemblyLoadDirectory\n{\n get\n {\n string codeBase = Assembly.GetCallingAssembly().CodeBase;\n UriBuilder uri = new UriBuilder(codeBase);\n string path = Uri.UnescapeDataString(uri.Path);\n return Path.GetDirectoryName(path);\n }\n}\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20007/" ]
For my apps, I store some configuration file in xml along with the assembly(exe), and something other temporary files for proccessing purpose. I found some quirk with `".\\"` and `Application.StartupPath`. I've been using ``` String configPath = ".\\config.xml"; ``` It works fine until I called `OpenFIleDialog` to open some files in other folders, the statement above failed. Apparently ".\" is referring to "CurrentDirectory", which changes every time when we browse to another folder. At some point, I was using ``` String configPath = Path.Combine(Application.StartupPath + "config.xml"); ``` At some point, when I need to execute this assembly from another folder by using `Process.Start()`, things start to fall apart. Apparently the working directory is not set properly, and `Application.StartupPath` is actually referring to working directory instead of the directory of which the assembly is executing, as I've assumed. So I have to resort to using ProcessInfo to setup the working directory to the assembly's directory. I also had problem with this when I was writing VSTO. So, my question is, what's the best, simplest and most assured way to get the current directory that the assembly is executing, without those quirks(or misunderstanding) that I've just mentioned? EDIT: I meant to get the directory which the assembly reside EDIT: According to MSDN on [AppDomain.BaseDirectory](http://msdn.microsoft.com/en-us/library/system.appdomain.basedirectory.aspx), it seems that it can be changes during runtime, which is what I don't want(Just to clarify, not that I don't want to allow changing BaseDirectory, but rather, when I retrieve it without knowing for sure whether it's been changed) EDIT: I've notice that a related question was posted much earlier. [What would cause the current directory of an executing app to change?](https://stackoverflow.com/questions/158219/what-would-cause-the-current-directory-of-an-executing-app-to-change) Thanks guys for the answer.
``` System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) ```
253,469
<p>I have a <code>CMFCRibbonStatusBar</code> in my mainframe to which I add a <code>CMFCRibbonButtonsGroup</code> which again has a <code>CMFCRibbonButton</code>. This button has the same ID as a menu entry.</p> <p>Creating the button is done as follows:</p> <pre><code>CMFCRibbonButtonsGroup* pBGroup = new CMFCRibbonButtonsGroup(); CMFCToolBarImages images; images.SetImageSize(CSize(32, 16)); // Non-square bitmaps if(images.Load(IDB_STATUSBAR_IMAGES)) { pBGroup-&gt;SetImages(&amp;images, NULL, NULL); } m_pStatusButton = new CMFCRibbonButton(ID_STATUS_SHOWSTATUS, _T(""), IMAGEINDEX_DEFAULTSTATUS); pBGroup-&gt;AddButton(m_pStatusButton); m_wndStatusBar.AddExtendedElement(pBGroup, _T("")); </code></pre> <p>I want to use this button as a status indicator.</p> <p>I want to display a tool tip in the following two cases:</p> <ul> <li>when the status changes and</li> <li>when the user moves the mouse over the button.</li> </ul> <p>I have no idea how to start in the first place. I have looked at the <code>ToolTipDemo</code> and <code>DlgToolTips</code> sample projects but couldn't figure out how to do it since all they do is display tooltips for the toolbar items or dialog buttons (<code>CWnd</code>-derived instead of <code>CMFCRibbonButton</code>).</p> <p>If you are familiar with the <code>ToolTipDemo</code> sample project: Since there seem to be several ways of doing things, I would prefer the tooltip to look like the "Extended Visual Manager-based" tool tip as <a href="http://img394.imageshack.us/my.php?image=tooltiptm7.png" rel="nofollow noreferrer">shown in this screenshot</a>.</p> <p>Thanks!</p>
[ { "answer_id": 505535, "author": "demoncodemonkey", "author_id": 61697, "author_profile": "https://Stackoverflow.com/users/61697", "pm_score": 3, "selected": true, "text": "<p>I don't think it's possible to show the tooltip without the mouse cursor being over the control. That's all done automatically.</p>\n\n<p>However if you want to have a nice looking tooltip like in your screenshot, you need to call <code>SetToolTipText</code> and <code>SetDescription</code>, like this:</p>\n\n<pre><code>CMFCRibbonButton* pBtn = new CMFCRibbonButton(12345, _T(\"\"), 1);\npBtn-&gt;SetToolTipText(\"This is the bold Title\");\npBtn-&gt;SetDescription(\"This is the not-so-bold Description\");\npGroup-&gt;AddButton(pBtn);\n</code></pre>\n" }, { "answer_id": 11353849, "author": "David Carr", "author_id": 695807, "author_profile": "https://Stackoverflow.com/users/695807", "pm_score": 0, "selected": false, "text": "<p>I am using <code>CMFCRibbonButton</code> controls within a <code>CMFCRibbonButtonGroup</code>, which is added to the <code>CMFCRibbonStatusBar</code>. Take note of the 4th parameter in the <code>CMFCRibbonButton()</code> constructor, <code>bAlwaysShowDescription</code>, as this seems to affect the behavior depending upon whether <code>SetDescription()</code> has been called.</p>\n\n<p>Specifically, if <code>SetDescription()</code> has not been called, it doesn't matter whether <code>bAlwaysShowDescription</code> is TRUE or FALSE - the tool tip is displayed (as I would expect). If <code>SetDescription()</code> is set and <code>bAlwaysShowDescription</code> is FALSE, when hovering over the button the tool tip is displayed with the description below it.</p>\n\n<p>What seems counterintuitive given the name of this <code>bAlwaysShowDescription</code> parameter, is that when this is TRUE and <code>SetDescription()</code> is set, <strong>NEITHER</strong> the tool tip nor the description appear. I wonder if this is related to this post:\n<a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/399646/cmfcribbonbutton-wont-show-tooltip-if-balwaysshowdescription-1\" rel=\"nofollow\">https://connect.microsoft.com/VisualStudio/feedback/details/399646/cmfcribbonbutton-wont-show-tooltip-if-balwaysshowdescription-1</a></p>\n\n<p>Hope this helps and you can achieve what you need with the different combinations of <code>bAlwaysShowDescription</code> parameter and whether <code>SetDescription()</code> is set.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27596/" ]
I have a `CMFCRibbonStatusBar` in my mainframe to which I add a `CMFCRibbonButtonsGroup` which again has a `CMFCRibbonButton`. This button has the same ID as a menu entry. Creating the button is done as follows: ``` CMFCRibbonButtonsGroup* pBGroup = new CMFCRibbonButtonsGroup(); CMFCToolBarImages images; images.SetImageSize(CSize(32, 16)); // Non-square bitmaps if(images.Load(IDB_STATUSBAR_IMAGES)) { pBGroup->SetImages(&images, NULL, NULL); } m_pStatusButton = new CMFCRibbonButton(ID_STATUS_SHOWSTATUS, _T(""), IMAGEINDEX_DEFAULTSTATUS); pBGroup->AddButton(m_pStatusButton); m_wndStatusBar.AddExtendedElement(pBGroup, _T("")); ``` I want to use this button as a status indicator. I want to display a tool tip in the following two cases: * when the status changes and * when the user moves the mouse over the button. I have no idea how to start in the first place. I have looked at the `ToolTipDemo` and `DlgToolTips` sample projects but couldn't figure out how to do it since all they do is display tooltips for the toolbar items or dialog buttons (`CWnd`-derived instead of `CMFCRibbonButton`). If you are familiar with the `ToolTipDemo` sample project: Since there seem to be several ways of doing things, I would prefer the tooltip to look like the "Extended Visual Manager-based" tool tip as [shown in this screenshot](http://img394.imageshack.us/my.php?image=tooltiptm7.png). Thanks!
I don't think it's possible to show the tooltip without the mouse cursor being over the control. That's all done automatically. However if you want to have a nice looking tooltip like in your screenshot, you need to call `SetToolTipText` and `SetDescription`, like this: ``` CMFCRibbonButton* pBtn = new CMFCRibbonButton(12345, _T(""), 1); pBtn->SetToolTipText("This is the bold Title"); pBtn->SetDescription("This is the not-so-bold Description"); pGroup->AddButton(pBtn); ```
253,475
<pre><code>struct elem { int i; char k; }; elem user; // compile error! struct elem user; // this is correct </code></pre> <p>In the above piece of code we are getting an error for the first declaration. But this error doesn't occur with a C++ compiler. In C++ we don't need to use the keyword struct again and again. <p>So why doesn't anyone update their C compiler, so that we can use structure without the keyword as in C++ ? <p>Why doesn't the C compiler developer remove some of the glitches of C, like the one above, and update with some advanced features without damaging the original concept of C? <p>Why it is the same old compiler not updated from 1970's ? <p>Look at visual studio etc.. It is frequently updated with new releases and for every new release we have to learn some new function usage (even though it is a problem we can cope up with it). We will also get updated with the new compiler if there is any. <p>Don't take this as a silly question. Why it is not possible? It could be developed without any incompatibility issues (without affecting the code that was developed on the present / old compiler) <p>Ok, lets develop the new C language, C+, which is in between C and C++ which removes all glitches of C and adds some advanced features from C++ while keeping it useful for specific applications like system level applications, embedded systems etc.</p>
[ { "answer_id": 253484, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>Because C is Standardized. Compiler could offer that feature and some do, but using it means that the source code doesn't follow the standard and could only be compiled on that vendor's compiler.</p>\n" }, { "answer_id": 253501, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>As already mentioned, C has a standard that needs to be adhered to. But can't you just write your code using slightly modified C syntax, but use a C++ compiler so that things like</p>\n\n<pre><code>struct elem\n{\n int i;\n char k;\n};\nelem user;\n</code></pre>\n\n<p>will compile?</p>\n" }, { "answer_id": 253509, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 2, "selected": false, "text": "<p>We have a typedef for exactly this purpose. \nAnd please do not change the standard we have enough compatibility problems already....</p>\n\n<p>@ Manoj Doubts comment<br>\nI have no problem with you or somebody else to define C+ or C- or Cwhatever unless you don't touch C :)<br>\nI still need a language that capable to complete my task - have a <strong>same</strong> piece of code (not a small one) to be able to run on tens of Operating system compiled by significant number of different compilers and be able to run on tens of different hardware platform at the moment there is only one language that allow me complete my task and i prefer not to experiment with this ability :) Especially for reason you provided. Do you really think that ability to write</p>\n\n<pre><code>foo test;\n</code></pre>\n\n<p>instead </p>\n\n<pre><code>struct foo test;\n</code></pre>\n\n<p>will make you code better from any point of view ? </p>\n" }, { "answer_id": 253519, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 5, "selected": true, "text": "<p>Because it takes years for a new Standard to evolve.\nThey are working on a new C++ Standard (<a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x\" rel=\"noreferrer\">C++0x</a>), and also on a new C standard (C1x), but if you remember that it usually takes between 5 and 10 years for each iteration, i don't expect to see it before 2010 or so.</p>\n\n<p>Also, just like in any democracy, there are compromises in a Standard. You got the hardliners who say \"If you want all that fancy syntactic sugar, go for a toy language like Java or C# that takes you by the hand and even buys you a lollipop\", whereas others say \"The language needs to be easier and less error-prone to survive in these days or rapidly reducing development cycles\".</p>\n\n<p>Both sides are partially right, so standardization is a very long battle that takes years and will lead to many compromises. That applies to everything where multiple big parties are involved, it's not just limited to C/C++.</p>\n" }, { "answer_id": 253542, "author": "Miro Kropacek", "author_id": 21009, "author_profile": "https://Stackoverflow.com/users/21009", "pm_score": 4, "selected": false, "text": "<pre><code>typedef struct\n{\n int i;\n char k;\n} elem;\n\nelem user;\n</code></pre>\n\n<p>will work nicely. as other said, it's about standard -- when you implement this in VS2008, you can't use it in GCC and when you implement this even in GCC, you certainly not compile in something else. Method above will work everywhere.</p>\n\n<p>On the other side -- when we have C99 standard with bool type, declarations in a for() cycle and in the middle of blocks -- why not this feature as well?</p>\n" }, { "answer_id": 253582, "author": "Malkocoglu", "author_id": 31152, "author_profile": "https://Stackoverflow.com/users/31152", "pm_score": 1, "selected": false, "text": "<p>Well,</p>\n\n<p>1 - None of the compilers that are in use today are from the 70s...</p>\n\n<p>2 - There are standarts for both C and C++ languages and compilers are developed according to those standarts. They can't just change some behaviour !</p>\n\n<p>3 - What happens if you develop on VS2008 and then try to compile that code by another compiler whose last version was released 10 years ago ?</p>\n\n<p>4 - What happens when you play with the options on the C/C++ / Language tab ?</p>\n\n<p>5 - Why don't Microsoft compilers target all the possible processors ? They only target x86, x86_64 and Itanium, that's all...</p>\n\n<p>6 - Believe me , this is not even considered as a problem !!!</p>\n" }, { "answer_id": 253594, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>Most people still using C use it because they're either:</p>\n\n<ul>\n<li>Targeting a very specific platform (ie, embedded) and therefore must use the compiler provided by that platform vendor</li>\n<li>Concerned about portability, in which case a non-standard compiler would defeat the purpose</li>\n<li>Very comfortable with plain C and see no reason to change, in which case they just don't want to.</li>\n</ul>\n" }, { "answer_id": 253633, "author": "John Carter", "author_id": 8331, "author_profile": "https://Stackoverflow.com/users/8331", "pm_score": 0, "selected": false, "text": "<p>You don't need to develop a new language if you want to use C with C++ typedefs and the like (but without classes, templates etc).</p>\n\n<p>Just write your C-like code and use the C++ compiler.</p>\n" }, { "answer_id": 253814, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": false, "text": "<p>First and foremost, compilers need to support the standard. That's true even if the standard seems awkward in hindsight. Second, compiler vendors do add extensions. For example, many compilers support this:</p>\n\n<pre><code>(char *) p += 100;\n</code></pre>\n\n<p>to move a pointer by 100 bytes instead of 100 of whatever type <code>p</code> is a pointer to. Strictly speaking that's non-standard because the cast removes the lvalue-ness of <code>p</code>.</p>\n\n<p>The problem with non-standard extensions is that you can't count on them. That's a big problem if you ever want to switch compilers, make your code portable, or use third-party tools.</p>\n\n<p>C is largely a victim of its own success. One of the main reasons to use C is portability. There are C compilers for virtually every hardware platform and OS in existence. If you want to be able to run your code <em>anywhere</em> you write it in C. This creates enormous inertia. It's almost impossible to change anything without sacrificing one of the best things about using the language in the first place.</p>\n\n<p>The result for software developers is that you may need to write to the lowest common denominator, typically ANSI C (C89). For example: Parrot, the virtual machine that will run the next version of Perl, is being written in ANSI C. Perl6 will have an enormously powerful and expressive syntax with some mind-bending concepts baked right into the language. The implementation, though, is being built using a language that is almost the complete opposite. The reason is that this will make it possible for perl to run anywhere: PCs, Macs, Windows, Linux, Unix, VAX, BSD...</p>\n" }, { "answer_id": 254300, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>Actually, many C compilers do add features - doesn't pretty much every C compiler support C++ style <code>//</code> comments?</p>\n\n<p>Most of the features added to updates of the C standard (C99 being the most recent) come from extensions that 'caught on'.</p>\n\n<p>For example, even though the compiler I'm using right now on an embedded platform does not claim to conform to the C99 standard (and it is missing quite a bit from it), it does add the following extensions (all of which are borrowed from C++ or C99) to it's 'C90' support:</p>\n\n<ul>\n<li>declarations mixed with statements</li>\n<li>anonymous structs and unions</li>\n<li>inline</li>\n<li>declaration in the for loop initialization expression</li>\n<li>and, of course, C++ style <code>//</code> comments</li>\n</ul>\n\n<p>The problem I run into with this is that when I try to compile those files using MSVC (either for testing or because the code is useful on more than just the embedded platform), it'll choke on most of them (I'm honestly not sure about anonymous structs/unions).</p>\n\n<p>So, extensions do get added to C compilers, it's just that they're done at different rates and in different ways (so code using them becomes more difficult to port) and the process of moving them into a standard occurs at a near glacial pace.</p>\n" }, { "answer_id": 254848, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 0, "selected": false, "text": "<p>As far as new functionality in new releases go, Visual C++ is not completely standard-conforming (see <a href=\"http://msdn.microsoft.com/en-us/library/x84h5b78.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/x84h5b78.aspx</a>), By the time Visual Studio 2010 is out, the next C++ standard will likely have been approved, giving the VC++ team more functionality to change.</p>\n\n<p>There are also changes to the Microsoft libraries (which have little or nothing to do with the standard), and to what the compiler puts out (C++/CLI). There's plenty of room for changes without trying to deviate from the standard.</p>\n\n<p>Nor do you need anything like C+. Just write in C, use whatever C++ features you like, and compile as C++. One of the Bjarne Stroustrup's original design goals for C++ was to make it unnecessary to write anything in C. It should compile perfectly efficiently provided you limit the C++ features you use (and even then will compile very efficiently; modern C++ compilers do a very good job).</p>\n\n<p>And the unanswered question: Why would you want to use non-standard C, when you could write standard C or standard C++ with almost equal facility? </p>\n" }, { "answer_id": 254878, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 0, "selected": false, "text": "<p>This sounds like the <a href=\"http://en.wikipedia.org/wiki/Embrace_extend_and_extinguish\" rel=\"nofollow noreferrer\">embrace and extend</a> concept.\nLife under your scenario.</p>\n\n<ol>\n<li>I develop code using a C compiler that has the C \"glitches\" removed.</li>\n<li>I move to a different platform with another C compiler that has the C \"glitches\" removed, but in a slightly different way.</li>\n<li>My code doesn't compile or runs differently on the new platform, I waste time \"porting\" my code to the new platform.</li>\n</ol>\n\n<p>Some vendors actually like to fix \"glitches\" because this tends to lock people into a single platform.</p>\n" }, { "answer_id": 255507, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 3, "selected": false, "text": "<p>This \"feature\" will <strong>never</strong> be adopted by future C standards for one reason only: it would badly break backward compatibility. In C, struct tags have separate namespaces to normal identifiers, and this may or may not be considered a feature. Thus, this fragment:</p>\n\n<pre><code>struct elem\n{\n int foo;\n};\n\nint elem;\n</code></pre>\n\n<p>Is perfectly fine in C, because these two elems are in separate namespaces. If a future standard allowed you to declare a struct elem without a struct qualifier or appropriate typedef, the above program would fail because elem is being used as an identifier for an int.</p>\n\n<p>An example where a future C standard does in fact break backward compatibiity is when C99 disallowed a function without an explicit return type, ie:</p>\n\n<pre><code>foo(void); /* declare a function foo that takes no parameters and returns an int */\n</code></pre>\n\n<p>This is illegal in C99. However, it is trivial to make this C99 compliant just by adding an int return type. It is not so trivial to \"fix\" C programs if suddenly struct tags didn't have a separate namespace.</p>\n" }, { "answer_id": 258644, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The following program outputs \"1\" when compiled as standard C or something else, probably 2, when compiled as C++ or your suggested syntax. That's why the C language can't make this change, it would give new meaning to existing code. And that's bad!</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\ntypedef struct\n{\n int a;\n int b;\n} X;\n\nint main(void)\n{\n union X\n {\n int a;\n int b;\n };\n\n X x;\n x.a = 1;\n x.b = 2;\n\n printf(\"%d\\n\", x.a);\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 258672, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you want to write in standard C, follow the standards. That's it.</p>\n\n<p>If you want more freedom use C# or C++.NET or anything else your hardware supports.</p>\n" }, { "answer_id": 261061, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 3, "selected": false, "text": "<p>I've found that when I've implemented non-standard extensions to C and C++, even when people request them, they do not get used. The C and C++ world definitely revolves around strict standard compliance. Many of these extensions and improvements have found fertile ground in the D programming language.</p>\n\n<p>Walter Bright, Digital Mars</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
``` struct elem { int i; char k; }; elem user; // compile error! struct elem user; // this is correct ``` In the above piece of code we are getting an error for the first declaration. But this error doesn't occur with a C++ compiler. In C++ we don't need to use the keyword struct again and again. So why doesn't anyone update their C compiler, so that we can use structure without the keyword as in C++ ? Why doesn't the C compiler developer remove some of the glitches of C, like the one above, and update with some advanced features without damaging the original concept of C? Why it is the same old compiler not updated from 1970's ? Look at visual studio etc.. It is frequently updated with new releases and for every new release we have to learn some new function usage (even though it is a problem we can cope up with it). We will also get updated with the new compiler if there is any. Don't take this as a silly question. Why it is not possible? It could be developed without any incompatibility issues (without affecting the code that was developed on the present / old compiler) Ok, lets develop the new C language, C+, which is in between C and C++ which removes all glitches of C and adds some advanced features from C++ while keeping it useful for specific applications like system level applications, embedded systems etc.
Because it takes years for a new Standard to evolve. They are working on a new C++ Standard ([C++0x](http://en.wikipedia.org/wiki/C%2B%2B0x)), and also on a new C standard (C1x), but if you remember that it usually takes between 5 and 10 years for each iteration, i don't expect to see it before 2010 or so. Also, just like in any democracy, there are compromises in a Standard. You got the hardliners who say "If you want all that fancy syntactic sugar, go for a toy language like Java or C# that takes you by the hand and even buys you a lollipop", whereas others say "The language needs to be easier and less error-prone to survive in these days or rapidly reducing development cycles". Both sides are partially right, so standardization is a very long battle that takes years and will lead to many compromises. That applies to everything where multiple big parties are involved, it's not just limited to C/C++.
253,490
<p>I have a problem with the <a href="http://freetextbox.com/" rel="nofollow noreferrer">FreeTextBox</a> rich Text Editor in my ASP.NET site. The problem occurs when I access the site with firefox, and I have a freetextbox instance in a hidden div. The hidden div might also be an AJAX Tab Panel. The actual problem is that when the page loads it throws an uncaught exception (firebug shows the StoreHtml() function) and halts the postback!! </p> <p>Is anywhere of the problem and a solution for it?? </p> <p>Thanks</p>
[ { "answer_id": 254064, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Firefox has a problem with being inside anything with a style of display:none. What I did was to use a div with a zIndex that hid the div until I needed it displayed. I would start there. </p>\n" }, { "answer_id": 258141, "author": "Nikos Steiakakis", "author_id": 932, "author_profile": "https://Stackoverflow.com/users/932", "pm_score": 0, "selected": false, "text": "<p>Thanks for your answer, however my problem currently is that the FreeTextBox is inside an AJAX Tab Panel, therefore I would have to reconstruct the whole tab functionality in order to do so, and I do not have adequate time! </p>\n\n<p>For what it's worth, I am close to a solution (I think) by setting the .ReadOnly attribute of the FTB to true and then setting it back to false on the controlo .PreRender. It works for the first time the page loads, so now I have to figure out how to implement this properly for every postback. </p>\n\n<p>I will post the solution if I find it!</p>\n\n<p>Thanks anyway!</p>\n" }, { "answer_id": 258210, "author": "Vegard Larsen", "author_id": 1606, "author_profile": "https://Stackoverflow.com/users/1606", "pm_score": 3, "selected": true, "text": "<p>I recently met a similar problem with jQuery UI tabs. What you need to do is to change the CSS for hidden tabs to something like:</p>\n\n<pre><code>.hiddentab\n{\n position: absolute;\n left: -99999999999999;\n}\n</code></pre>\n\n<p>This puts hidden tabs far to the left, and in absolute position mode this does not cause horizontal scroll bars to appear. When the tab is shown, simply remove the hiddentab class from the tab element.</p>\n\n<p>This will work if the problem is related to Firefox' odd behavior with display: none.</p>\n" }, { "answer_id": 268790, "author": "Nikos Steiakakis", "author_id": 932, "author_profile": "https://Stackoverflow.com/users/932", "pm_score": 2, "selected": false, "text": "<p>I have found another solution to the problem in case anyone is looking for it. What I did was use javascript to override the OnSubmit function of the form, thus catching the exception that caused the problem and going on with the rest of the code. </p>\n\n<p>However the solution is kind of \"hack\" since it does not cover every situation. I found the solution in the <a href=\"http://freetextbox.com/forums/permalink/3933/8604/ShowThread.aspx#8604\" rel=\"nofollow noreferrer\">FreeTextBox forum</a> and tried it out and it works. The only difference in my code is that I return true in the end of the override function:</p>\n\n<pre><code>function OvrdSubmit()\n{\n var ftbSubmit=document.forms[0].onsubmit;\n if (typeof(ftbSubmit) == 'function')\n {\n document.forms[0].onsubmit = function()\n {\n try{ftbSubmit();}\n catch(ex){}\n }\n }\n\n // We are ok\n return true;\n}\n</code></pre>\n\n<p>Since my site is an ASP.NET site I also had to add this line in the Page_Load():</p>\n\n<pre><code>ClientScript.RegisterOnSubmitStatement(this.GetType(), String.Concat(this.ClientID, \"_OnSubmit\"), \"javascript: return OvrdSubmit();\");\n</code></pre>\n\n<p>Hope it helps anyone with the same problem.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932/" ]
I have a problem with the [FreeTextBox](http://freetextbox.com/) rich Text Editor in my ASP.NET site. The problem occurs when I access the site with firefox, and I have a freetextbox instance in a hidden div. The hidden div might also be an AJAX Tab Panel. The actual problem is that when the page loads it throws an uncaught exception (firebug shows the StoreHtml() function) and halts the postback!! Is anywhere of the problem and a solution for it?? Thanks
I recently met a similar problem with jQuery UI tabs. What you need to do is to change the CSS for hidden tabs to something like: ``` .hiddentab { position: absolute; left: -99999999999999; } ``` This puts hidden tabs far to the left, and in absolute position mode this does not cause horizontal scroll bars to appear. When the tab is shown, simply remove the hiddentab class from the tab element. This will work if the problem is related to Firefox' odd behavior with display: none.
253,492
<p>I was looking at the Java code for <code>LinkedList</code> and noticed that it made use of a static nested class, <code>Entry</code>.</p> <pre><code>public class LinkedList&lt;E&gt; ... { ... private static class Entry&lt;E&gt; { ... } } </code></pre> <p>What is the reason for using a static nested class, rather than an normal inner class?</p> <p>The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation. </p> <p>But I thought there might be other reasons, maybe performance. What might it be?</p> <p>Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html" rel="noreferrer">http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html</a></p>
[ { "answer_id": 253507, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "<p>To my mind, the question ought to be the other way round whenever you see an inner class - does it <em>really</em> need to be an inner class, with the extra complexity and the implicit (rather than explicit and clearer, IMO) reference to an instance of the containing class?</p>\n\n<p>Mind you, I'm biased as a C# fan - C# doesn't have the equivalent of inner classes, although it does have nested types. I can't say I've missed inner classes yet :)</p>\n" }, { "answer_id": 253514, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 2, "selected": false, "text": "<p>One of the reasons for static vs. normal have to do with classloading. You cannot instantiate an inner class in the constructor of it's parent.</p>\n\n<p>PS: I've always understood 'nested' and 'inner' to be interchangeable. There may be subtle nuances in the terms but most Java developers would understand either.</p>\n" }, { "answer_id": 253515, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I don't know about performance difference, but as you say, static nested class is not a part of an instance of the enclosing class. Seems just simpler to create a static nested class unless you really need it to be an inner class.</p>\n\n<p>It's a bit like why I always make my variables final in Java - if they're not final, I know there's something funny going on with them. If you use an inner class instead of a static nested class, there should be a good reason.</p>\n" }, { "answer_id": 253521, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 9, "selected": true, "text": "<p>The Sun page you link to has some key differences between the two:</p>\n\n<blockquote>\n <p>A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.<br>\n ...</p>\n \n <p>Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. <strong>In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.</strong></p>\n</blockquote>\n\n<p>There is no need for <code>LinkedList.Entry</code> to be top-level class as it is <em>only</em> used by <code>LinkedList</code> (there are some other interfaces that also have static nested classes named <code>Entry</code>, such as <code>Map.Entry</code> - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.</p>\n\n<p>As <a href=\"https://stackoverflow.com/a/253507/4249\">Jon Skeet points out</a>, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.</p>\n" }, { "answer_id": 253541, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.</p>\n\n<p>As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a \"struct\" in C, consider making it static.</p>\n" }, { "answer_id": 253575, "author": "Vinze", "author_id": 26859, "author_profile": "https://Stackoverflow.com/users/26859", "pm_score": 2, "selected": false, "text": "<p>Simple example : </p>\n\n<pre><code>package test;\n\npublic class UpperClass {\npublic static class StaticInnerClass {}\n\npublic class InnerClass {}\n\npublic static void main(String[] args) {\n // works\n StaticInnerClass stat = new StaticInnerClass();\n // doesn't compile\n InnerClass inner = new InnerClass();\n}\n}\n</code></pre>\n\n<p>If non-static the class cannot be instantiated exept in an instance of the upper class (so not in the example where main is a static function)</p>\n" }, { "answer_id": 253690, "author": "Leigh", "author_id": 26061, "author_profile": "https://Stackoverflow.com/users/26061", "pm_score": 5, "selected": false, "text": "<p>There are non-obvious memory retention issues to take into account here. Since a non-static inner class maintains an implicit reference to it's 'outer' class, if an instance of the inner class is strongly referenced, then the outer instance is strongly referenced too. This can lead to some head-scratching when the outer class is not garbage collected, even though <em>it appears</em> that nothing references it.</p>\n" }, { "answer_id": 8257808, "author": "The Gun", "author_id": 1064017, "author_profile": "https://Stackoverflow.com/users/1064017", "pm_score": 1, "selected": false, "text": "<p>Non static inner classes can result in memory leaks while static inner class will protect against them. If the outer class holds considerable data, it can lower the performance of the application.</p>\n" }, { "answer_id": 20129805, "author": "John29", "author_id": 2324685, "author_profile": "https://Stackoverflow.com/users/2324685", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html\" rel=\"noreferrer\">http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html</a>:</p>\n\n<blockquote>\n <p>Use a non-static nested class (or inner class) if you require access\n to an enclosing instance's non-public fields and methods. Use a static\n nested class if you don't require this access.</p>\n</blockquote>\n" }, { "answer_id": 20608594, "author": "user1923551", "author_id": 1923551, "author_profile": "https://Stackoverflow.com/users/1923551", "pm_score": 4, "selected": false, "text": "<p>static nested class is just like any other outer class, as it doesn't have access to outer class members.</p>\n\n<p>Just for packaging convenience we can club static nested classes into one outer class for readability purpose. Other than this there is no other use case of static nested class.</p>\n\n<p>Example for such kind of usage, you can find in Android R.java (resources) file.\nRes folder of android contains layouts (containing screen designs), drawable folder (containing images used for project), values folder (which contains string constants), etc..</p>\n\n<p>Sine all the folders are part of Res folder, android tool generates a R.java (resources) file which internally contains lot of static nested classes for each of their inner folders.</p>\n\n<p><strong>Here is the look and feel of R.java file generated in android:</strong>\nHere they are using only for packaging convenience. </p>\n\n<pre><code>/* AUTO-GENERATED FILE. DO NOT MODIFY.\n *\n * This class was automatically generated by the\n * aapt tool from the resource data it found. It\n * should not be modified by hand.\n */\n\npackage com.techpalle.b17_testthird;\n\npublic final class R {\n public static final class drawable {\n public static final int ic_launcher=0x7f020000;\n }\n public static final class layout {\n public static final int activity_main=0x7f030000;\n }\n public static final class menu {\n public static final int main=0x7f070000;\n }\n public static final class string {\n public static final int action_settings=0x7f050001;\n public static final int app_name=0x7f050000;\n public static final int hello_world=0x7f050002;\n }\n}\n</code></pre>\n" }, { "answer_id": 35716726, "author": "Gaurav Tiwari", "author_id": 5961515, "author_profile": "https://Stackoverflow.com/users/5961515", "pm_score": -1, "selected": false, "text": "<p>Adavantage of inner class--</p>\n\n<ol>\n<li>one time use</li>\n<li>supports and improves encapsulation</li>\n<li>readibility </li>\n<li>private field access</li>\n</ol>\n\n<p>Without existing of outer class inner class will not exist.</p>\n\n<pre><code>class car{\n class wheel{\n\n }\n}\n</code></pre>\n\n<p>There are four types of inner class.</p>\n\n<ol>\n<li>normal inner class</li>\n<li>Method Local Inner class</li>\n<li>Anonymous inner class</li>\n<li>static inner class</li>\n</ol>\n\n<p>point --- </p>\n\n<ol>\n<li>from static inner class ,we can only access static member of outer class.</li>\n<li>Inside inner class we cananot declare static member .</li>\n<li><p>inorder to invoke normal inner class in static area of outer class.</p>\n\n<p><code>Outer 0=new Outer();\nOuter.Inner i= O.new Inner();</code></p></li>\n<li><p>inorder to invoke normal inner class in instance area of outer class.</p>\n\n<p><code>Inner i=new Inner();</code></p></li>\n<li><p>inorder to invoke normal inner class in outside of outer class.</p>\n\n<p><code>Outer 0=new Outer();\nOuter.Inner i= O.new Inner();</code></p></li>\n<li><p>inside Inner class This pointer to inner class.</p>\n\n<p><code>this.member-current inner class\nouterclassname.this--outer class</code></p></li>\n<li><p>for inner class applicable modifier is -- public,default, </p>\n\n<p><code>final,abstract,strictfp,+private,protected,static</code></p></li>\n<li><p>outer$inner is the name of inner class name.</p></li>\n<li><p>inner class inside instance method then we can acess static and instance field of outer class.</p></li>\n</ol>\n\n<p>10.inner class inside static method then we can access only static field of </p>\n\n<p>outer class.</p>\n\n<pre><code>class outer{\n\n int x=10;\n static int y-20;\n\n public void m1() {\n int i=30;\n final j=40;\n\n class inner{\n\n public void m2() {\n // have accees x,y and j\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 40192585, "author": "JenkinsY", "author_id": 6088463, "author_profile": "https://Stackoverflow.com/users/6088463", "pm_score": 0, "selected": false, "text": "<p>Using a static nested class rather than non-static one may save spaces in some cases. For example: implementing a <code>Comparator</code> inside a class, say Student.</p>\n\n<pre><code>public class Student {\n public static final Comparator&lt;Student&gt; BY_NAME = new ByName();\n private final String name;\n ...\n private static class ByName implements Comparator&lt;Student&gt; {\n public int compare() {...}\n }\n}\n</code></pre>\n\n<p>Then the <code>static</code> ensures that the Student class has only one Comparator, rather than instantiate a new one every time a new student instance is created. </p>\n" }, { "answer_id": 40267521, "author": "seenimurugan", "author_id": 745401, "author_profile": "https://Stackoverflow.com/users/745401", "pm_score": 4, "selected": false, "text": "<p>Static inner class is used in the builder pattern. Static inner class can instantiate it's outer class which has only private constructor. <strong>You can not do the same with the inner class as you need to have object of the outer class created prior to accessing the inner class.</strong></p>\n<pre><code>class OuterClass {\n private OuterClass(int x) {\n System.out.println(&quot;x: &quot; + x);\n }\n \n static class InnerClass {\n public static void test() {\n OuterClass outer = new OuterClass(1);\n }\n }\n}\n\npublic class Test {\n public static void main(String[] args) {\n OuterClass.InnerClass.test();\n // OuterClass outer = new OuterClass(1); // It is not possible to create outer instance from outside.\n }\n}\n</code></pre>\n<p>This will output x: 1</p>\n" }, { "answer_id": 63950042, "author": "Sahil Gupta", "author_id": 2484748, "author_profile": "https://Stackoverflow.com/users/2484748", "pm_score": 1, "selected": false, "text": "<ol>\n<li><p>JVM knows no nested classes. Nesting is just syntactic sugar.</p>\n<p>Below images shows Java file:</p>\n<p><a href=\"https://i.stack.imgur.com/ql56F.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ql56F.png\" alt=\"enter image description here\" /></a></p>\n<p>Below images show class files representation of the java file :</p>\n<p><a href=\"https://i.stack.imgur.com/YztK8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YztK8.png\" alt=\"enter image description here\" /></a></p>\n<p>Notice that 2 class files are generated, one for parent and another for nested class.</p>\n</li>\n<li><p>Non-static nested class' objects have access to the enclosing scope. That access to the enclosing scope is maintained by holding an implicit reference of the enclosing scope object in the nested object</p>\n</li>\n<li><p>Nested class is a way to represent the intent that the nested class type represents a component of the parent class.</p>\n<pre><code>public class Message {\n\nprivate MessageType messageType; // component of parent class\n\npublic enum MessageType {\n SENT, RECEIVE;\n}\n}\n\n\n\nclass Otherclass {\n\npublic boolean isSent(Message message) {\n if (message.getMessageType() == MessageType.SENT) { // accessible at other places as well\n return true;\n }\n return false;\n}\n}\n</code></pre>\n</li>\n<li><p>private static nested class represents Point#3 &amp; the fact the nested type can only be the subcomponent to the parent class. It can't be used separately.</p>\n<pre><code>public class Message {\n\n private Content content; // Component of message class\n\n private static class Content { // can only be a component of message class\n\n private String body;\n private int sentBy;\n\n public String getBody() {\n return body;\n }\n\n public int getSentBy() {\n return sentBy;\n }\n\n}\n}\n\nclass Message2 {\n private Message.Content content; // Not possible\n}\n</code></pre>\n</li>\n<li><p>More details <a href=\"https://blog.jooq.org/2015/02/02/top-5-use-cases-for-nested-types/\" rel=\"nofollow noreferrer\">here</a>.</p>\n</li>\n</ol>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10171/" ]
I was looking at the Java code for `LinkedList` and noticed that it made use of a static nested class, `Entry`. ``` public class LinkedList<E> ... { ... private static class Entry<E> { ... } } ``` What is the reason for using a static nested class, rather than an normal inner class? The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation. But I thought there might be other reasons, maybe performance. What might it be? Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: <http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html>
The Sun page you link to has some key differences between the two: > > A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. > > ... > > > Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. **In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.** > > > There is no need for `LinkedList.Entry` to be top-level class as it is *only* used by `LinkedList` (there are some other interfaces that also have static nested classes named `Entry`, such as `Map.Entry` - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach. As [Jon Skeet points out](https://stackoverflow.com/a/253507/4249), I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.
253,517
<p>I want to create a subclass of TabPage that contains some control, and I want to control the layout and properties of those controls through the designer. However, if I open my subclass in the designer, I can't position them like I could on a UserControl. I don't want to have to create a TabPage with an UserControl instance on it, I want to design the TabPage directly.</p> <p>How do I do that? I've tried changing the Designer and DesignerCategory attributes, but I haven't found any values that help.</p>
[ { "answer_id": 254210, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 3, "selected": false, "text": "<p>I've had a similar problem in the past.</p>\n\n<p>What i did first was switch from inheriting Usercontrol to tabpage like so</p>\n\n<p>class UserInterface : UserControl // Do designer bit then change it to </p>\n\n<p>class UserInterface : TabPage</p>\n\n<p>Second i Just put all my controls and stuff in the usercontrol and docked that into a tabpage.</p>\n\n<p>third i've made a generic class that takes any usercontrol and does the docking automatically.</p>\n\n<p>so you can take your 'UserInterface' class and just get a type that you can add to a System.Windows.Forms.TabControl</p>\n\n<pre><code>public class UserTabControl&lt;T&gt; : TabPage\n where T : UserControl, new ()\n{\n private T _userControl;\n public T UserControl \n { \n get{ return _userControl;}\n set\n { \n _userControl = value;\n OnUserControlChanged(EventArgs.Empty);\n }\n }\n public event EventHandler UserControlChanged;\n protected virtual void OnUserControlChanged(EventArgs e)\n {\n //add user control docked to tabpage\n this.Controls.Clear(); \n UserControl.Dock = DockStyle.Fill;\n this.Controls.Add(UserControl);\n\n if (UserControlChanged != null)\n {\n UserControlChanged(this, e);\n }\n }\n\n public UserTabControl() : this(\"UserTabControl\")\n {\n }\n\n public UserTabControl(string text) \n : this( new T(),text )\n {\n }\n\n public UserTabControl(T userControl) \n : this(userControl, userControl.Name)\n {\n }\n\n public UserTabControl(T userControl, string tabtext)\n : base(tabtext)\n {\n InitializeComponent();\n UserControl = userControl; \n }\n\n private void InitializeComponent()\n {\n this.SuspendLayout();\n // \n // UserTabControl\n // \n\n this.BackColor = System.Drawing.Color.Transparent;\n this.Padding = new System.Windows.Forms.Padding(3);\n this.UseVisualStyleBackColor = true;\n this.ResumeLayout(false);\n }\n}\n</code></pre>\n" }, { "answer_id": 254667, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 1, "selected": false, "text": "<p>I handle this by designing the pages themselves as individual forms, which are then hosted inside tab pages at runtime.</p>\n\n<p>How do you put a form inside a <code>TabPage</code>?</p>\n\n<pre><code>form.TopLevel = false;\nform.Parent = tabPage;\nform.FormBorderStyle = FormBorderStyle.None; // otherwise you get a form with a \n // title bar inside the tab page, \n // which is a little odd\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I want to create a subclass of TabPage that contains some control, and I want to control the layout and properties of those controls through the designer. However, if I open my subclass in the designer, I can't position them like I could on a UserControl. I don't want to have to create a TabPage with an UserControl instance on it, I want to design the TabPage directly. How do I do that? I've tried changing the Designer and DesignerCategory attributes, but I haven't found any values that help.
I've had a similar problem in the past. What i did first was switch from inheriting Usercontrol to tabpage like so class UserInterface : UserControl // Do designer bit then change it to class UserInterface : TabPage Second i Just put all my controls and stuff in the usercontrol and docked that into a tabpage. third i've made a generic class that takes any usercontrol and does the docking automatically. so you can take your 'UserInterface' class and just get a type that you can add to a System.Windows.Forms.TabControl ``` public class UserTabControl<T> : TabPage where T : UserControl, new () { private T _userControl; public T UserControl { get{ return _userControl;} set { _userControl = value; OnUserControlChanged(EventArgs.Empty); } } public event EventHandler UserControlChanged; protected virtual void OnUserControlChanged(EventArgs e) { //add user control docked to tabpage this.Controls.Clear(); UserControl.Dock = DockStyle.Fill; this.Controls.Add(UserControl); if (UserControlChanged != null) { UserControlChanged(this, e); } } public UserTabControl() : this("UserTabControl") { } public UserTabControl(string text) : this( new T(),text ) { } public UserTabControl(T userControl) : this(userControl, userControl.Name) { } public UserTabControl(T userControl, string tabtext) : base(tabtext) { InitializeComponent(); UserControl = userControl; } private void InitializeComponent() { this.SuspendLayout(); // // UserTabControl // this.BackColor = System.Drawing.Color.Transparent; this.Padding = new System.Windows.Forms.Padding(3); this.UseVisualStyleBackColor = true; this.ResumeLayout(false); } } ```
253,544
<p>I have been reading the post here:</p> <p><a href="http://encosia.com/2008/10/04/using-jquery-to-enhance-aspnet-ajax-progress-indication/" rel="nofollow noreferrer">http://encosia.com/2008/10/04/using-jquery-to-enhance-aspnet-ajax-progress-indication/</a></p> <p>But it wants to use the following object:</p> <pre><code>Sys.WebForms.PageRequestManager.getInstance() </code></pre> <p>Which doesn't exist when using the MVC AJAX code. Has anyone tried to hook when the postback ends from MVC AJAX to know when to unblock the UI?</p>
[ { "answer_id": 253526, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 5, "selected": true, "text": "<p>NO. numerical primary keys will not reused, except you specify them manually(you should really avoid this!)</p>\n" }, { "answer_id": 253530, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 2, "selected": false, "text": "<p>Depends on the auto-numbering system. If you're using a sequence of any kind, the numbers of deleted records will not get reused, as the sequence does not know about them.</p>\n" }, { "answer_id": 253536, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Generally, no, the numbers are not reused.</p>\n\n<p>However, you can -- in products like Oracle -- specify a sequence generator which cycles around and will reuse numbers. </p>\n\n<p>Whether those are numbers of deleted records or not is your applications's problem.</p>\n" }, { "answer_id": 253540, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 1, "selected": false, "text": "<p>Not specifically. If the key is being read from a sequence or autoincrementing identity column the sequence will just plug along and produce the next value. However, you can deactivate this (<code>set identity_insert on</code> on SQL Server) and put any number you want in the column as long as it doesn't violate the uniqueness constraint.</p>\n" }, { "answer_id": 253543, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 1, "selected": false, "text": "<p>This question needs to be made more precise:</p>\n\n<p>... \"with Oracle Sequences\"</p>\n\n<p>... \"with MySQL autonumber columns\"</p>\n\n<p>... etc...</p>\n" }, { "answer_id": 253554, "author": "DiningPhilanderer", "author_id": 30934, "author_profile": "https://Stackoverflow.com/users/30934", "pm_score": 1, "selected": false, "text": "<p>As long as you create the table correctly you will not reuse numbers.\nHowever you can RESEED the identity column (IN MSSQL anyway) by using the following:</p>\n\n<p>-- Enter the number of the last valid entry in the table not the next number to be used</p>\n\n<p>DBCC CHECKIDENT ([TableName], RESEED, [NumberYouWantToStartAt])</p>\n\n<p>This is of course insane... and should never be done :)</p>\n" }, { "answer_id": 253580, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "<p>MySQL will not reuse IDs unless you <code>truncate</code> the table or <code>delete from</code> the table with no <code>where</code> clause (in which case MySQL, internally, simply does a <code>truncate</code>).</p>\n" }, { "answer_id": 253591, "author": "Martin Bøgelund", "author_id": 18968, "author_profile": "https://Stackoverflow.com/users/18968", "pm_score": 3, "selected": false, "text": "<p>AFAIK, this <em>could</em> happen in MySQL:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html\" rel=\"noreferrer\">How AUTO_INCREMENT Handling Works in InnoDB</a>:</p>\n\n<blockquote>\n <p>InnoDB uses the in-memory auto-increment counter as long as the server runs. When the server is stopped and restarted, InnoDB reinitializes the counter for each table for the first INSERT to the table, as described earlier.</p>\n</blockquote>\n\n<p><a href=\"http://bugs.mysql.com/bug.php?id=8402\" rel=\"noreferrer\">After a restart of server. Innodb reuse previously generated auto_increment values.\n</a>:</p>\n\n<blockquote>\n <p>Suggested fix:\n innodb table should not lose the track of next number for auto_increment column after\n restart.</p>\n</blockquote>\n" }, { "answer_id": 254819, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 0, "selected": false, "text": "<p>Yeah, it really depends on the way you generate the id.</p>\n\n<p>For example if you are using a GUID as the primary key, most implementations of getting a random new Guid are not likely to pick another guid again, but it will given enough time and if the Guid is not in the table the insert statement will go fine, but if there is already a guid there you will get a primary key constraint violation.</p>\n" }, { "answer_id": 1650823, "author": "bobflux", "author_id": 144450, "author_profile": "https://Stackoverflow.com/users/144450", "pm_score": 0, "selected": false, "text": "<p>I consider the MySQL \"feature\" of reusing id's a bug. </p>\n\n<p>Consider something like processing of file uploads. Using the database id as a filename is a good practice : simple, no risk of exploits with user-supplied filenames, etc.</p>\n\n<p>You can't really make everything transactional when the filesystem is involved... you'll have to commit the database transaction then write the file, or write the file and commit the database transaction, but if one or both fail, or you have a crash, or your network filesystem has a fit, you might have a valid record in the database and no file, or a file without a database record, since the thing is not atomic.</p>\n\n<p>If such a problem happens, and the first thing the server does when coming back is overwrite the ids, and thus the files, of rolled back transactions, it sucks. Those files could have been useful.</p>\n" }, { "answer_id": 3684569, "author": "Jon Black", "author_id": 298016, "author_profile": "https://Stackoverflow.com/users/298016", "pm_score": 0, "selected": false, "text": "<p>no, imagine if your bank decided to re-use your account_id - arghhhh !!</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24227/" ]
I have been reading the post here: <http://encosia.com/2008/10/04/using-jquery-to-enhance-aspnet-ajax-progress-indication/> But it wants to use the following object: ``` Sys.WebForms.PageRequestManager.getInstance() ``` Which doesn't exist when using the MVC AJAX code. Has anyone tried to hook when the postback ends from MVC AJAX to know when to unblock the UI?
NO. numerical primary keys will not reused, except you specify them manually(you should really avoid this!)
253,546
<p>I have a line (actually a cube) going from (x1,y1,z1) to (x2,y2,z2). I would like to rotate it so that it is aligned along another line going from (x3,y3,z3) to (x4,y4,z4). Presently I am using <code>Math::Atan2</code> along with <code>Matrix::RotateYawPitchRoll</code>. Any better ways to do this?</p> <p>Edit: I think I've worded this post very badly. What I am actually looking for is a Rotation Matrix from two Vectors.</p>
[ { "answer_id": 253674, "author": "timday", "author_id": 24283, "author_profile": "https://Stackoverflow.com/users/24283", "pm_score": 3, "selected": true, "text": "<p>Yes you can do this without needing to think in terms of angles at all.</p>\n\n<p>Since you have a cube, suppose you pick one corner and then define the 3 edges radiating out from it as vectors f0, f1, f2 (these are direction vectors, relative to the corner you've picked). Normalise those and write them as columns in a matrix F</p>\n\n<pre><code>(f0x f1x f2x)\n(f0y f1y f2y)\n(f0z f1z f2z)\n</code></pre>\n\n<p>Now do the same thing for the vectors t0, t1, t2 of the cube you want to rotate to and call it matrix T.</p>\n\n<p>Now the matrix R = T * Inverse(F) is the matrix which rotates from the orientation of the first cube to the orientation of the second (because inverse F maps e.g f0 to (1 0 0)', and then T maps (1 0 0)' to t0).</p>\n\n<p>If you want to know why this works, think in terms of coordinate system basis vectors: if you want to rotate the X Y and Z axes to a new coordinate system, well the columns of the rotation matrix are just the vectors you want (1 0 0)', (0 1 0)' &amp; (0 0 1)' to be mapped to. T*Inverse(F) is effectively rotating your cube from its original orientation to axis aligned, and then to the desired orientation.</p>\n\n<p>(Sorry, above is for column vectors and transforms on the left, OpenGL style. I seem to remember Direct3D is row vectors and transforms on the right, but it should be obvious how to switch it around).</p>\n\n<p>It also applies equally well to 4x4 matrices with a translation component too.</p>\n" }, { "answer_id": 280186, "author": "starmole", "author_id": 35706, "author_profile": "https://Stackoverflow.com/users/35706", "pm_score": 0, "selected": false, "text": "<p>You might want to add how to actually interpolate the matrices. Source and destination matrices are fine in your answer, but computing the inverse is pointless. Quaternions will give you the shortest rotational path, so take the rotational 3x3 matrices on both matrices, convert to quaternions and lerp those. Do a separate lerp for the translation and recompose. Google for quaternion - matrix and back conversions and quaternion lerp. </p>\n\n<p>Edit: A rotation matrix from a forward and an up vector is trivial. The missing column is the cross product of the other two vectors. (don't forget to normalize columns). </p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
I have a line (actually a cube) going from (x1,y1,z1) to (x2,y2,z2). I would like to rotate it so that it is aligned along another line going from (x3,y3,z3) to (x4,y4,z4). Presently I am using `Math::Atan2` along with `Matrix::RotateYawPitchRoll`. Any better ways to do this? Edit: I think I've worded this post very badly. What I am actually looking for is a Rotation Matrix from two Vectors.
Yes you can do this without needing to think in terms of angles at all. Since you have a cube, suppose you pick one corner and then define the 3 edges radiating out from it as vectors f0, f1, f2 (these are direction vectors, relative to the corner you've picked). Normalise those and write them as columns in a matrix F ``` (f0x f1x f2x) (f0y f1y f2y) (f0z f1z f2z) ``` Now do the same thing for the vectors t0, t1, t2 of the cube you want to rotate to and call it matrix T. Now the matrix R = T \* Inverse(F) is the matrix which rotates from the orientation of the first cube to the orientation of the second (because inverse F maps e.g f0 to (1 0 0)', and then T maps (1 0 0)' to t0). If you want to know why this works, think in terms of coordinate system basis vectors: if you want to rotate the X Y and Z axes to a new coordinate system, well the columns of the rotation matrix are just the vectors you want (1 0 0)', (0 1 0)' & (0 0 1)' to be mapped to. T\*Inverse(F) is effectively rotating your cube from its original orientation to axis aligned, and then to the desired orientation. (Sorry, above is for column vectors and transforms on the left, OpenGL style. I seem to remember Direct3D is row vectors and transforms on the right, but it should be obvious how to switch it around). It also applies equally well to 4x4 matrices with a translation component too.
253,549
<p>I have the following code which works just fine when the method is "POST", but changing to "GET" doesn't work:</p> <pre><code>HttpWebRequest request = null; request = HttpWebRequest.Create(uri) as HttpWebRequest; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.Method = "POST"; // Doesn't work with "GET" request.BeginGetRequestStream(this.RequestCallback, null); </code></pre> <p>I get a <code>ProtocolViolationException</code> exception with the "GET" method.</p> <p><strong>Edit:</strong> After having a look using Reflector, it seems there is an explicit check for the "GET" method, if it's set to that it throws the exception.</p> <p><strong>Edit2:</strong> I've updated my code to the following, but it still throws an exception when I call EndGetResponse()</p> <pre><code>if (request.Method == "GET") { request.BeginGetResponse(this.ResponseCallback, state); } else { request.BeginGetRequestStream(this.RequestCallback, state); } </code></pre> <p>In my function, ResponseCallback, I have this:</p> <pre><code>HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); </code></pre> <p>Which throws the exception as well.</p> <p><strong>Answer</strong> </p> <p>The above code now works, I had forgotten to take out the Content-Type line which was causing the exception to be thrown at the end. +1 to tweakt &amp; answer to Jon.</p> <p>The working code is now below:</p> <pre><code>HttpWebRequest request = null; request = HttpWebRequest.Create(uri) as HttpWebRequest; request.Method = "GET";// Supports POST too if (request.Method == "GET") { request.BeginGetResponse(this.ResponseCallback, state); } else { request.BeginGetRequestStream(this.RequestCallback, state); } </code></pre>
[ { "answer_id": 253559, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 3, "selected": false, "text": "<p>Does it make sense for a GET request to send a Content-Type? Did you try removing the third line?</p>\n" }, { "answer_id": 253619, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>This is <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx\" rel=\"noreferrer\">specified in the documentation</a>. Basically GET requests aren't meant to contain bodies, so there's no sensible reason to call <code>BeginGetRequestStream</code>.</p>\n" }, { "answer_id": 253639, "author": "Tor Haugen", "author_id": 32050, "author_profile": "https://Stackoverflow.com/users/32050", "pm_score": 1, "selected": false, "text": "<p>BeginGetRequestStream is used to get a stream specifically for writing data to the request. This is not applicable to GET requests.</p>\n\n<p>The documentation for the BeginGetRequestStream method states explicitly that the method will throw a ProtocolViolationException if the Method is GET or HEAD.</p>\n\n<p>Morale: read the docs ;-)</p>\n" }, { "answer_id": 3549748, "author": "MarkPflug", "author_id": 190371, "author_profile": "https://Stackoverflow.com/users/190371", "pm_score": 1, "selected": false, "text": "<p>It is specified in the documentation for the GetRequestStream that it will throw a ProtocolViolationException if the method is GET. However, I cannot find anything in the <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616.html\" rel=\"nofollow noreferrer\">HTTP spec</a> to suggest that this is actually an HTTP protocol violation. Consider this a challenge.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
I have the following code which works just fine when the method is "POST", but changing to "GET" doesn't work: ``` HttpWebRequest request = null; request = HttpWebRequest.Create(uri) as HttpWebRequest; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.Method = "POST"; // Doesn't work with "GET" request.BeginGetRequestStream(this.RequestCallback, null); ``` I get a `ProtocolViolationException` exception with the "GET" method. **Edit:** After having a look using Reflector, it seems there is an explicit check for the "GET" method, if it's set to that it throws the exception. **Edit2:** I've updated my code to the following, but it still throws an exception when I call EndGetResponse() ``` if (request.Method == "GET") { request.BeginGetResponse(this.ResponseCallback, state); } else { request.BeginGetRequestStream(this.RequestCallback, state); } ``` In my function, ResponseCallback, I have this: ``` HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); ``` Which throws the exception as well. **Answer** The above code now works, I had forgotten to take out the Content-Type line which was causing the exception to be thrown at the end. +1 to tweakt & answer to Jon. The working code is now below: ``` HttpWebRequest request = null; request = HttpWebRequest.Create(uri) as HttpWebRequest; request.Method = "GET";// Supports POST too if (request.Method == "GET") { request.BeginGetResponse(this.ResponseCallback, state); } else { request.BeginGetRequestStream(this.RequestCallback, state); } ```
This is [specified in the documentation](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx). Basically GET requests aren't meant to contain bodies, so there's no sensible reason to call `BeginGetRequestStream`.
253,574
<p>I've written some custom model binders (implementing IModelBinder) in our ASP.NET MVC application. I'm wondering what is a good approach to unittest them (binders)?</p>
[ { "answer_id": 254447, "author": "Korbin", "author_id": 17902, "author_profile": "https://Stackoverflow.com/users/17902", "pm_score": 5, "selected": true, "text": "<p>I did it this way: </p>\n\n<pre><code>var formElements = new NameValueCollection() { {\"FirstName\",\"Bubba\"}, {\"MiddleName\", \"\"}, {\"LastName\", \"Gump\"} }; \nvar fakeController = GetControllerContext(formElements);\nvar valueProvider = new Mock&lt;IValueProvider&gt;(); \n\nvar bindingContext = new ModelBindingContext(fakeController, valueProvider.Object, typeof(Guid), null, null, null, null);\n\n\n\nprivate static ControllerContext GetControllerContext(NameValueCollection form) {\n Mock&lt;HttpRequestBase&gt; mockRequest = new Mock&lt;HttpRequestBase&gt;();\n mockRequest.Expect(r =&gt; r.Form).Returns(form);\n\n Mock&lt;HttpContextBase&gt; mockHttpContext = new Mock&lt;HttpContextBase&gt;();\n mockHttpContext.Expect(c =&gt; c.Request).Returns(mockRequest.Object);\n\n return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock&lt;ControllerBase&gt;().Object);\n}\n</code></pre>\n\n<p>And then I just passed in the bindingContext variable to the BindModel method of the object that implements the IModelBinder interface.</p>\n" }, { "answer_id": 589250, "author": "Scott Hanselman", "author_id": 6380, "author_profile": "https://Stackoverflow.com/users/6380", "pm_score": 4, "selected": false, "text": "<p>Here's a simple no-mocks way I wrote for you on my blog assuming you use the ValueProvider and not the HttpContext: <a href=\"http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx\" rel=\"noreferrer\">http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx</a></p>\n\n<pre><code>[TestMethod] \npublic void DateTime_Can_Be_Pulled_Via_Provided_Month_Day_Year_Hour_Minute_Second_Alternate_Names() \n{ \n var dict = new ValueProviderDictionary(null) { \n { \"foo.month1\", new ValueProviderResult(\"2\",\"2\",null) }, \n { \"foo.day1\", new ValueProviderResult(\"12\", \"12\", null) }, \n { \"foo.year1\", new ValueProviderResult(\"1964\", \"1964\", null) }, \n { \"foo.hour1\", new ValueProviderResult(\"13\",\"13\",null) }, \n { \"foo.minute1\", new ValueProviderResult(\"44\", \"44\", null) }, \n { \"foo.second1\", new ValueProviderResult(\"01\", \"01\", null) } \n }; \n\n var bindingContext = new ModelBindingContext() { ModelName = \"foo\", ValueProvider = dict }; \n\n DateAndTimeModelBinder b = new DateAndTimeModelBinder() { Month = \"month1\", Day = \"day1\", Year = \"year1\", Hour = \"hour1\", Minute = \"minute1\", Second = \"second1\" }; \n\n DateTime result = (DateTime)b.BindModel(null, bindingContext); \n Assert.AreEqual(DateTime.Parse(\"1964-02-12 13:44:01\"), result); \n} \n</code></pre>\n" }, { "answer_id": 625106, "author": "labilbe", "author_id": 1195872, "author_profile": "https://Stackoverflow.com/users/1195872", "pm_score": 2, "selected": false, "text": "<p>dict could be refactored like this</p>\n\n<pre><code> FormCollection form = new FormCollection\n {\n { \"month1\", \"2\" },\n { \"day1\", \"12\" },\n { \"year1\", \"1964\" },\n { \"hour1\", \"13\" },\n { \"minute1\", \"44\" },\n { \"second1\", \"01\" }\n };\n\n var bindingContext = new ModelBindingContext() { ModelName = \"foo\", ValueProvider = form.ToValueProvider() }; \n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3182/" ]
I've written some custom model binders (implementing IModelBinder) in our ASP.NET MVC application. I'm wondering what is a good approach to unittest them (binders)?
I did it this way: ``` var formElements = new NameValueCollection() { {"FirstName","Bubba"}, {"MiddleName", ""}, {"LastName", "Gump"} }; var fakeController = GetControllerContext(formElements); var valueProvider = new Mock<IValueProvider>(); var bindingContext = new ModelBindingContext(fakeController, valueProvider.Object, typeof(Guid), null, null, null, null); private static ControllerContext GetControllerContext(NameValueCollection form) { Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>(); mockRequest.Expect(r => r.Form).Returns(form); Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Expect(c => c.Request).Returns(mockRequest.Object); return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object); } ``` And then I just passed in the bindingContext variable to the BindModel method of the object that implements the IModelBinder interface.
253,587
<p>I've recently started using code coverage tools (particularily Emma and EclEmma), and I really like the view that it gives me as to the completeness of my unit tests - and the ability to see what areas of the code my unit tests aren't hitting at all. I currently work in an organization that doesn't do a lot of unit testing, and I plan on really pushing everyone to take on unit testing and code coverage and TDD and hopefully convert the organization.</p> <p>One issue that I'm unsure of with this subject is exactly how far I should take my code coverage. For example, if I have a class such as this:</p> <pre><code>//this class is meant as a pseudo-enum - I'm stuck on Java 1.4 for time being public final class BillingUnit { public final static BillingUnit MONTH = new BillingUnit("month"); public final static BillingUnit YEAR = new BillingUnit("year"); private String value; private BillingUnit(String value) { this.value = value; } public String getValue() { return this.value; } public boolean equals(Object obj) { return value.equals(((BillingUnit) obj).getValue()); } public int hashCode() { return value.hashCode(); } } </code></pre> <p>I wrote some simple unit tests to make sure that <code>equals()</code> works correctly, that <code>getValue()</code> returns what I expected, etc. But thanks to the visual nature of EclEmma, the <code>hashcode()</code> method shows up as bright red for "not tested".</p> <p>Is it worthwhile to even bother to test <code>hashCode()</code>, in this example, considering how simple the implementation is? I feel like I would be adding a unit test for this method simply to bump the code coverage % up, and get rid of the glaring red highlight that EclEmma adds to these lines.</p> <p>Maybe I'm being neurotic and OCD-like, but I find that using something like EclEmma that makes it so easy to see what is untested - the plugin highlights the source code in red, and covered code in green - really makes me want to push to get as many classes 100% green as a I can - even when it doesn't add much of a benefit.</p>
[ { "answer_id": 253612, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 2, "selected": false, "text": "<p>It may not be too complicated now, but a simple check to verify that it is still working as expected can be very useful later on if the method gets modified.</p>\n\n<p>Since the check should be really easy to write, why not do so? It helps the stats, and also helps give you a check later just in case it breaks.</p>\n\n<p>Also, for TDD, you would like 100% coverage, because then you can be sure (or very close to it) that you're not breaking anything when you refactor.</p>\n" }, { "answer_id": 253618, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<p>I use code coverage to give me hints on places where I may have an incomplete set of tests. For example, I may write a test for some given functionality, then go develop the code that satisfies that functionality, but in doing so actually write code that does more than it is supposed to -- say it might catch an exception in an alternate case that the test doesn't exercise. When I use the coverage analyzer, I can see that I've introduced code that doesn't have an associated test. It helps me to know when I haven't written enough tests.</p>\n\n<p>On the other hand, coverage analysis can lead to false security. Having all of your code covered does not mean that you have enough tests. You need to think about tests from the perspective of what should the code do and write tests to make sure that it does it. Preferably by writing the test first. Just because your code is completely covered does not mean that the code does what it is supposed to do.</p>\n\n<p>In your example, I would have written the test for hashCode to define what the functionality of the method does, before I wrote the code. Therefore, I would have it covered. That doesn't mean that I always have 100% coverage. I'm not overly zealous about writing tests for simple accessors, for example. I also may not test methods from the parent class where I inherit from a framework, since I don't feel the need to test other people's code.</p>\n" }, { "answer_id": 253625, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "<p>I think it is worthwhile to use a library where you can choose to ignore certain kinds of statements. For example, if you have a lot of:</p>\n\n<pre><code>if(logger.isDebugEnabled()) {\n logger.debug(\"something\");\n}\n</code></pre>\n\n<p>It is useful if you can turn off coverage calculations for those sorts of lines. It can also be (arguably) valid to turn off coverage calculations for trivial getters and setters (those that simply set or return a member variable with no other checks or side-effects). I do however think that if you have overridden equals and hashcode, those should be tested. You added non-trivial functionality, and it should be tested.</p>\n\n<p>Just to be clear, the reason I think the above situations should be excluded from coverage is that:</p>\n\n<ul>\n<li>Not testing that functionality is ok. You shouldn't have to run through your entire suite of tests 5 times, with the logging library set to each logging level, just to make sure that all your statements are hit.</li>\n<li>If you did the above, it would skew your coverage the other way. If 90% of your branches are <code>if(log.isDebugEnabled())</code>, and you test them all but no other branches, it will look like you have 90% branch coverage (good), when in reality, you have 0% non-trivial branch coverage (bad!!).</li>\n</ul>\n" }, { "answer_id": 253627, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 0, "selected": false, "text": "<p>As I've said elsewhere, low code-coverage is a problem, but high code-coverage doesn't mean that you're writing pure gold.</p>\n\n<p>If you weren't concerned about code-coverage, then I'd suggest that you'd need tests for <code>equals()</code> and <code>getValue()</code> - depending on how and where <code>hashCode()</code> is being used (sorry, I'm a C# developer), then you <em>might</em> want to test that.</p>\n\n<p>The most important part is that your tests give you confidence that you've written the right code and that the code works as expected.</p>\n" }, { "answer_id": 253645, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<p>A fellow programmer stuck like me in old Java1.4 ;)</p>\n\n<p>As said in my <a href=\"https://stackoverflow.com/questions/170751/what-techniques-have-you-actually-used-successfully-to-improve-code-coverage#170768\">previous answer</a>, code covered is not code tested. And the conclusion was: from a certain point, the only way to improve code coverage is... to delete code!</p>\n\n<p>Now, regarding hashCode, it is interesting to have it covered in a unit test design to check the expected sorted mechanism is respected (and not for covering one more function)</p>\n" }, { "answer_id": 253712, "author": "Ryan Boucher", "author_id": 27818, "author_profile": "https://Stackoverflow.com/users/27818", "pm_score": 2, "selected": false, "text": "<p>There is a different between code coverage and testing coverage. You should attempt to ensure that your code is adequately tested rather than having 100% code coverage.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>public float reciprocal (float ex)\n{\n return (1.0 / ex) ;\n}\n</code></pre>\n\n<p>If you ran one test that passed in a value of 1.0 then you would get 100% code coverage (branch and statement) with all passes. The code obviously has a defect.</p>\n\n<p>Measuring test coverage is more difficult and one that comes from becoming a better developer and tester.</p>\n\n<p>With respect to hashCode specifically, a truist would say that you should have a seperate unit test for that method. I personally would ensure that it is include in at least one unit-integration test and would not test each accessor/modifier directly. The return on your investment is often too low to justify the effort. This is assuming of course that you havea unit test that ensure you are generating the correct hash code.</p>\n" }, { "answer_id": 253738, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<p>Reaching 100% code coverage with <em>meaningful</em> tests may not be worth the climb, and, as mentioned before, 100% Code Coverage doesn't necessarily mean that all the possible conditions in the application have been tested.</p>\n\n<p>As for testing <code>equals</code>, <code>hashCode</code> and some other <strong><em>contract based</em></strong> interfaces, like <code>Comparable</code> and <code>Serializable</code>, I do include those tests. It is important that the <code>equals/hashCode</code> contract is implemented correctly, likewise with <code>equals/Comparable</code>.</p>\n\n<p>See <a href=\"http://junit-addons.sourceforge.net/\" rel=\"nofollow noreferrer\">JUnit-Addons</a>, especially</p>\n\n<ul>\n<li><a href=\"http://junit-addons.sourceforge.net/junitx/extensions/EqualsHashCodeTestCase.html\" rel=\"nofollow noreferrer\">EqualsHashCodeTestCase</a></li>\n<li><a href=\"http://junit-addons.sourceforge.net/junitx/extensions/ComparabilityTestCase.html\" rel=\"nofollow noreferrer\">ComparabilityTestCase</a></li>\n<li><a href=\"http://junit-addons.sourceforge.net/junitx/extensions/SerializabilityTestCase.html\" rel=\"nofollow noreferrer\">SerializabilityTestCase</a></li>\n</ul>\n" }, { "answer_id": 254085, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 0, "selected": false, "text": "<p>In this particular case, I would say that since you're testing the equals method, you may as well also test that equal objects have equal hashcodes: just add an extra test to all the cases where equals is expected to return true.</p>\n\n<p>That will give you code coverage, and into the bargain it will give you some confidence that hashCode actually satisfies its contract :-)</p>\n\n<p>It's only marginally worthwhile, given that you obviously can trust the hashCode method of String, and you don't expect ever to change this class. But if you're suspicious enough of your equals method to test it at all, then you should be suspicious enough of it to test that it and hashCode remain consistent. And you should always be suspicious of assumptions that you will not in future want to mess about with what you've done before. For instance, if someone comes along and decides to 'optimise' by adding a pointer-equality check, then you may as well have a complete set of tests for them to run their modified code against. Otherwise they'll waste time on the same worry you did - is it OK that I don't have code coverage?</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I've recently started using code coverage tools (particularily Emma and EclEmma), and I really like the view that it gives me as to the completeness of my unit tests - and the ability to see what areas of the code my unit tests aren't hitting at all. I currently work in an organization that doesn't do a lot of unit testing, and I plan on really pushing everyone to take on unit testing and code coverage and TDD and hopefully convert the organization. One issue that I'm unsure of with this subject is exactly how far I should take my code coverage. For example, if I have a class such as this: ``` //this class is meant as a pseudo-enum - I'm stuck on Java 1.4 for time being public final class BillingUnit { public final static BillingUnit MONTH = new BillingUnit("month"); public final static BillingUnit YEAR = new BillingUnit("year"); private String value; private BillingUnit(String value) { this.value = value; } public String getValue() { return this.value; } public boolean equals(Object obj) { return value.equals(((BillingUnit) obj).getValue()); } public int hashCode() { return value.hashCode(); } } ``` I wrote some simple unit tests to make sure that `equals()` works correctly, that `getValue()` returns what I expected, etc. But thanks to the visual nature of EclEmma, the `hashcode()` method shows up as bright red for "not tested". Is it worthwhile to even bother to test `hashCode()`, in this example, considering how simple the implementation is? I feel like I would be adding a unit test for this method simply to bump the code coverage % up, and get rid of the glaring red highlight that EclEmma adds to these lines. Maybe I'm being neurotic and OCD-like, but I find that using something like EclEmma that makes it so easy to see what is untested - the plugin highlights the source code in red, and covered code in green - really makes me want to push to get as many classes 100% green as a I can - even when it doesn't add much of a benefit.
I use code coverage to give me hints on places where I may have an incomplete set of tests. For example, I may write a test for some given functionality, then go develop the code that satisfies that functionality, but in doing so actually write code that does more than it is supposed to -- say it might catch an exception in an alternate case that the test doesn't exercise. When I use the coverage analyzer, I can see that I've introduced code that doesn't have an associated test. It helps me to know when I haven't written enough tests. On the other hand, coverage analysis can lead to false security. Having all of your code covered does not mean that you have enough tests. You need to think about tests from the perspective of what should the code do and write tests to make sure that it does it. Preferably by writing the test first. Just because your code is completely covered does not mean that the code does what it is supposed to do. In your example, I would have written the test for hashCode to define what the functionality of the method does, before I wrote the code. Therefore, I would have it covered. That doesn't mean that I always have 100% coverage. I'm not overly zealous about writing tests for simple accessors, for example. I also may not test methods from the parent class where I inherit from a framework, since I don't feel the need to test other people's code.
253,614
<p>I'm trying to generate code coverage reports with <a href="http://emma.sourceforge.net/" rel="nofollow noreferrer">EMMA</a> using tests of which some use <a href="http://jmockit.dev.java.net" rel="nofollow noreferrer">JMockit</a> as a mocking framework. For the most part, it works, but a few of my tests crash with a ClassFormatError, like so:</p> <pre><code>java.lang.ClassFormatError at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method) at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:79) at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:138) at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:73) at mockit.Mockit.setUpMocks(Mockit.java:177) at test.my.UnitTest.setUpBeforeClass(UnitTest.java:21) </code></pre> <p>Any idea what is going on, and whether I can fix the problem? Or are EMMA and JMockit mutually exclusive?</p>
[ { "answer_id": 253677, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 2, "selected": true, "text": "<p>Seems to be a bug in JMockit: After the class was already instrumented by EMMA, JMockit seems to have issues creating \"reentry=true\" mock methods.</p>\n\n<p>Removing the \"reentry=true\" \"worked around\" the issue.</p>\n" }, { "answer_id": 527735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>From where and how to remove this \"reentry=true\"</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I'm trying to generate code coverage reports with [EMMA](http://emma.sourceforge.net/) using tests of which some use [JMockit](http://jmockit.dev.java.net) as a mocking framework. For the most part, it works, but a few of my tests crash with a ClassFormatError, like so: ``` java.lang.ClassFormatError at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method) at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:79) at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:138) at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:73) at mockit.Mockit.setUpMocks(Mockit.java:177) at test.my.UnitTest.setUpBeforeClass(UnitTest.java:21) ``` Any idea what is going on, and whether I can fix the problem? Or are EMMA and JMockit mutually exclusive?
Seems to be a bug in JMockit: After the class was already instrumented by EMMA, JMockit seems to have issues creating "reentry=true" mock methods. Removing the "reentry=true" "worked around" the issue.
253,666
<p>In Microsoft Oslo SDK CTP 2008 (using Intellipad) the following code compiles fine:</p> <pre><code>module M { type T { Text : Text; } } </code></pre> <p>while compiling the below code leads to the error "M0197: 'Text' cannot be used in a Type context"</p> <pre><code>module M { type T { Text : Text; Value : Text; // error } } </code></pre> <p>I do not see the difference between the examples, as in the first case Text is also used in a Type context.</p> <p>UPDATE:</p> <p>To add to the confusion, consider the following example, which also compiles fine:</p> <pre><code>module M { type X; type T { X : X; Y : X; } } </code></pre> <p>The M Language Specification states that:</p> <blockquote> <p>Field declarations override lexical scoping to prevent the type of a declaration binding to the declaration itself. The ascribed type of a field declaration must not be the declaration itself; however, the declaration may be used in a constraint. Consider the following example:</p> <p>type A; type B { A : A; }</p> <p>The lexically enclosing scope for the type ascription of the field declaration A is the entity declaration B. With no exception, the type ascription A would bind to the field declaration in a circular reference which is an error. The exception allows lexical lookup to skip the field declaration in this case. </p> </blockquote> <p>It seems that user defined types and built-in (intrinsic) types are not treated equal.</p> <p>UPDATE2:</p> <p>Note that <em>Value</em> in the above example is not a reserved keyword. The same error results if you rename <em>Value</em> to <em>Y</em>.</p> <p>Any ideas?</p> <p>Regards, tamberg</p>
[ { "answer_id": 253672, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>CHUI is faster in execution speed, not user interaction speed. I write embedded systems (as well as GUIs), so I'll always have a use for command line apps.</p>\n" }, { "answer_id": 253675, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>You should absolutely still consider it. Most importantly, command line programs can be automated (and chained together in scripts) much more easily than GUIs (typically). I can't imagine working with a source control tool which didn't have a command line interface - although obviously having a GUI is useful too.</p>\n\n<p>Now whether you need a command line version for your particular app is hard to say without knowing what your app does. Do you need automation and scripting? Might someone want to VPN in and run it from a very bad connection, and thus appreciate low bandwidth?</p>\n\n<p>Note that MS certainly doesn't believe the command line is dead - or they wouldn't have created PowerShell.</p>\n" }, { "answer_id": 253676, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 4, "selected": false, "text": "<p>You should poll your customers, not programmers. If your customers, who use your applications, want a CHUI, even if all your developers think it's a waste of time, you build it, because the customer is always right (except for when they're wrong).</p>\n" }, { "answer_id": 253688, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 2, "selected": false, "text": "<p>Even GUI apps like Firefox can benefit from command line interfaces like <a href=\"http://wiki.mozilla.org/Labs/Ubiquity\" rel=\"nofollow noreferrer\">Ubiquity</a>. If there's a way to provide the command line from within the GUI then why not have the best of both worlds?</p>\n\n<p>A lot of CAD programs have command line interfaces that show you what the GUI interaction you just performed equates to in the command line. That way you can learn the command line operations for the things that you do frequently and where the command line can be quicker to interact with whist still having the discoverability of the GUI interface.</p>\n\n<p>See <a href=\"http://www.youtube.com/watch?v=As0WUtBV3NQ\" rel=\"nofollow noreferrer\">this youtube video</a> demonstrating Rhino3D's command line</p>\n" }, { "answer_id": 253696, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 3, "selected": false, "text": "<p>I agree with Eli that your customers should have final say, <strong>but</strong> if you can keep the meat of your program from being too interwoven with the GUI(or CHUI), then production cost to make both available should be minimal.</p>\n" }, { "answer_id": 253700, "author": "Jason Short", "author_id": 19974, "author_profile": "https://Stackoverflow.com/users/19974", "pm_score": 3, "selected": false, "text": "<p>If you write apps for unix and you need to handle users who telnet / ssh to your box then you will need command line interfaces. </p>\n\n<p>I would say it depends on your target. Do you script your code from other apps? That would be a requirement to keep the interactive version (or some piece to avoid the GUI startup).</p>\n\n<p>We usually do one or the other. But sometimes we have utils that have to be deployable through ftp and run ssh. Or we have tools that our users embed into their apps and don't want to expose a UI (data migration / conversion).</p>\n" }, { "answer_id": 253766, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 2, "selected": false, "text": "<p>When I first read this, my immediate thought was that this is probably one of those apps that's basically a series of forms, but displays inside a terminal. Often you see such dinosaurs running on cash registers. I also recall seeing such an app used to apply for a loan when I bought my car. This type of application doesn't seem to have a place in the modern world -- any system with even a tiny bit of processing power can handle a normal GUI nowadays. Unless you're trying to support really low-end legacy customers, get rid of this user interface. A GUI with decent keyboard shortcuts (please, please, please put some thought into keyboard-only use of your GUI programs...) is going to be equally effective for the users coming from the old CHUI system and much friendlier to those used to a GUI, without having to have 2 versions of your app.</p>\n\n<p>I don't see why everyone is bringing up command line apps. I think most people recognize that the command line isn't going away. It's far faster for many tasks than a GUI, largely because the programs tend to be non-interactive (and thus easily scriptable). As soon as your app becomes interactive (or, at least, doesn't have a param to make it non-interactive), running it from the command line is much less important. Even awesome programs like Vim that are terminal-based are transitioning to their graphical counterparts (gVim) because it gives you the best of both worlds.</p>\n" }, { "answer_id": 253850, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 5, "selected": true, "text": "<p>The primary benefits of a CHUI (that is something with forms and fields, not necessarily command line interfaces) is the keyboard for navigation and consistent layout. That is key.</p>\n\n<p>If your GUI can be completely, and efficiently, keyboard navigated, then your CHUI user base should be happy. This is because in time, the users simply \"type\" their commands in to the system without \"seeing the interface\". They don't need to \"discover\" the interface, which is a primary feature of the GUI.</p>\n\n<p>While CHUIs appear to be dinosaurs, they are still functional and usable. Most folks once they're trained (notably POS/Counter workers, but even back office scenarios like factory or warehouse floor, etc) have no problem using a CHUI.</p>\n\n<p>But the key is the keyboard support so the user don't have to wait for the screen to catch up with them. Seeing a skilled operator with a mastery of the keyboard can make an application fly. You barely have a chance to see popup windows and what not.</p>\n" }, { "answer_id": 253862, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>As soon as you present some data, someone's going to want to query against it. You can integrate that with a gui, no problem. If you think some of your customers are going to want to script certain tasks. set it up. Anything to do with automation is better done from the command line(y harlo thar cron job!)</p>\n\n<p>I love guis. I'm a mac user. But there is a time and a place for a CLI.</p>\n" }, { "answer_id": 253904, "author": "Nack", "author_id": 28314, "author_profile": "https://Stackoverflow.com/users/28314", "pm_score": 2, "selected": false, "text": "<p>To this day, some of the most efficient user interfaces I've ever seen were plain old terminal-based character interfaces.</p>\n\n<p>Anecdote: I was once part of a project to \"modernize\" a terminal application used by 500 customer service representatives. We published sexy GUI mockups and everyone, including the users, were suitably impressed. We worked for six months on the application, and all the user acceptance testing seemed to indicate we had a winner.</p>\n\n<p>But when the application was finally launched, it failed miserably. As it turns out, CSRs are measured for performance daily, right down to the average number of seconds per call handled. And no matter how hard they tried, they could not match the same level of efficiency in the GUI as they could in the terminal interface. They could get close with tabs and shortcuts, but not quite there.</p>\n\n<p>Hard lessons learned. Modern programmers may abhor \"dinosaurs\", but do users really care about slick interfaces? Usually they just want to get their work done.</p>\n" }, { "answer_id": 253963, "author": "Jim C", "author_id": 21706, "author_profile": "https://Stackoverflow.com/users/21706", "pm_score": 1, "selected": false, "text": "<p>Every study I have ever read showed that CHUI's are much faster for experienced users. GUI's are easier for new users and for applications that are only occasionally used. Also for a given screen size, you can display more information on a CHUI then a GUI. A good GUI can give you a quick over view at a glance. </p>\n" }, { "answer_id": 396399, "author": "reuben", "author_id": 41646, "author_profile": "https://Stackoverflow.com/users/41646", "pm_score": 1, "selected": false, "text": "<p>In addition to the other benefits mentioned above, I've frequently found another reason to keep around an alternative UI--it keeps you and your interfaces honest. When an application is built with only one user interface, it becomes much easier to let design principles slide and for your business logic, etc. and your GUI to become an intertwined ball of spaghetti--despite best intentions. Regardless of the importance of your customers having a command-line interface, soon there might come a time when an alternative GUI (read: presentation layer) might be needed, and you'll want to be prepared. This might not be relevant to your requirements, but I think it's something good to keep in mind...</p>\n" }, { "answer_id": 1242622, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>One of the big issues that we encountered was multisession capability which is almost nonexistent with the GUI technologies I have seen. Our users were quick to point out that with the current character based interface they could have over a dozen Telnet based terminal sessions going at the same time on their PC screen which enabled them to multitask or task switch with high efficiency. They rated multitasking as the killer feature which they benefitted from in our fast paced environment where interruptions are frequent. Being able to have concurrent access to multiple instances of a particular ERP application or multiple different ERP applications while always retaining session states was important to our user community.</p>\n" }, { "answer_id": 2001954, "author": "JeffO", "author_id": 61339, "author_profile": "https://Stackoverflow.com/users/61339", "pm_score": 1, "selected": false, "text": "<p>I think the problem comes from design practices in GUI forms. We tend to place more objects on them especially with a vertical scroll bar and tab capabilities. This also makes loading slower. Going through CHUI menus with the keyboard is faster once you've memorized those sequences and holding the Ctrl key isn't required. There is something about the menu bar in Windows where the short-cut key descriptions are off to the right. The character based menus seemed easier to remember after awhile.</p>\n\n<pre><code>A) - This Menu\nB) - That Menu\nC) - Some other Menu\n</code></pre>\n\n<p>Or you could arrow through the choices and you just seemed to have some muscle memory where That Menu is the second choice.</p>\n" }, { "answer_id": 58880328, "author": "Sherwood Botsford", "author_id": 1816138, "author_profile": "https://Stackoverflow.com/users/1816138", "pm_score": 0, "selected": false, "text": "<p>I was sysadmin at a university math department when the registration system went from a character based system using telnet, to a gui system on a PeopleSoft app.</p>\n\n<p>The gals in the front office HATED the new system. Now part of this was the whole bit about old shoes being more comfortable. But when I asked about it, Christine said that even after a week of doing several hundred registrations per day, the new system took several times as long to do anything. Lots of things only doable with a mouse. The old system could accept input as fast as they could type. Screen repaints were under a tenth of a second. New system had lots of 3/4 to 2 second pauses -- just long enough to be annoying, not long enough to do anything else.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3588/" ]
In Microsoft Oslo SDK CTP 2008 (using Intellipad) the following code compiles fine: ``` module M { type T { Text : Text; } } ``` while compiling the below code leads to the error "M0197: 'Text' cannot be used in a Type context" ``` module M { type T { Text : Text; Value : Text; // error } } ``` I do not see the difference between the examples, as in the first case Text is also used in a Type context. UPDATE: To add to the confusion, consider the following example, which also compiles fine: ``` module M { type X; type T { X : X; Y : X; } } ``` The M Language Specification states that: > > Field declarations override lexical scoping to prevent the type of a declaration binding to the declaration itself. The ascribed type of a field declaration must not be the declaration itself; however, the declaration may be used in a constraint. Consider the following example: > > > type A; > type B { > A : A; > } > > > The lexically enclosing scope for the type ascription of the field declaration A is the entity declaration B. With no exception, the type ascription A would bind to the field declaration in a circular reference which is an error. The exception allows lexical lookup to skip the field declaration in this case. > > > It seems that user defined types and built-in (intrinsic) types are not treated equal. UPDATE2: Note that *Value* in the above example is not a reserved keyword. The same error results if you rename *Value* to *Y*. Any ideas? Regards, tamberg
The primary benefits of a CHUI (that is something with forms and fields, not necessarily command line interfaces) is the keyboard for navigation and consistent layout. That is key. If your GUI can be completely, and efficiently, keyboard navigated, then your CHUI user base should be happy. This is because in time, the users simply "type" their commands in to the system without "seeing the interface". They don't need to "discover" the interface, which is a primary feature of the GUI. While CHUIs appear to be dinosaurs, they are still functional and usable. Most folks once they're trained (notably POS/Counter workers, but even back office scenarios like factory or warehouse floor, etc) have no problem using a CHUI. But the key is the keyboard support so the user don't have to wait for the screen to catch up with them. Seeing a skilled operator with a mastery of the keyboard can make an application fly. You barely have a chance to see popup windows and what not.
253,689
<p>I am making an expand/collapse call rates table for the company I work for. I currently have a table with a button under it to expand it, the button says "Expand". It is functional except I need the button to change to "Collapse" when it is clicked and then of course back to "Expand" when it is clicked again. The writing on the button is a background image.</p> <p>So basically all I need is to change the background image of a div when it is clicked, except sort of like a toggle.</p>
[ { "answer_id": 253710, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 9, "selected": false, "text": "<pre><code>$('#divID').css(\"background-image\", \"url(/myimage.jpg)\"); \n</code></pre>\n\n<p>Should do the trick, just hook it up in a click event on the element</p>\n\n<pre><code>$('#divID').click(function()\n{\n // do my image switching logic here.\n});\n</code></pre>\n" }, { "answer_id": 253717, "author": "alexp206", "author_id": 666, "author_profile": "https://Stackoverflow.com/users/666", "pm_score": 3, "selected": false, "text": "<p>One way to do this is to put both images in the HTML, inside a SPAN or DIV, you can hide the default either with CSS, or with JS on page load. Then you can toggle on click. Here is a similar example I am using to put left/down icons on a list:</p>\n\n<pre><code>$(document).ready(function(){\n $(\".button\").click(function () {\n $(this).children(\".arrow\").toggle();\n return false;\n });\n});\n\n&lt;a href=\"#\" class=\"button\"&gt;\n &lt;span class=\"arrow\"&gt;\n &lt;img src=\"/images/icons/left.png\" alt=\"+\" /&gt;\n &lt;/span&gt;\n &lt;span class=\"arrow\" style=\"display: none;\"&gt;\n &lt;img src=\"/images/down.png\" alt=\"-\" /&gt;\n &lt;/span&gt;\n&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 253718, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 4, "selected": false, "text": "<p>If you use a CSS sprite for the background images, you could bump the background offset +/- <em>n</em> pixels depending on whether you were expanding or collapsing. Not a toggle, but closer to it than having to switch background image URLs.</p>\n" }, { "answer_id": 253722, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": false, "text": "<p>This works on all current browsers on WinXP. Basically just checking what the current backgrond image is. If it's image1, show image2, otherwise show image1.</p>\n\n<p>The jsapi stuff just loads jQuery from the Google CDN (easier for testing a misc file on the desktop).</p>\n\n<p>The replace is for cross-browser compatibility (opera and ie add quotes to the url and firefox, chrome and safari remove quotes).</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script src=\"http://www.google.com/jsapi\"&gt;&lt;/script&gt;\n &lt;script&gt;\n google.load(\"jquery\", \"1.2.6\");\n google.setOnLoadCallback(function() {\n var original_image = 'url(http://stackoverflow.com/Content/img/wmd/link.png)';\n var second_image = 'url(http://stackoverflow.com/Content/img/wmd/code.png)';\n\n $('.mydiv').click(function() {\n if ($(this).css('background-image').replace(/\"/g, '') == original_image) {\n $(this).css('background-image', second_image);\n } else {\n $(this).css('background-image', original_image);\n }\n\n return false;\n });\n });\n &lt;/script&gt;\n\n &lt;style&gt;\n .mydiv {\n background-image: url('http://stackoverflow.com/Content/img/wmd/link.png');\n width: 100px;\n height: 100px;\n }\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div class=\"mydiv\"&gt;&amp;nbsp;&lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 2509065, "author": "Sebastian Wolf", "author_id": 300951, "author_profile": "https://Stackoverflow.com/users/300951", "pm_score": 2, "selected": false, "text": "<p>I've found a solution in a forum, <em><a href=\"http://www.dynamicdrive.com/forums/showthread.php?t=5967&amp;page=2\" rel=\"nofollow noreferrer\">Toggle Background Img</a></em>.</p>\n" }, { "answer_id": 3808559, "author": "Kelly", "author_id": 460029, "author_profile": "https://Stackoverflow.com/users/460029", "pm_score": 6, "selected": false, "text": "<p>I personally would just use the JavaScript code to switch between 2 classes.</p>\n\n<p>Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded &amp; collapsed) as rules each with the correct background image (or background position if using a sprite).</p>\n\n<p><strong>CSS with different images</strong></p>\n\n<pre><code>.div {\n /* button size etc properties */\n}\n\n.expanded {background: url(img/x.gif) no-repeat left top;}\n.collapsed {background: url(img/y.gif) no-repeat left top;}\n</code></pre>\n\n<p>Or <strong>CSS with image sprite</strong></p>\n\n<pre><code>.div {\n background: url(img/sprite.gif) no-repeat left top;\n /* Other styles */\n}\n\n.expanded {background-position: left bottom;}\n</code></pre>\n\n<p>Then...</p>\n\n<p><strong>JavaScript code with images</strong></p>\n\n<pre><code>$(function){\n $('#button').click(function(){\n if($(this).hasClass('expanded'))\n {\n $(this).addClass('collapsed').removeClass('expanded');\n }\n else\n {\n $(this).addClass('expanded').removeClass('collapsed');\n }\n });\n}\n</code></pre>\n\n<p><strong>JavaScript with sprite</strong></p>\n\n<p><em>Note: the elegant toggleClass does not work in Internet Explorer 6, but the below <code>addClass</code>/<code>removeClass</code> method will work fine in this situation as well</em></p>\n\n<p><em>The most elegant solution (unfortunately not Internet Explorer 6 friendly)</em></p>\n\n<pre><code>$(function){\n $('#button').click(function(){\n $(this).toggleClass('expanded');\n });\n }\n\n$(function){\n $('#button').click(function(){\n if($(this).hasClass('expanded'))\n {\n $(this).removeClass('expanded');\n }\n else\n {\n $(this).addClass('expanded');\n }\n });\n }\n</code></pre>\n\n<p>As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.</p>\n" }, { "answer_id": 4917267, "author": "Ecropolis", "author_id": 249355, "author_profile": "https://Stackoverflow.com/users/249355", "pm_score": 6, "selected": false, "text": "<p>There are two different ways to change a background image CSS with jQuery.</p>\n\n<ol>\n<li><code>$('selector').css('backgroundImage','url(images/example.jpg)');</code></li>\n<li><code>$('selector').css({'background-image':'url(images/example.jpg)'});</code></li>\n</ol>\n\n<p>Look carefully to note the differences. In the second, you can use conventional CSS and string multiple CSS properties together.</p>\n" }, { "answer_id": 8827670, "author": "Loupax", "author_id": 208271, "author_profile": "https://Stackoverflow.com/users/208271", "pm_score": 4, "selected": false, "text": "<p>Here is how I do it:</p>\n\n<p>CSS</p>\n\n<pre><code>#button{\n background-image: url(\"initial_image.png\");\n}\n\n#button.toggled{\n background-image:url(\"toggled_image.png\");\n}\n</code></pre>\n\n<p>JS</p>\n\n<pre><code>$('#button').click(function(){\n $('#my_content').toggle();\n $(this).toggleClass('toggled');\n});\n</code></pre>\n" }, { "answer_id": 9572401, "author": "DjebbZ", "author_id": 893242, "author_profile": "https://Stackoverflow.com/users/893242", "pm_score": 2, "selected": false, "text": "<p>CSS Sprites work best. I tried switching classes and manipulating the 'background-image' property with jQuery, none worked. I think it's because the browsers (at least the latest stable Chrome) can't \"reload\" an image already loaded.</p>\n\n<p>Bonus : CSS Sprites are faster to download and faster to display. Less HTTP requests means faster page load. Reducing the number of HTTP is the <strong>best</strong> way to improve front end performance, so I recommend going this route all the time.</p>\n" }, { "answer_id": 10592845, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This is a fairly simple response changes the background of the site with a list of items</p>\n\n<pre><code>function randomToN(maxVal) {\n var randVal = Math.random() * maxVal;\n return typeof 0 == 'undefined' ? Math.round(randVal) : randVal.toFixed(0);\n};\nvar list = [ \"IMG0.EXT\", \"IMG2.EXT\",\"IMG3.EXT\" ], // Images\n ram = list[parseFloat(randomToN(list.length))], // Random 1 to n\n img = ram == undefined || ram == null ? list[0] : ram; // Detect null\n$(\"div#ID\").css(\"backgroundImage\", \"url(\" + img + \")\"); // push de background\n</code></pre>\n" }, { "answer_id": 11102959, "author": "bphillips", "author_id": 1466663, "author_profile": "https://Stackoverflow.com/users/1466663", "pm_score": 2, "selected": false, "text": "<p>Old post, but this would allow you to use an image sprite and adjust the repeat as well as positioning by using the shorthand for the css property (background, repeat, left top). </p>\n\n<pre><code>$.each($('.smallPreview'), function(i){\n var $this = $(this);\n\n $this.mouseenter(function(){\n $this.css('background', 'url(Assets/imgs/imgBckg-Small_Over.png) no-repeat 0 0');\n });\n\n $this.mouseleave(function(){\n $this.css('background', 'url(Assets/imgs/imgBckg-Small.png) no-repeat 0 0');\n });\n\n});\n</code></pre>\n" }, { "answer_id": 15684169, "author": "user2220104", "author_id": 2220104, "author_profile": "https://Stackoverflow.com/users/2220104", "pm_score": 3, "selected": false, "text": "<p>I did mine using regular expressions, since I wanted to preserve a relative path and not use add the addClass function. I just wanted to make it convoluted, lol.</p>\n\n<pre><code>$(\".travelinfo-btn\").click(\n function() {\n $(\"html, body\").animate({scrollTop: $(this).offset().top}, 200);\n var bgImg = $(this).css('background-image')\n var bgPath = bgImg.substr(0, bgImg.lastIndexOf('/')+1)\n if(bgImg.match(/collapse/)) {\n $(this).stop().css('background-image', bgImg.replace(/collapse/,'expand'));\n $(this).next(\".travelinfo-item\").stop().slideToggle(400);\n } else {\n $(this).stop().css('background-image', bgImg.replace(/expand/,'collapse'));\n $(this).next(\".travelinfo-item\").stop().slideToggle(400);\n }\n }\n );\n</code></pre>\n" }, { "answer_id": 38220660, "author": "yPhil", "author_id": 1729094, "author_profile": "https://Stackoverflow.com/users/1729094", "pm_score": 3, "selected": false, "text": "<p>Mine is animated:</p>\n\n<pre><code>$(this).animate({\n opacity: 0\n}, 100, function() {\n // Callback\n $(this).css(\"background-image\", \"url(\" + new_img + \")\").promise().done(function(){\n // Callback of the callback :)\n $(this).animate({\n opacity: 1\n }, 600)\n }); \n});\n</code></pre>\n" }, { "answer_id": 59030469, "author": "AdamVanBuskirk", "author_id": 2456574, "author_profile": "https://Stackoverflow.com/users/2456574", "pm_score": 2, "selected": false, "text": "<p>I always use a timestamp as well to prevent browsers from caching the image. For example, if the user is rotating their avatar, it will often get cached and appear to not change. </p>\n\n<pre><code>var d = new Date();\nvar t = d.getTime();\n\n$('#avatar').css(\"background-image\", \"url(\" + iPath + \"?\" + t + \")\");\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
I am making an expand/collapse call rates table for the company I work for. I currently have a table with a button under it to expand it, the button says "Expand". It is functional except I need the button to change to "Collapse" when it is clicked and then of course back to "Expand" when it is clicked again. The writing on the button is a background image. So basically all I need is to change the background image of a div when it is clicked, except sort of like a toggle.
``` $('#divID').css("background-image", "url(/myimage.jpg)"); ``` Should do the trick, just hook it up in a click event on the element ``` $('#divID').click(function() { // do my image switching logic here. }); ```
253,691
<p>I have an abstract base class which inherits from <code>UserControl</code> and which is then used to derive a number of classes. </p> <p>The problem I have is how to elegantly ensure that the generated function <code>InitializeComponent()</code> is called for each layer of class. </p> <p>So the (abstract) base class has a number of controls on it that will be shared for all children. When creating an instance of the child class, the base constructor is called first, but is there any way to elegantly call the derived <code>InitializeComponent()</code> without having to build effectively the same Constructor for each derived class </p> <pre><code>public DerivedClass() { InitializeComponent(); } </code></pre> <p>I'm wondering if there's a more efficient way than repeating myself in each Derived class? </p> <p>In effect, I'd like the (abstract) base class to be able to called </p> <pre><code>Derived.InitializeComponent(); </code></pre> <p>After all, when it's in the base constructor (in debug) it knows that it's a derived instance ... </p>
[ { "answer_id": 253739, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 1, "selected": false, "text": "<p>public DerivedClass() : base()\n{}</p>\n\n<p>This will call your base constructor, there isn't usually a magic way to do things, if you need InitializeComponents called, you'll probably have to call it yourself.</p>\n" }, { "answer_id": 253763, "author": "MrJavaGuy", "author_id": 7138, "author_profile": "https://Stackoverflow.com/users/7138", "pm_score": 0, "selected": false, "text": "<p>if you make InitializeComponent virtual, and you override it for all sub-classes, the base class will call the right method for each of the sub-classes if you call the base constructor from the derived constructor.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2902/" ]
I have an abstract base class which inherits from `UserControl` and which is then used to derive a number of classes. The problem I have is how to elegantly ensure that the generated function `InitializeComponent()` is called for each layer of class. So the (abstract) base class has a number of controls on it that will be shared for all children. When creating an instance of the child class, the base constructor is called first, but is there any way to elegantly call the derived `InitializeComponent()` without having to build effectively the same Constructor for each derived class ``` public DerivedClass() { InitializeComponent(); } ``` I'm wondering if there's a more efficient way than repeating myself in each Derived class? In effect, I'd like the (abstract) base class to be able to called ``` Derived.InitializeComponent(); ``` After all, when it's in the base constructor (in debug) it knows that it's a derived instance ...
public DerivedClass() : base() {} This will call your base constructor, there isn't usually a magic way to do things, if you need InitializeComponents called, you'll probably have to call it yourself.
253,695
<p>I have a Silverlight 2 application that validates data OnTabSelectionChanged. Immediately I began wishing that UpdateSourceTrigger allowed more than just LostFocus because if you click the tab without tabbing off of a control the LINQ object is not updated before validation. </p> <p>I worked around the issue for TextBoxes by setting focus to another control and then back OnTextChanged:</p> <pre><code>Private Sub OnTextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs) txtSetFocus.Focus() sender.Focus() End Sub </code></pre> <p>Now I am trying to accomplish the same sort of hack within a DataGrid. My DataGrid uses DataTemplates generated at runtime for the CellTemplate and CellEditingTemplate. I tried writing the TextChanged="OnTextChanged" into the TextBox in the DataTemplate, but it is not triggered.</p> <p>Anyone have any ideas? </p>
[ { "answer_id": 1654968, "author": "bugfixr", "author_id": 36620, "author_profile": "https://Stackoverflow.com/users/36620", "pm_score": -1, "selected": false, "text": "<p>I know it's old news... but I got around this by doing this:</p>\n\n<p>Text=\"{Binding Path=newQuantity, UpdateSourceTrigger=PropertyChanged}\"</p>\n" }, { "answer_id": 2908237, "author": "murki", "author_id": 5953, "author_profile": "https://Stackoverflow.com/users/5953", "pm_score": 0, "selected": false, "text": "<p>This blog post shows how to update the source of a textbox explicitly using attached property: \n<a href=\"http://www.thomasclaudiushuber.com/blog/2009/07/17/here-it-is-the-updatesourcetrigger-for-propertychanged-in-silverlight/\" rel=\"nofollow noreferrer\">http://www.thomasclaudiushuber.com/blog/2009/07/17/here-it-is-the-updatesourcetrigger-for-propertychanged-in-silverlight/</a></p>\n\n<p>You could easily modify it to work with other controls as well...</p>\n" }, { "answer_id": 3077562, "author": "Ben Brodie", "author_id": 371280, "author_profile": "https://Stackoverflow.com/users/371280", "pm_score": 0, "selected": false, "text": "<p>I ran into this same problem using MVVM and Silverlight 4. The problem is that the binding does not update the source until after the textbox looses focus, but setting focus on another control doesn't do the trick.</p>\n\n<p>I found a solution using a combination of two different blog posts. I used the code from Patrick Cauldwell's DefaultButtonHub concept, with one \"SmallWorkaround\" from SmallWorkarounds.net</p>\n\n<p><a href=\"http://www.cauldwell.net/patrick/blog/DefaultButtonSemanticsInSilverlightRevisited.aspx\" rel=\"nofollow noreferrer\">http://www.cauldwell.net/patrick/blog/DefaultButtonSemanticsInSilverlightRevisited.aspx</a></p>\n\n<p>www.smallworkarounds.net/2010/02/elementbindingbinding-modes.html</p>\n\n<p>My change resulted in the following code for the DefaultButtonHub class:</p>\n\n<pre><code>public class DefaultButtonHub\n{\n ButtonAutomationPeer peer = null;\n\n private void Attach(DependencyObject source)\n {\n if (source is Button)\n {\n peer = new ButtonAutomationPeer(source as Button);\n }\n else if (source is TextBox)\n {\n TextBox tb = source as TextBox;\n tb.KeyUp += OnKeyUp;\n }\n else if (source is PasswordBox)\n {\n PasswordBox pb = source as PasswordBox;\n pb.KeyUp += OnKeyUp;\n }\n }\n\n private void OnKeyUp(object sender, KeyEventArgs arg)\n {\n if (arg.Key == Key.Enter)\n if (peer != null)\n {\n if (sender is TextBox)\n {\n TextBox t = (TextBox)sender;\n BindingExpression expression = t.GetBindingExpression(TextBox.TextProperty);\n expression.UpdateSource();\n }\n ((IInvokeProvider)peer).Invoke();\n }\n }\n\n public static DefaultButtonHub GetDefaultHub(DependencyObject obj)\n {\n return (DefaultButtonHub)obj.GetValue(DefaultHubProperty);\n }\n\n public static void SetDefaultHub(DependencyObject obj, DefaultButtonHub value)\n {\n obj.SetValue(DefaultHubProperty, value);\n }\n\n // Using a DependencyProperty as the backing store for DefaultHub. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty DefaultHubProperty =\n DependencyProperty.RegisterAttached(\"DefaultHub\", typeof(DefaultButtonHub), typeof(DefaultButtonHub), new PropertyMetadata(OnHubAttach));\n\n private static void OnHubAttach(DependencyObject source, DependencyPropertyChangedEventArgs prop)\n {\n DefaultButtonHub hub = prop.NewValue as DefaultButtonHub;\n hub.Attach(source);\n }\n\n}\n</code></pre>\n\n<p>This should be included in some sort of documentation for Silverlight :)</p>\n" }, { "answer_id": 3251313, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://blog.mustoverride.com/2010/01/silverlight-updatesourcetrigger.html?showComment=1279149377285_AIe9_BFLaR4pbpg_swaitgIUU0PR-hQVluTHi6P3siH156dRQIYsaNKVxx_ptreNpwv-HaozS_tab7wC55uFRxgzpOU22HtkC6-Cz2DwtrHdnmZZ5dn0sOwczJ_MpPg5K5LsT24F6GdNHZyI9LYI4kQQaU0V7rtwuIkU1AsYxATywIYpt_ZIRS5lh4WjahPQqu4-c9TBPqHvJN0zQAQGAUsCeuIa0h_HR-rE7iUy4ajM3zzOACX3B9D3tQBXhLrGf0q0mG67thiUcZZqgvzr2eNENemhQpWLX_5Kky7Nj2WDwQcOxIDsYlWz6WTjVu8_UPVFuSTVJjmGajc9rEGDX7Xcq1ZwzVXhRTMCTw_IGXWYm_pp0in0V5G5LEwKViKkNLgFWL3BazgXZQjtFsnFT4Y2-K5FxMGIGmufAAo5uwMM1Q3GLbXwlhwAAcxz3Gar6Z-olH7ylmobDKmCKNedO2zb0ctdkPQZe7U2yYRg5OY-cI3PQtygpkQpjG6ap9yvUIf6Gpd6HErk8Q6OFy4AlpXqiiIriABLE-E1b-e9w44l1T_FQhGLEtiJD4bvY2VZXx5Pe1_0EISdX_PNPcN1E3a5iOmq7CppTkmY64gar1XZtWZ7xdZ18WldNXG3LDFEInWlUiSngpJdBqv0wT81_-RwxJuGY8Faq2iOATzih4274u1bJa73-HWzcepR9G5nl33NBWNCOWZbuW_Q8heTU6ea02X3D-E767OCxHTBi_NB7pRDyAq_stQiFPTD3H--g-DWrhVaI44PXBia88huy4-b1PIEyUzatDm747Hyw9ilRsQPH9RgUbuKocnTBbssmuhq8hK4vErFspeh-nEIHLVvyTxNs-YWhHKBpgY27k5bLZU1fSdyudw#c8238632009983091264\" rel=\"noreferrer\">You can do it with a behavior applied to the textbox too</a></p>\n\n<pre><code>// xmlns:int is System.Windows.Interactivity from System.Windows.Interactivity.DLL)\n// xmlns:behavior is your namespace for the class below\n&lt;TextBox Text=\"{Binding Description,Mode=TwoWay,UpdateSourceTrigger=Explicit}\"&gt;\n &lt;int:Interaction.Behaviors&gt;\n &lt;behavior:TextBoxUpdatesTextBindingOnPropertyChanged /&gt;\n &lt;/int:Interaction.Behaviors&gt;\n&lt;/TextBox&gt;\n\n\npublic class TextBoxUpdatesTextBindingOnPropertyChanged : Behavior&lt;TextBox&gt;\n{\n protected override void OnAttached()\n {\n base.OnAttached();\n\n AssociatedObject.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n\n AssociatedObject.TextChanged -= TextBox_TextChanged;\n }\n\n void TextBox_TextChanged(object sender, TextChangedEventArgs e)\n {\n var bindingExpression = AssociatedObject.GetBindingExpression(TextBox.TextProperty);\n bindingExpression.UpdateSource();\n }\n}\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33102/" ]
I have a Silverlight 2 application that validates data OnTabSelectionChanged. Immediately I began wishing that UpdateSourceTrigger allowed more than just LostFocus because if you click the tab without tabbing off of a control the LINQ object is not updated before validation. I worked around the issue for TextBoxes by setting focus to another control and then back OnTextChanged: ``` Private Sub OnTextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs) txtSetFocus.Focus() sender.Focus() End Sub ``` Now I am trying to accomplish the same sort of hack within a DataGrid. My DataGrid uses DataTemplates generated at runtime for the CellTemplate and CellEditingTemplate. I tried writing the TextChanged="OnTextChanged" into the TextBox in the DataTemplate, but it is not triggered. Anyone have any ideas?
[You can do it with a behavior applied to the textbox too](http://blog.mustoverride.com/2010/01/silverlight-updatesourcetrigger.html?showComment=1279149377285_AIe9_BFLaR4pbpg_swaitgIUU0PR-hQVluTHi6P3siH156dRQIYsaNKVxx_ptreNpwv-HaozS_tab7wC55uFRxgzpOU22HtkC6-Cz2DwtrHdnmZZ5dn0sOwczJ_MpPg5K5LsT24F6GdNHZyI9LYI4kQQaU0V7rtwuIkU1AsYxATywIYpt_ZIRS5lh4WjahPQqu4-c9TBPqHvJN0zQAQGAUsCeuIa0h_HR-rE7iUy4ajM3zzOACX3B9D3tQBXhLrGf0q0mG67thiUcZZqgvzr2eNENemhQpWLX_5Kky7Nj2WDwQcOxIDsYlWz6WTjVu8_UPVFuSTVJjmGajc9rEGDX7Xcq1ZwzVXhRTMCTw_IGXWYm_pp0in0V5G5LEwKViKkNLgFWL3BazgXZQjtFsnFT4Y2-K5FxMGIGmufAAo5uwMM1Q3GLbXwlhwAAcxz3Gar6Z-olH7ylmobDKmCKNedO2zb0ctdkPQZe7U2yYRg5OY-cI3PQtygpkQpjG6ap9yvUIf6Gpd6HErk8Q6OFy4AlpXqiiIriABLE-E1b-e9w44l1T_FQhGLEtiJD4bvY2VZXx5Pe1_0EISdX_PNPcN1E3a5iOmq7CppTkmY64gar1XZtWZ7xdZ18WldNXG3LDFEInWlUiSngpJdBqv0wT81_-RwxJuGY8Faq2iOATzih4274u1bJa73-HWzcepR9G5nl33NBWNCOWZbuW_Q8heTU6ea02X3D-E767OCxHTBi_NB7pRDyAq_stQiFPTD3H--g-DWrhVaI44PXBia88huy4-b1PIEyUzatDm747Hyw9ilRsQPH9RgUbuKocnTBbssmuhq8hK4vErFspeh-nEIHLVvyTxNs-YWhHKBpgY27k5bLZU1fSdyudw#c8238632009983091264) ``` // xmlns:int is System.Windows.Interactivity from System.Windows.Interactivity.DLL) // xmlns:behavior is your namespace for the class below <TextBox Text="{Binding Description,Mode=TwoWay,UpdateSourceTrigger=Explicit}"> <int:Interaction.Behaviors> <behavior:TextBoxUpdatesTextBindingOnPropertyChanged /> </int:Interaction.Behaviors> </TextBox> public class TextBoxUpdatesTextBindingOnPropertyChanged : Behavior<TextBox> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.TextChanged += new TextChangedEventHandler(TextBox_TextChanged); } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.TextChanged -= TextBox_TextChanged; } void TextBox_TextChanged(object sender, TextChangedEventArgs e) { var bindingExpression = AssociatedObject.GetBindingExpression(TextBox.TextProperty); bindingExpression.UpdateSource(); } } ```
253,701
<p>I have a web application that allows a user to search on some criteria, select an object, edit it and then return to the previous search. All the editing takes place on a separate page linked to the datagrid of returned results. I was wondering what is the best way to store the previous search parameters so that when they return to the grid they have the same search they previously used. The best option I came up with is to use a NameValue collection of each of the selected paramters and store that to Session or a cookie when the user presses the search button. Any other ideas as to a better way to approach this?</p>
[ { "answer_id": 253845, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 2, "selected": true, "text": "<p>In our app, we have dozens of lists with search fields. We've designed a simple utility class that generates a unique string based on the current Page and stores it in the session.</p>\n\n<pre><code> public static string GenerateSessionKeyFromPage(Page page)\n {\n return \"__\" + page.Request.Path;\n }\n</code></pre>\n\n<p>This allows us to store the search field without having to maintain a NameValue collection every time we add a new page. </p>\n" }, { "answer_id": 254032, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "<p>If it's a common query (common across all users), you may want to cache the results and simply bind to the cached results when you return to the grid. It'll save you the processing and bandwidth expense of making the call again.</p>\n\n<p>If it's a user-specific query and you have the resources, you may want to cache the results.</p>\n\n<p>If it's a user-specific query and you don't have the resources, caching the parameters (like you mention) is probably the best option.</p>\n\n<p>Coming up with a robust caching scheme can be tricky. Take a look at <a href=\"http://en.wikipedia.org/wiki/Memcached\" rel=\"nofollow noreferrer\">memcached</a> to see how others have solved it (note the <a href=\"http://www.codeplex.com/memcachedproviders\" rel=\"nofollow noreferrer\">ASP.NET Memcached Providers</a>).</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30383/" ]
I have a web application that allows a user to search on some criteria, select an object, edit it and then return to the previous search. All the editing takes place on a separate page linked to the datagrid of returned results. I was wondering what is the best way to store the previous search parameters so that when they return to the grid they have the same search they previously used. The best option I came up with is to use a NameValue collection of each of the selected paramters and store that to Session or a cookie when the user presses the search button. Any other ideas as to a better way to approach this?
In our app, we have dozens of lists with search fields. We've designed a simple utility class that generates a unique string based on the current Page and stores it in the session. ``` public static string GenerateSessionKeyFromPage(Page page) { return "__" + page.Request.Path; } ``` This allows us to store the search field without having to maintain a NameValue collection every time we add a new page.
253,705
<p>I have a dropdown list that stores name/value pairs. The dropdown appears in each row of a gridview.</p> <p>The values in the dropdown correspond to a third attribute (data type) not persisted in the dropdown list. I'd like to create a client-side "lookup" table so that when a user chooses a dropdown value, the proper data type populates next to it.</p> <p>What's the best way to accomplish this in an ASP.NET application? The List of value/attributes could potentially range from 1 to 100 members in a list...</p>
[ { "answer_id": 253715, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "<p>If you want it all to run client side, then your only option is probably JavaScript.</p>\n\n<pre><code>var oVals = new Array('1','2','3','4','5');\n\ndocument.getElementById(\"cell1\").innerHTML = oVals[document.getElementById(\"dropdown1\").selectedIndex];\n</code></pre>\n" }, { "answer_id": 263515, "author": "Caveatrob", "author_id": 335036, "author_profile": "https://Stackoverflow.com/users/335036", "pm_score": 2, "selected": true, "text": "<p>Found a nice solution at snipplr.com (<a href=\"http://tinyurl.com/67rzav\" rel=\"nofollow noreferrer\">http://tinyurl.com/67rzav</a>)</p>\n\n<p>The function call looks something like this:</p>\n\n<pre><code>var profileHeaders = new AArray(); \n\nprofileHeaders .add(\"k01\", \"hi\");\nprofileHeaders .add(\"k02\", \"ho\");\n\nvar oC = profileHeaders .get(\"k02\");\n\nalert(oC); \n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335036/" ]
I have a dropdown list that stores name/value pairs. The dropdown appears in each row of a gridview. The values in the dropdown correspond to a third attribute (data type) not persisted in the dropdown list. I'd like to create a client-side "lookup" table so that when a user chooses a dropdown value, the proper data type populates next to it. What's the best way to accomplish this in an ASP.NET application? The List of value/attributes could potentially range from 1 to 100 members in a list...
Found a nice solution at snipplr.com (<http://tinyurl.com/67rzav>) The function call looks something like this: ``` var profileHeaders = new AArray(); profileHeaders .add("k01", "hi"); profileHeaders .add("k02", "ho"); var oC = profileHeaders .get("k02"); alert(oC); ```
253,724
<p>I'm looking for a way to supply an argument to a ruby on rails project at runtime. Essentially, our project uses public key cryptography to encrypt some sensitive client data and we want the ability to supply the password to the private key file at runtime.</p>
[ { "answer_id": 253980, "author": "Micah", "author_id": 19964, "author_profile": "https://Stackoverflow.com/users/19964", "pm_score": 1, "selected": false, "text": "<p>What is wrong with putting the password in a file that is chmod'ed to only be readable by the web server user?</p>\n" }, { "answer_id": 254703, "author": "Jsnydr", "author_id": 32503, "author_profile": "https://Stackoverflow.com/users/32503", "pm_score": 2, "selected": true, "text": "<p>An easy way to do this would be to create a Rails plugin that takes arguments using 'gets' in its 'init.rb'. Allow me to cook-up a quick code sample:</p>\n\n<p>Make a directory: '$railsRoot/vendor/plugins/startup_args/lib'</p>\n\n<p>Create an object to store argument data in '$railsRoot/vendor/plugins/startup_args/lib/startup_args.rb':</p>\n\n<pre><code>module StartupArgs\n @@argHash = {}\n\n def self.setArg(key, value)\n @@argHash[key.to_sym] = value\n end\n\n def self.getArg(key)\n return @@argHash[key.to_sym]\n end\nend\n</code></pre>\n\n<p>Load the StartupArgs module into the Rails project's namespace and populate it with arguments in '$railsRoot/vendor/plugins/startup_args/init.rb':</p>\n\n<pre><code>require \"startup_args\"\n\npromptString = \"Enter arg name (type nothing to continue):\"\n\nputs promptString\nwhile (newArg = gets.chomp) != \"\"\n puts \"Enter value for '#{newArg}':\"\n newVal = gets.chomp\n StartupArgs.setArg(newArg, newVal)\n\n puts promptString\nend\n</code></pre>\n\n<p>Now, during the Rails project's start-up process, it will try to take key-value pairs from the console. These pairs will be stored in the global-namespace object StartupArgs for later access (via 'StartupArgs.getArg()').</p>\n\n<p>If you anticipate that your Rails project might be deployed in scenarios where the daemon will not have access to the console during startup-time, you could read from a named-pipe instead of the console's standard input.</p>\n\n<p>Going one step further, you could remove all parts of 'init.rb' except for the 'require' statement and add an action that performs this setup to a controller that would take the relevant parameters as a post over the web. Make sure to configure Rails to prevent potentially sensitive parameters (e.g. passwords) from being entered into log files recording accesses or errors (especially if it might be used as an HTTP GET, with parameters in the URL).</p>\n\n<p>(You get the same effect this way as with the system described above if you configure your other Rails actions to ignore requests until the setup action has stored the appropriate parameters to the global object.)</p>\n\n<p>A Note For Micah: I don't have the reputation to comment directly on your post, so I will include my comment here. There might be a few reasons to consider a system that never requires the password to be represented in the filesystem. For example, a developer might be planning a Rails project that could be deployed on varying operating systems and in varying environments. If the developer determines that there could be scenarios in which an administrative or root user could be compromised, cannot be trusted, or cannot be asked to sign confidentiality and security agreements, the developer might decide to add the additional obfuscation of placing the password in memory only (in the interest of requiring a slightly less secure system or a slightly more clever attack to steal the password). Perhaps it could be considered a matter of relative costs: at low cost, the password can be hidden in a way that requires more expensive knowledge in order to retrieve.</p>\n" }, { "answer_id": 254858, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "<p>Any Ruby script has access to local environment variables through the ENV hash.</p>\n\n<pre><code>puts ENV['PATH']\n</code></pre>\n\n<p>So with any posix system (Linux, Unix, Mac OS) you can simply set it when calling the script, like this:</p>\n\n<pre><code>MY_ARG=supersecret ruby script.rb\n</code></pre>\n\n<p>The same is also valid for rails. If you put <code>puts ENV['MY_ARG']</code> in your environment.rb and start your server:</p>\n\n<pre><code>$ MY_ARG=supersecret mongrel_rails start\n** Starting Mongrel listening at 0.0.0.0:3000\n** Starting Rails with development environment...\nsupersecret\n** Rails loaded.\n** Loading any Rails specific GemPlugins\n** Signals ready. TERM =&gt; stop. USR2 =&gt; restart. INT =&gt; stop (no restart).\n** Rails signals registered. HUP =&gt; reload (without restart). It might not work well.\n** Mongrel 1.1.5 available at 0.0.0.0:3000\n** Use CTRL-C to stop.\n</code></pre>\n\n<p>An environment variable is by far the simplest solution in my opinion.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11042/" ]
I'm looking for a way to supply an argument to a ruby on rails project at runtime. Essentially, our project uses public key cryptography to encrypt some sensitive client data and we want the ability to supply the password to the private key file at runtime.
An easy way to do this would be to create a Rails plugin that takes arguments using 'gets' in its 'init.rb'. Allow me to cook-up a quick code sample: Make a directory: '$railsRoot/vendor/plugins/startup\_args/lib' Create an object to store argument data in '$railsRoot/vendor/plugins/startup\_args/lib/startup\_args.rb': ``` module StartupArgs @@argHash = {} def self.setArg(key, value) @@argHash[key.to_sym] = value end def self.getArg(key) return @@argHash[key.to_sym] end end ``` Load the StartupArgs module into the Rails project's namespace and populate it with arguments in '$railsRoot/vendor/plugins/startup\_args/init.rb': ``` require "startup_args" promptString = "Enter arg name (type nothing to continue):" puts promptString while (newArg = gets.chomp) != "" puts "Enter value for '#{newArg}':" newVal = gets.chomp StartupArgs.setArg(newArg, newVal) puts promptString end ``` Now, during the Rails project's start-up process, it will try to take key-value pairs from the console. These pairs will be stored in the global-namespace object StartupArgs for later access (via 'StartupArgs.getArg()'). If you anticipate that your Rails project might be deployed in scenarios where the daemon will not have access to the console during startup-time, you could read from a named-pipe instead of the console's standard input. Going one step further, you could remove all parts of 'init.rb' except for the 'require' statement and add an action that performs this setup to a controller that would take the relevant parameters as a post over the web. Make sure to configure Rails to prevent potentially sensitive parameters (e.g. passwords) from being entered into log files recording accesses or errors (especially if it might be used as an HTTP GET, with parameters in the URL). (You get the same effect this way as with the system described above if you configure your other Rails actions to ignore requests until the setup action has stored the appropriate parameters to the global object.) A Note For Micah: I don't have the reputation to comment directly on your post, so I will include my comment here. There might be a few reasons to consider a system that never requires the password to be represented in the filesystem. For example, a developer might be planning a Rails project that could be deployed on varying operating systems and in varying environments. If the developer determines that there could be scenarios in which an administrative or root user could be compromised, cannot be trusted, or cannot be asked to sign confidentiality and security agreements, the developer might decide to add the additional obfuscation of placing the password in memory only (in the interest of requiring a slightly less secure system or a slightly more clever attack to steal the password). Perhaps it could be considered a matter of relative costs: at low cost, the password can be hidden in a way that requires more expensive knowledge in order to retrieve.
253,727
<p>When building static libraries with VS2005 I keep getting linker warnings that VC80.pdb cant be found with my library.lib. Apparently, as a result, the edit and continue feature of the IDE fails to work any project that incorporates library.lib</p> <p>What magic is needed to tell VS2005 to produce a static lib with edit and continue debug info that does NOT reference or require vs80.pdb when linked into a project?</p> <p>--Upon Further Understanding-- So, In order to get edit-and-continue to function with a pre-compiled static lib, we need to place the vs80.pdb and vs80.pdb file into SVN along with the .lib, AND rename the pdb/idb to prevent conflicts when doing this with multiple pre-compiled libs.</p>
[ { "answer_id": 254257, "author": "Steve Steiner", "author_id": 3892, "author_profile": "https://Stackoverflow.com/users/3892", "pm_score": 4, "selected": true, "text": "<p>vc80.pdb is the file that contains the debug information for your lib. In the ide Property pages:configuration properties:c\\c++:output files allows you to rename this to something more appropriate, such as the name of your lib. When the linker links your lib into the target exe it looks for this pdb (there is a pointer to it in the lib) and extracts the info from that pdb and drops it in the exe's pdb.</p>\n\n<p>/Fd[name] is the option for renaming the pdb\n/ZI is the option for compiling with a pdb that includes Edit and Continue information.</p>\n\n<p>All linked libs and the final taget exe or dll need /ZI, to enable edit and continue.</p>\n\n<p>I made a tiny testlib.lib and used \"dumpbin /all\" to get the following showing the pointer to the debug info (this is a tiny excerpt):</p>\n\n<pre><code>SECTION HEADER #7\n.debug$T name\n 0 physical address\n 0 virtual address\n 48 size of raw data\n 838 file pointer to raw data (00000838 to 0000087F)\n 0 file pointer to relocation table\n 0 file pointer to line numbers\n 0 number of relocations\n 0 number of line numbers\n42100040 flags\n Initialized Data\n Discardable\n 1 byte align\n Read Only\n\nRAW DATA #7\n 00000000: 04 00 00 00 42 00 15 15 D5 EA 1E C9 7C 10 3A 40 ....B...Õê.É|.:@\n 00000010: 93 63 CE 95 77 15 49 4A 03 00 00 00 64 3A 5C 64 .cÎ.w.IJ....d:\\d\n 00000020: 65 76 5C 74 65 73 74 5C 74 65 73 74 6C 69 62 5C ev\\test\\testlib\\\n 00000030: 74 65 73 74 6C 69 62 5C 64 65 62 75 67 5C 76 63 testlib\\debug\\vc\n 00000040: 38 30 2E 70 64 62 00 F1 80.pdb.ñ\n</code></pre>\n" }, { "answer_id": 2760985, "author": "george", "author_id": 330605, "author_profile": "https://Stackoverflow.com/users/330605", "pm_score": 2, "selected": false, "text": "<p>If you can live without 'edit and continue', try using <a href=\"http://msdn.microsoft.com/en-us/library/958x11bc(VS.80).aspx\" rel=\"nofollow noreferrer\">/Z7</a>.<br>\nI use it for all the .lib files that are stored in source control. No .pdb file is created - the debug info is stored inside the .lib file.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27491/" ]
When building static libraries with VS2005 I keep getting linker warnings that VC80.pdb cant be found with my library.lib. Apparently, as a result, the edit and continue feature of the IDE fails to work any project that incorporates library.lib What magic is needed to tell VS2005 to produce a static lib with edit and continue debug info that does NOT reference or require vs80.pdb when linked into a project? --Upon Further Understanding-- So, In order to get edit-and-continue to function with a pre-compiled static lib, we need to place the vs80.pdb and vs80.pdb file into SVN along with the .lib, AND rename the pdb/idb to prevent conflicts when doing this with multiple pre-compiled libs.
vc80.pdb is the file that contains the debug information for your lib. In the ide Property pages:configuration properties:c\c++:output files allows you to rename this to something more appropriate, such as the name of your lib. When the linker links your lib into the target exe it looks for this pdb (there is a pointer to it in the lib) and extracts the info from that pdb and drops it in the exe's pdb. /Fd[name] is the option for renaming the pdb /ZI is the option for compiling with a pdb that includes Edit and Continue information. All linked libs and the final taget exe or dll need /ZI, to enable edit and continue. I made a tiny testlib.lib and used "dumpbin /all" to get the following showing the pointer to the debug info (this is a tiny excerpt): ``` SECTION HEADER #7 .debug$T name 0 physical address 0 virtual address 48 size of raw data 838 file pointer to raw data (00000838 to 0000087F) 0 file pointer to relocation table 0 file pointer to line numbers 0 number of relocations 0 number of line numbers 42100040 flags Initialized Data Discardable 1 byte align Read Only RAW DATA #7 00000000: 04 00 00 00 42 00 15 15 D5 EA 1E C9 7C 10 3A 40 ....B...Õê.É|.:@ 00000010: 93 63 CE 95 77 15 49 4A 03 00 00 00 64 3A 5C 64 .cÎ.w.IJ....d:\d 00000020: 65 76 5C 74 65 73 74 5C 74 65 73 74 6C 69 62 5C ev\test\testlib\ 00000030: 74 65 73 74 6C 69 62 5C 64 65 62 75 67 5C 76 63 testlib\debug\vc 00000040: 38 30 2E 70 64 62 00 F1 80.pdb.ñ ```
253,731
<p>I have a web page that has a web form for signing up. I want to remove fields. I've tried removing the field code from the .asp file but obviously there are other things that I need to remove along those lines. I have full access to all the code but I need help knowing where things are linked as far as making the form work again. Our programmer bailed. </p> <p>A step by step guide would be great on this. thanks.</p>
[ { "answer_id": 253762, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 2, "selected": false, "text": "<p>If they're just .ASP files, you should be fine removing the field tag, along with any references to it.</p>\n\n<p>I.e. you'd delete this line:</p>\n\n<pre><code>&lt;asp:TextBox id=\"text1\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>and do a search for the 'id' attribute in the rest of the file (a find on 'text1' in this case), and remove those lines.</p>\n" }, { "answer_id": 253790, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>If everything to do with that for in in the same ASP page, it's easy. You can do a simple text search for the names and/or IDs of each form field. Sometimes they're referenced in a javascript block, so you'll have to comment-out some of the form validation code referencing those fields.</p>\n\n<p>If they've used some dumb Dreamweaver script for all this - good luck!</p>\n\n<p>If there are #include statements, or references to external JavaScript files it's more work - you'll have to trace through them as well, hoping they don't have their own included files as well.</p>\n" }, { "answer_id": 254007, "author": "WestDiscGolf", "author_id": 33116, "author_profile": "https://Stackoverflow.com/users/33116", "pm_score": 0, "selected": false, "text": "<p>After removing the input parts of the markup, if it is a .asp (assuming asp v3 instead of asp.net) it is also worth going through the &lt;% %> tags part of the page to look for references to the removed inputs. If it's asp.net then check the vb.net / c# code in the script runat server block in the page, or look in the code behind file for references and recompile.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a web page that has a web form for signing up. I want to remove fields. I've tried removing the field code from the .asp file but obviously there are other things that I need to remove along those lines. I have full access to all the code but I need help knowing where things are linked as far as making the form work again. Our programmer bailed. A step by step guide would be great on this. thanks.
If they're just .ASP files, you should be fine removing the field tag, along with any references to it. I.e. you'd delete this line: ``` <asp:TextBox id="text1" runat="server" /> ``` and do a search for the 'id' attribute in the rest of the file (a find on 'text1' in this case), and remove those lines.
253,735
<p>I have a report that is used by a windows service and a form application. So, I want to put embed the report in a DLL file that can be used by both.</p> <p>The problem is that if I try to set the ReportEmbeddedResource property of a ReportViewer control in my windows form app, it will search the windows form app for the resource, not the dll file.</p> <p>e.g.: Code from the windows form app:</p> <pre><code>rv.LocalReport.ReportEmbeddedResource = "MyReportInMyDLLFile.rdlc" </code></pre> <p>How can I make the above command look for the embedded resource in my DLL file?</p>
[ { "answer_id": 261842, "author": "DrCamel", "author_id": 4168, "author_profile": "https://Stackoverflow.com/users/4168", "pm_score": 4, "selected": false, "text": "<p>Probably the best thing to do would be to get a stream to the RDLC resource from the other assembly, then pass that to the \"LoadReportDefinition\" method of the Report Viewer control.</p>\n\n<p>Details of how to get a stream from an embedded resource in a different assembly can be found here : <a href=\"http://msdn.microsoft.com/en-us/library/aa984408(VS.71).aspx\" rel=\"noreferrer\">Retrieving Resources with the ResourceManager Class</a></p>\n\n<p>Additionally, you will need to refer to the embedded resource using it's full namespace path.</p>\n\n<p>E.g. if you have an application with a default namespace of <strong>TheApp</strong>, and you keep a report called \"<strong>MyReport.rdlc</strong>\" in a folder called \"<strong>Reports</strong>\", the report reference call would be:-</p>\n\n<pre><code>rv.LocalReport.ReportEmbeddedResource = \"TheApp.Reports.MyReport.rdlc\";\n</code></pre>\n" }, { "answer_id": 358276, "author": "gschuager", "author_id": 19716, "author_profile": "https://Stackoverflow.com/users/19716", "pm_score": 7, "selected": true, "text": "<p>Something like this should do it:</p>\n\n<pre><code>Assembly assembly = Assembly.LoadFrom(\"Reports.dll\");\nStream stream = assembly.GetManifestResourceStream(\"Reports.MyReport.rdlc\");\nreportViewer.LocalReport.LoadReportDefinition(stream);\n</code></pre>\n" }, { "answer_id": 3334002, "author": "Dan Higham", "author_id": 402149, "author_profile": "https://Stackoverflow.com/users/402149", "pm_score": 5, "selected": false, "text": "<p>Just use the full namespace of the assembly, then folder names and then the name of the file:</p>\n\n<pre><code>rv.LocalReport.ReportEmbeddedResource = \n \"My.Assembly.Namespace.Folder1.Folder2.MyReport.rdlc\";\n</code></pre>\n\n<p>Then make sure the report file is set as an embedded resource using the properties pane.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
I have a report that is used by a windows service and a form application. So, I want to put embed the report in a DLL file that can be used by both. The problem is that if I try to set the ReportEmbeddedResource property of a ReportViewer control in my windows form app, it will search the windows form app for the resource, not the dll file. e.g.: Code from the windows form app: ``` rv.LocalReport.ReportEmbeddedResource = "MyReportInMyDLLFile.rdlc" ``` How can I make the above command look for the embedded resource in my DLL file?
Something like this should do it: ``` Assembly assembly = Assembly.LoadFrom("Reports.dll"); Stream stream = assembly.GetManifestResourceStream("Reports.MyReport.rdlc"); reportViewer.LocalReport.LoadReportDefinition(stream); ```
253,746
<p>In Microsoft Oslo SDK CTP 2008 (using Intellipad) the following code compiles fine:</p> <pre><code>module T { type A { Id : Integer32 = AutoNumber(); } where identity Id; As : A*; type B { Id : Integer32 = AutoNumber(); // A : A; // } where A in As &amp;&amp; identity Id; } where identity Id; Bs : B*; type C { Id : Integer32 = AutoNumber(); B : B; } where B in Bs &amp;&amp; identity Id; Cs : C*; } </code></pre> <p>and results in the following Reach SQL output:</p> <pre><code>set xact_abort on; go begin transaction; go set ansi_nulls on; go create schema [T]; go create table [T].[As] ( [Id] int not null identity, constraint [PK_As] primary key clustered ([Id]) ); go create table [T].[Bs] ( [Id] int not null identity, constraint [PK_Bs] primary key clustered ([Id]) ); go create table [T].[Cs] ( [Id] int not null identity, [B] int not null, constraint [PK_Cs] primary key clustered ([Id]), constraint [FK_Cs_B_T_Bs] foreign key ([B]) references [T].[Bs] ([Id]) ); go commit transaction; go </code></pre> <p>But after changing the commented line in module T as follows</p> <pre><code> A : A; } where A in As &amp;&amp; identity Id; // } where identity Id; </code></pre> <p>the error message "M2037: SQL Generation Internal Error: Missing generator for variable 'A'" is displayed (in Intellipad's Reach SQL Window).</p> <p>Any Ideas?</p> <p>Regards, tamberg</p>
[ { "answer_id": 254473, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": true, "text": "<p>I think what you want is:</p>\n\n<pre><code>type A {\n Id : Integer32 = AutoNumber();\n} where identity Id;\n\nAs : A*;\n\ntype B {\n Id : Integer32 = AutoNumber();\n A : A;\n} where identity Id;\n\nBs : (B where value.A in As)*;\n\ntype C {\n Id : Integer32 = AutoNumber();\n B : B;\n} where identity Id &amp;&amp; B in Bs;\n\nCs : (C where value.B in Bs)*;\n</code></pre>\n\n<p>Note that the constraints are on the externs, not the types here. I was able to get similar code when the constraints where on the types but not able to go more than one relationship deep. Moving them to the externs seems correct and generates the expected Reach SQL.</p>\n" }, { "answer_id": 254943, "author": "tamberg", "author_id": 3588, "author_profile": "https://Stackoverflow.com/users/3588", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/oslo/thread/05103bf8-4e0f-4976-bcdd-2c724cb08738/\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/oslo/thread/05103bf8-4e0f-4976-bcdd-2c724cb08738/</a></p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3588/" ]
In Microsoft Oslo SDK CTP 2008 (using Intellipad) the following code compiles fine: ``` module T { type A { Id : Integer32 = AutoNumber(); } where identity Id; As : A*; type B { Id : Integer32 = AutoNumber(); // A : A; // } where A in As && identity Id; } where identity Id; Bs : B*; type C { Id : Integer32 = AutoNumber(); B : B; } where B in Bs && identity Id; Cs : C*; } ``` and results in the following Reach SQL output: ``` set xact_abort on; go begin transaction; go set ansi_nulls on; go create schema [T]; go create table [T].[As] ( [Id] int not null identity, constraint [PK_As] primary key clustered ([Id]) ); go create table [T].[Bs] ( [Id] int not null identity, constraint [PK_Bs] primary key clustered ([Id]) ); go create table [T].[Cs] ( [Id] int not null identity, [B] int not null, constraint [PK_Cs] primary key clustered ([Id]), constraint [FK_Cs_B_T_Bs] foreign key ([B]) references [T].[Bs] ([Id]) ); go commit transaction; go ``` But after changing the commented line in module T as follows ``` A : A; } where A in As && identity Id; // } where identity Id; ``` the error message "M2037: SQL Generation Internal Error: Missing generator for variable 'A'" is displayed (in Intellipad's Reach SQL Window). Any Ideas? Regards, tamberg
I think what you want is: ``` type A { Id : Integer32 = AutoNumber(); } where identity Id; As : A*; type B { Id : Integer32 = AutoNumber(); A : A; } where identity Id; Bs : (B where value.A in As)*; type C { Id : Integer32 = AutoNumber(); B : B; } where identity Id && B in Bs; Cs : (C where value.B in Bs)*; ``` Note that the constraints are on the externs, not the types here. I was able to get similar code when the constraints where on the types but not able to go more than one relationship deep. Moving them to the externs seems correct and generates the expected Reach SQL.
253,747
<p>I'm using .NET typed datasets on a project, and I often get into situations where I prefetch data from several tables into a dataset and then pass that dataset to several methods for processing. It seems cleaner to let each method decide exactly which data it needs and then load the data itself. However, several of the methods work with the same data, and I want the performance benefit of loading data in the beginning only once.</p> <p>My problem is that I don't know of a good way or pattern to use for managing dependencies (I want to be sure I load all the data that I'm going to need for each class/method that will use the dataset). Currently, I just end up looking through the code for the various classes that will use the dataset to make sure I'm loading everything appropriately.</p> <p>What are good approaches or patterns to use in this situation? Am I doing something fundamentally wrong? Although I'm using typed datasets, this seems like it would be a common situation where prefetching data is used.</p> <p>Thanks!</p>
[ { "answer_id": 254473, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": true, "text": "<p>I think what you want is:</p>\n\n<pre><code>type A {\n Id : Integer32 = AutoNumber();\n} where identity Id;\n\nAs : A*;\n\ntype B {\n Id : Integer32 = AutoNumber();\n A : A;\n} where identity Id;\n\nBs : (B where value.A in As)*;\n\ntype C {\n Id : Integer32 = AutoNumber();\n B : B;\n} where identity Id &amp;&amp; B in Bs;\n\nCs : (C where value.B in Bs)*;\n</code></pre>\n\n<p>Note that the constraints are on the externs, not the types here. I was able to get similar code when the constraints where on the types but not able to go more than one relationship deep. Moving them to the externs seems correct and generates the expected Reach SQL.</p>\n" }, { "answer_id": 254943, "author": "tamberg", "author_id": 3588, "author_profile": "https://Stackoverflow.com/users/3588", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/oslo/thread/05103bf8-4e0f-4976-bcdd-2c724cb08738/\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/oslo/thread/05103bf8-4e0f-4976-bcdd-2c724cb08738/</a></p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33096/" ]
I'm using .NET typed datasets on a project, and I often get into situations where I prefetch data from several tables into a dataset and then pass that dataset to several methods for processing. It seems cleaner to let each method decide exactly which data it needs and then load the data itself. However, several of the methods work with the same data, and I want the performance benefit of loading data in the beginning only once. My problem is that I don't know of a good way or pattern to use for managing dependencies (I want to be sure I load all the data that I'm going to need for each class/method that will use the dataset). Currently, I just end up looking through the code for the various classes that will use the dataset to make sure I'm loading everything appropriately. What are good approaches or patterns to use in this situation? Am I doing something fundamentally wrong? Although I'm using typed datasets, this seems like it would be a common situation where prefetching data is used. Thanks!
I think what you want is: ``` type A { Id : Integer32 = AutoNumber(); } where identity Id; As : A*; type B { Id : Integer32 = AutoNumber(); A : A; } where identity Id; Bs : (B where value.A in As)*; type C { Id : Integer32 = AutoNumber(); B : B; } where identity Id && B in Bs; Cs : (C where value.B in Bs)*; ``` Note that the constraints are on the externs, not the types here. I was able to get similar code when the constraints where on the types but not able to go more than one relationship deep. Moving them to the externs seems correct and generates the expected Reach SQL.
253,757
<p>In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class:</p> <pre><code>public class A { public event EventHandler SomeEvent; public void someMethod() { if(SomeEvent != null) SomeEvent(this, someArgs); } } public class B : A { public void someOtherMethod() { if(SomeEvent != null) SomeEvent(this, someArgs); // &lt;&lt; why is this not possible? //Error: The event 'SomeEvent' can only appear on the left hand side of += or -= //(except when used from within the type 'A') } } </code></pre> <p>Why isn't it possible?</p> <p>And what is the common solution for this kind of situation?</p>
[ { "answer_id": 253776, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 6, "selected": true, "text": "<p>The standard practice here is to have a protected virtual method OnSomeEvent on your base class, then call that method in derived classes. Also, for threading reasons you will want to keep a reference to the handler before checking null and calling it.</p>\n\n<p>For an explanation of the why read <a href=\"https://stackoverflow.com/questions/253757/why-events-cant-be-used-in-the-same-way-in-derived-classes-as-in-the-base-class#253803\">Jon Skeet's</a> answer or the <a href=\"http://msdn.microsoft.com/en-us/library/aa664454(VS.71).aspx\" rel=\"noreferrer\">C# specification</a> which describes how the compiler automatically creates a private field.</p>\n\n<p>Here is one possible work around.</p>\n\n<pre><code>public class A\n{\n public event EventHandler SomeEvent;\n\n public void someMethod()\n {\n OnSomeEvent();\n }\n\n protected void OnSomeEvent()\n {\n EventHandler handler = SomeEvent;\n if(handler != null)\n handler(this, someArgs);\n }\n}\n\npublic class B : A\n{\n public void someOtherMethod()\n {\n OnSomeEvent();\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong> Updated code based upon <a href=\"http://msdn.microsoft.com/en-us/library/cf18x51d(VS.71).aspx\" rel=\"noreferrer\">Framework Design Guidelines section 5.4</a> and <a href=\"https://stackoverflow.com/questions/253757/why-events-cant-be-used-in-the-same-way-in-derived-classes-as-in-the-base-class#253806\">reminders</a> by others.</p>\n" }, { "answer_id": 253793, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "<p>Wrap it with a protected virtual On... method:</p>\n\n<pre><code>public class BaseClass\n{\n public event EventHandler&lt;MyArgs&gt; SomeEvent;\n\n protected virtual void OnSomeEvent()\n {\n if(SomeEvent!= null)\n SomeEvent(this, new MyArgs(...) );\n }\n}\n</code></pre>\n\n<p>Then override this in a derived class</p>\n\n<pre><code>public class DerivedClass : BaseClass\n{\n protected override void OnSomeEvent()\n {\n //do something\n\n base.OnSomeEvent();\n }\n}\n</code></pre>\n\n<p>You'll set this pattern all over .Net - all form and web controls follow it.</p>\n\n<p>Do not use the prefix Raise... - this is not consistent with MS's standards and can cause confusion elsewhere.</p>\n" }, { "answer_id": 253803, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "<p>Others have explained how to get round the issue, but not why it's coming up.</p>\n\n<p>When you declare a public field-like event, the compiler creates a public event, and a private field. Within the same class (or <em>nested</em> classes) you can get at the field directly, e.g. to invoke all the handlers. From other classes, you only see the event, which only allows subscription and unsubscription.</p>\n" }, { "answer_id": 253806, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": false, "text": "<p>Todd's answer is correct. Often you will see this implemented throughout the .NET framework as <code>OnXXX(EventArgs)</code> methods:</p>\n\n<pre><code>public class Foo\n{\n public event EventHandler Click;\n\n protected virtual void OnClick(EventArgs e)\n {\n var click = Click;\n if (click != null)\n click(this, e);\n }\n}\n</code></pre>\n\n<p>I strongly encourage you to consider the <a href=\"http://www.c-sharpcorner.com/UploadFile/rmcochran/customgenericeventargs05132007100456AM/customgenericeventargs.aspx\" rel=\"noreferrer\"><code>EventArgs&lt;T&gt;</code>/<code>EventHandler&lt;T&gt;</code> pattern</a> before you find yourself making all manner of <code>CustomEventArgs</code>/<code>CustomEventHandler</code> for raising events.</p>\n" }, { "answer_id": 253813, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 2, "selected": false, "text": "<p>The reason the original code doesn't work is because you need to have access to the event's delegate in order to raise it, and C# keeps this delegate <code>private</code>.</p>\n\n<p>Events in C# are represented publicly by a pair of methods, <code>add_SomeEvent</code> and <code>remove_SomeEvent</code>, which is why you can subscribe to an event from outside the class, but not raise it.</p>\n" }, { "answer_id": 253969, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p>My answer would be that you shouldn't have to do this. </p>\n\n<p>C# nicely enforces <strong>Only the type declaring/publishing the event should fire/raise it.</strong> \nIf the base class trusted derivations to have the capability to raise its events, the creator would expose protected methods to do that. If they don't exist, its a good hint that you probably shouldn't do this.</p>\n\n<p>My contrived example as to how different the world would be if derived types were allowed to raise events in their ancestors. Note: this is <strong>not</strong> valid C# code.. (yet..)</p>\n\n<pre><code>public class GoodVigilante\n{\n public event EventHandler LaunchMissiles;\n\n public void Evaluate()\n {\n Action a = DetermineCourseOfAction(); // method that evaluates every possible\n// non-violent solution before resorting to 'Unleashing the fury'\n\n if (null != a) \n { a.Do(); }\n else\n { if (null != LaunchMissiles) LaunchMissiles(this, EventArgs.Empty); }\n }\n\n virtual protected string WhatsTheTime()\n { return DateTime.Now.ToString(); }\n .... \n}\npublic class TriggerHappy : GoodVigilante\n{\n protected override string WhatsTheTime()\n {\n if (null != LaunchMissiles) LaunchMissiles(this, EventArgs.Empty);\n }\n\n}\n\n// client code\nGoodVigilante a = new GoodVigilante();\na.LaunchMissiles += new EventHandler(FireAway);\nGoodVigilante b = new TriggerHappy(); // rogue/imposter\nb.LaunchMissiles += new EventHandler(FireAway);\n\nprivate void FireAway(object sender, EventArgs e)\n{\n // nuke 'em\n}\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26070/" ]
In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class: ``` public class A { public event EventHandler SomeEvent; public void someMethod() { if(SomeEvent != null) SomeEvent(this, someArgs); } } public class B : A { public void someOtherMethod() { if(SomeEvent != null) SomeEvent(this, someArgs); // << why is this not possible? //Error: The event 'SomeEvent' can only appear on the left hand side of += or -= //(except when used from within the type 'A') } } ``` Why isn't it possible? And what is the common solution for this kind of situation?
The standard practice here is to have a protected virtual method OnSomeEvent on your base class, then call that method in derived classes. Also, for threading reasons you will want to keep a reference to the handler before checking null and calling it. For an explanation of the why read [Jon Skeet's](https://stackoverflow.com/questions/253757/why-events-cant-be-used-in-the-same-way-in-derived-classes-as-in-the-base-class#253803) answer or the [C# specification](http://msdn.microsoft.com/en-us/library/aa664454(VS.71).aspx) which describes how the compiler automatically creates a private field. Here is one possible work around. ``` public class A { public event EventHandler SomeEvent; public void someMethod() { OnSomeEvent(); } protected void OnSomeEvent() { EventHandler handler = SomeEvent; if(handler != null) handler(this, someArgs); } } public class B : A { public void someOtherMethod() { OnSomeEvent(); } } ``` **Edit:** Updated code based upon [Framework Design Guidelines section 5.4](http://msdn.microsoft.com/en-us/library/cf18x51d(VS.71).aspx) and [reminders](https://stackoverflow.com/questions/253757/why-events-cant-be-used-in-the-same-way-in-derived-classes-as-in-the-base-class#253806) by others.
253,780
<p>I'd like to return an object with the following signature</p> <pre><code>class AnonClass{ string Name {get;} IEnumerable&lt;Group&gt; Groups {get;} } </code></pre> <p>I have tried the following query, but g only returns a single entity, not all the joined entities</p> <pre><code>var q = from t in dc.Themes join g in dc.Groups on t.K equals g.ThemeK select new {t.Name, Groups = g}; return q.ToArray(); </code></pre> <p>but this returns</p> <pre><code>class AnonClass{ string Name {get;} Group Groups{get;} } </code></pre> <p>What is the correct linq query to use?</p>
[ { "answer_id": 253774, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 2, "selected": false, "text": "<p>The de-facto OS X IDE and compiler is <a href=\"http://developer.apple.com/tools/xcode/\" rel=\"nofollow noreferrer\">Xcode</a>. It comes with every Mac, you just install it from the OS X install CD.</p>\n\n<p><a href=\"http://developer.apple.com/mac/\" rel=\"nofollow noreferrer\">Apple's developer site</a> is the place to get more information on OS X APIs</p>\n" }, { "answer_id": 253777, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 1, "selected": false, "text": "<p>Xcode and a custom GCC I believe...</p>\n" }, { "answer_id": 253825, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 0, "selected": false, "text": "<p>Xcode is used a lot, as far as I know the combination editor (e.g. <a href=\"http://macromates.com/\" rel=\"nofollow noreferrer\">Textmate</a>), command line gcc is in fairly heavy use too. (that's what I do on OS X)</p>\n\n<p>For all API needs head to <a href=\"http://developer.apple.com\" rel=\"nofollow noreferrer\">Apple's developer site</a> e.g. the <a href=\"http://developer.apple.com/referencelibrary/Networking/\" rel=\"nofollow noreferrer\">networking</a> API's</p>\n" }, { "answer_id": 253872, "author": "mmr", "author_id": 21981, "author_profile": "https://Stackoverflow.com/users/21981", "pm_score": 0, "selected": false, "text": "<p>xcode is the hotness, as people have already pointed out.</p>\n\n<p>Having maintained a windows/mac codebase in the past, take a look at <a href=\"http://en.wikipedia.org/wiki/Model_view_controller\" rel=\"nofollow noreferrer\">MVC</a>.</p>\n\n<p>So long as you keep the background logic distinct from the UI and from the platform-specific stuff (like file handling, networks, drawing to the screen, etc). That way, when you want to go to Linux in the future, you just have to write those platform specific components.</p>\n\n<p>As for mac networking, are you on the level of connecting and so forth? Why not just let the OS handle that, and then you just see what connections are available? Why bother with whether or not the connection is wired or wireless? Because the OS has a lot of those tools already built in and users are used to making sure that the connection is there to do work, it seems odd to have an extra program to want to manipulate the network. </p>\n" }, { "answer_id": 257369, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 4, "selected": true, "text": "<p>Xcode is the IDE for Mac OS X, you can download the latest version by joining the Apple Developer Connection with a free Online membership.</p>\n\n<p>I don't believe there are any supported APIs for controlling wireless networking adaptors. The closest thing would be the System Configuration framework, but I don't know if it will let you do everything you want.</p>\n\n<p>Also, I would strongly recommend <strong>against</strong> trying to use Flex/Air for your application's user experience. It may look slick to you on Windows as a Windows developer, but when it comes to providing a full Macintosh user experience such technologies aren't always a great choice.</p>\n\n<p>For one example, I think Air applications don't support the full range of Mac OS X text editing keystrokes. While not all Mac users will use all keystrokes, for those people used to them trying to type in a text field that doesn't handle (say) control-A and control-E to go to the beginning and end of field is like swimming through syrup.</p>\n\n<p>For a new application that needs to be cross-platform, I'd strongly consider building the core logic in C++ while using Cocoa on the Mac and WPF on Windows to get the best user experience on each platform. Both Mac OS X and Windows have modern native user experience technologies that their respective users are getting used to, and also have good ways for C++ code to interoperate with these technologies.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086/" ]
I'd like to return an object with the following signature ``` class AnonClass{ string Name {get;} IEnumerable<Group> Groups {get;} } ``` I have tried the following query, but g only returns a single entity, not all the joined entities ``` var q = from t in dc.Themes join g in dc.Groups on t.K equals g.ThemeK select new {t.Name, Groups = g}; return q.ToArray(); ``` but this returns ``` class AnonClass{ string Name {get;} Group Groups{get;} } ``` What is the correct linq query to use?
Xcode is the IDE for Mac OS X, you can download the latest version by joining the Apple Developer Connection with a free Online membership. I don't believe there are any supported APIs for controlling wireless networking adaptors. The closest thing would be the System Configuration framework, but I don't know if it will let you do everything you want. Also, I would strongly recommend **against** trying to use Flex/Air for your application's user experience. It may look slick to you on Windows as a Windows developer, but when it comes to providing a full Macintosh user experience such technologies aren't always a great choice. For one example, I think Air applications don't support the full range of Mac OS X text editing keystrokes. While not all Mac users will use all keystrokes, for those people used to them trying to type in a text field that doesn't handle (say) control-A and control-E to go to the beginning and end of field is like swimming through syrup. For a new application that needs to be cross-platform, I'd strongly consider building the core logic in C++ while using Cocoa on the Mac and WPF on Windows to get the best user experience on each platform. Both Mac OS X and Windows have modern native user experience technologies that their respective users are getting used to, and also have good ways for C++ code to interoperate with these technologies.
253,834
<p>Has anyone found a good class, or other file that will convert a .doc file into html or something that I can read and turn into html? </p> <p>I have been looking around for a couple hours now and have only found ones that require msword on the server in order to convert the file. I am pretty sure that is not an option but I have not actually talked to my hosting provider about it.</p> <p>The goal is for a user to be able to upload the file to my server and the server handle the conversion and then display it as html, much like googles view as html feature.</p>
[ { "answer_id": 556403, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A project called phpLiveDocx does what you want. It is a SOAP based service, but can be used free of charge. For a basic introduction, please see:\n<a href=\"http://www.phplivedocx.org/articles/brief-introduction-to-phplivedocx/\" rel=\"nofollow noreferrer\">http://www.phplivedocx.org/articles/brief-introduction-to-phplivedocx/</a></p>\n" }, { "answer_id": 2920480, "author": "Anthony Tolman", "author_id": 351864, "author_profile": "https://Stackoverflow.com/users/351864", "pm_score": 0, "selected": false, "text": "<p>Install open office on your system and run this on the command line:</p>\n\n<p>/usr/bin/soffice -headless \"macro:///Standard.Convert.SaveAsHtml(test.doc)\"</p>\n" }, { "answer_id": 2968182, "author": "CronosNull", "author_id": 356675, "author_profile": "https://Stackoverflow.com/users/356675", "pm_score": 3, "selected": false, "text": "<p>intall and use abiword, like this: </p>\n\n<pre><code>AbiWord --to=html archivo.doc\n</code></pre>\n\n<p>you can call this command from php. </p>\n" }, { "answer_id": 4281704, "author": "mvod", "author_id": 499843, "author_profile": "https://Stackoverflow.com/users/499843", "pm_score": 0, "selected": false, "text": "<p>You can do it through openoffice with unoconv <a href=\"http://dag.wieers.com/home-made/unoconv/\" rel=\"nofollow\">http://dag.wieers.com/home-made/unoconv/</a>\nReally great tool.</p>\n" }, { "answer_id": 11334583, "author": "forever99", "author_id": 1502362, "author_profile": "https://Stackoverflow.com/users/1502362", "pm_score": 0, "selected": false, "text": "<p>This PHP uploads your *.DOC file to a upload folder and opens it up in HTML.</p>\n\n<pre><code>&lt;?php\nfunction content($file){\n$data_array = explode(chr(0x0D),fread(fopen($file, \"r\"), filesize($file)));\n$data_text = \"\";\nforeach($data_array as $data_line){\nif (strpos($data_line, chr(0x00) !== false)||(strlen($data_line)==0))\n{} else {if(chr(0)) {$data_text .= \"&lt;br&gt;\";\n $data_text .= preg_replace(\"/[^a-zA-Z0-9\\s\\,\\.\\-\\n\\r\\t@\\/\\_\\(\\)]/\",\"\",$data_line); \n } \n } \n}\nreturn $data_text;}\n$destination = str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']);\n$destination.= \"upload/\";\n$maxsize = 5120000;\nif (isset($_GET['upload'])) {\n if($_FILES['userfile']['name'] &amp;&amp; $_FILES['userfile']['size'] &lt; $maxsize) {\n if(move_uploaded_file($_FILES['userfile']['tmp_name'], \"$destination/\".$_FILES['userfile']['name'])){\n $file = $destination.\"/\".$_FILES['userfile']['name'];\n $data = content($file);\n echo $data;\n } \n }\n}else{\n echo \"&lt;form enctype='multipart/form-data' method='post' action='index.php?upload'&gt;\n &lt;input name='userfile' type='file'&gt;\n &lt;input value='Upload' name='submit' type='submit'&gt;\n &lt;/form&gt;\";\n }\n?&gt;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925/" ]
Has anyone found a good class, or other file that will convert a .doc file into html or something that I can read and turn into html? I have been looking around for a couple hours now and have only found ones that require msword on the server in order to convert the file. I am pretty sure that is not an option but I have not actually talked to my hosting provider about it. The goal is for a user to be able to upload the file to my server and the server handle the conversion and then display it as html, much like googles view as html feature.
intall and use abiword, like this: ``` AbiWord --to=html archivo.doc ``` you can call this command from php.
253,843
<p>What is the best way to refresh a <code>DataGridView</code> when you update an underlying data source?</p> <p>I'm updating the datasource frequently and wanted to display the outcome to the user as it happens.</p> <p>I've got something like this (and it works), but setting the <code>DataGridView.DataSource</code> to <code>null</code> doesn't seem like the right way.</p> <pre><code>List&lt;ItemState&gt; itemStates = new List&lt;ItemState&gt;(); dataGridView1.DataSource = itemStates; for (int i = 0; i &lt; 10; i++) { itemStates.Add(new ItemState { Id = i.ToString() }); dataGridView1.DataSource = null; dataGridView1.DataSource = itemStates; System.Threading.Thread.Sleep(500); } </code></pre>
[ { "answer_id": 253863, "author": "Georg", "author_id": 30776, "author_profile": "https://Stackoverflow.com/users/30776", "pm_score": -1, "selected": false, "text": "<p>Try this Code</p>\n\n<pre><code>List itemStates = new List();\n\nfor (int i = 0; i &lt; 10; i++)\n{ \n itemStates.Add(new ItemState { Id = i.ToString() });\n dataGridView1.DataSource = itemStates;\n dataGridView1.DataBind();\n System.Threading.Thread.Sleep(500);\n}\n</code></pre>\n" }, { "answer_id": 253945, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 7, "selected": true, "text": "<p>Well, it doesn't get much better than that. Officially, you should use</p>\n\n<pre><code>dataGridView1.DataSource = typeof(List); \ndataGridView1.DataSource = itemStates;\n</code></pre>\n\n<p>It's still a \"clear/reset source\" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.</p>\n" }, { "answer_id": 1118992, "author": "GWLlosa", "author_id": 18071, "author_profile": "https://Stackoverflow.com/users/18071", "pm_score": 6, "selected": false, "text": "<p>I ran into this myself. My recommendation: If you have ownership of the datasource, don't use a <a href=\"https://msdn.microsoft.com/en-us/library/6sh2ey19.aspx\" rel=\"noreferrer\">List</a>. Use a <a href=\"https://msdn.microsoft.com/en-us/library/ms132679(v=vs.110).aspx\" rel=\"noreferrer\">BindingList</a>. The <a href=\"https://msdn.microsoft.com/en-us/library/ms132679(v=vs.110).aspx\" rel=\"noreferrer\">BindingList</a> has events that fire when items are added or changed, and the <a href=\"https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.aspx\" rel=\"noreferrer\">DataGridView</a> will automatically update itself when these events are fired. </p>\n" }, { "answer_id": 30174930, "author": "starko", "author_id": 3185406, "author_profile": "https://Stackoverflow.com/users/3185406", "pm_score": 0, "selected": false, "text": "<p>This is copy my answer from <a href=\"https://stackoverflow.com/questions/21299016/how-to-refresh-or-show-immediately-in-datagridview-after-inserting/30174907\">THIS</a> place.</p>\n\n<p>Only need to fill datagrid again like this:</p>\n\n<pre><code>this.XXXTableAdapter.Fill(this.DataSet.XXX);\n</code></pre>\n\n<p>If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()</p>\n" }, { "answer_id": 30175479, "author": "Kashif", "author_id": 636740, "author_profile": "https://Stackoverflow.com/users/636740", "pm_score": 2, "selected": false, "text": "<p><strong>Observablecollection</strong> :Represents a dynamic data collection that provides notifications \nwhen items get added, removed, or when the whole list is refreshed.\nYou can enumerate over any collection that implements the IEnumerable interface. \nHowever, to set up dynamic bindings so that insertions or deletions in the\n collection update the UI automatically,\n the collection must implement the INotifyCollectionChanged interface.\n This interface exposes the CollectionChanged event,\n an event that should be raised whenever the underlying collection changes.</p>\n\n<pre><code>Observablecollection&lt;ItemState&gt; itemStates = new Observablecollection&lt;ItemState&gt;();\n\nfor (int i = 0; i &lt; 10; i++) { \n itemStates.Add(new ItemState { Id = i.ToString() });\n }\n dataGridView1.DataSource = itemStates;\n</code></pre>\n" }, { "answer_id": 32018111, "author": "Stix", "author_id": 4917652, "author_profile": "https://Stackoverflow.com/users/4917652", "pm_score": 0, "selected": false, "text": "<p>You are setting the datasource inside of the loop and sleeping 500 after each add. Why not just add to itemstates and then set your datasource AFTER you have added everything. If you want the thread sleep after that fine. The first block of code here is yours the second block I modified.</p>\n\n<pre><code>for (int i = 0; i &lt; 10; i++) { \n itemStates.Add(new ItemState { Id = i.ToString() });\n dataGridView1.DataSource = null;\n dataGridView1.DataSource = itemStates;\n System.Threading.Thread.Sleep(500);\n}\n</code></pre>\n\n<p><strong>Change your Code As follows:</strong> this is much faster.</p>\n\n<pre><code>for (int i = 0; i &lt; 10; i++) { \n itemStates.Add(new ItemState { Id = i.ToString() });\n\n}\n dataGridView1.DataSource = typeof(List); \n dataGridView1.DataSource = itemStates;\n System.Threading.Thread.Sleep(500);\n</code></pre>\n" }, { "answer_id": 40953879, "author": "Alexander Abakumov", "author_id": 3345644, "author_profile": "https://Stackoverflow.com/users/3345644", "pm_score": 5, "selected": false, "text": "<p>The cleanest, most efficient and paradigm-friendly solution in this case is to use a <code>System.Windows.Forms.BindingSource</code> as a proxy between your list of items (datasource) and your <code>DataGridView</code>:</p>\n\n<pre><code>var itemStates = new List&lt;ItemState&gt;();\nvar bindingSource1 = new System.Windows.Forms.BindingSource { DataSource = itemStates };\ndataGridView1.DataSource = bindingSource1;\n</code></pre>\n\n<p>Then, when adding items, use <code>Add()</code> method of <code>BindingSource</code> instead of your list's <code>Add()</code> method:</p>\n\n<pre><code>for (var i = 0; i &lt; 10; i++)\n{\n bindingSource1.Add(new ItemState { Id = i.ToString() });\n System.Threading.Thread.Sleep(500);\n}\n</code></pre>\n\n<p>This way you adding items to your list and notifying <code>DataGridView</code> about those additions with the same line of code. No need to reset <code>DataGridView</code>'s <code>DataSource</code> every time you make a change to the list.</p>\n\n<p>It also worth mentioning that you can drop a <code>BindingSource</code> onto your form directly in Visual Studio's Forms Designer and attach it as a data source to your <code>DataGridView</code> there as well, which saves you a line of code in the above example where I'm doing it manually.</p>\n" }, { "answer_id": 72885206, "author": "David", "author_id": 19495496, "author_profile": "https://Stackoverflow.com/users/19495496", "pm_score": 0, "selected": false, "text": "<p>Just delete all Rows and fill it after deleting:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>BindingList&lt;ItemState&gt; itemStates = new BindingList&lt;ItemState&gt;();\ndatagridview1.Rows.Clear();\n\nfor(int i = 0; i &lt; 10; i++)\n{\n itemStates.Add(new ItemState { id = i.ToString() });\n}\n\ndatagridview1.DataSource = itemStates;\nThread.Sleep(500);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21180/" ]
What is the best way to refresh a `DataGridView` when you update an underlying data source? I'm updating the datasource frequently and wanted to display the outcome to the user as it happens. I've got something like this (and it works), but setting the `DataGridView.DataSource` to `null` doesn't seem like the right way. ``` List<ItemState> itemStates = new List<ItemState>(); dataGridView1.DataSource = itemStates; for (int i = 0; i < 10; i++) { itemStates.Add(new ItemState { Id = i.ToString() }); dataGridView1.DataSource = null; dataGridView1.DataSource = itemStates; System.Threading.Thread.Sleep(500); } ```
Well, it doesn't get much better than that. Officially, you should use ``` dataGridView1.DataSource = typeof(List); dataGridView1.DataSource = itemStates; ``` It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.
253,868
<p>I'm looking at all the CSS Drop shadow tutorials, which are great. Unfortunately, I need to put a shadow on three sides of a block element (left, bottom, right). All the tutorials talk about shifting your block element up and to the left. Anyone have insights into putting a shadow on three or even four sides?</p>
[ { "answer_id": 253878, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 2, "selected": false, "text": "<p>make your block element larger/higher, so that it exceeds the sides you want.</p>\n" }, { "answer_id": 253915, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 1, "selected": false, "text": "<p>Here's one way to do it:</p>\n\n<pre><code>&lt;div style='position:relative;'&gt;\n &lt;div style='position:absolute;top:10px;left:10px;width:300px;height:100px;z-index:1;background-color:#CCCCCC'&gt;&lt;/div&gt;\n &lt;div style='position:absolute;top:0px;left:0px;width:300px;height:100px;z-index:2;background-color:#00CCFF'&gt;\n &lt;p&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse at felis. Etiam ullamcorper.&lt;/p&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Size and position the \"z-index:1\" DIV to your liking.</p>\n" }, { "answer_id": 253916, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<p>Pseudo HTML</p>\n\n<pre><code>&lt;div style=\"position:absolute;top:8;left:12;width:200;height:204;background-color:#888888\"&gt;&lt;/div&gt;\n&lt;div style=\"position:absolute;top:10;left:10;width:200;height:200;background-color:#FFFFFF\"&gt;The element&lt;/div&gt;\n</code></pre>\n\n<p>You need to play with the size of the shadow. In the above example the shadow is slightly higher than the element so the shadow shows above, its slightly offset to the left so the shadow shows on the right and it is slightly larger than the element so the shadow shows below.</p>\n" }, { "answer_id": 371526, "author": "Nathan DeWitt", "author_id": 1753, "author_profile": "https://Stackoverflow.com/users/1753", "pm_score": 1, "selected": true, "text": "<p>Thanks everyone. The way I ended up doing it was sorta like this:</p>\n\n<pre><code>&lt;div id=\"top_margin\"&gt;&lt;/div&gt;\n&lt;div id=\"left_right_shadow\"&gt;this div has a 5 px tall repeating background that is a bit bigger than the width of my content block, shadow on the left, white space, shadow on the right\n &lt;div id=\"content\"&gt;Content as normal&lt;/div&gt;\n&lt;/div&gt;\n&lt;div id=\"bottom_margin\"&gt;This has the bottom shadow&lt;/div&gt;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753/" ]
I'm looking at all the CSS Drop shadow tutorials, which are great. Unfortunately, I need to put a shadow on three sides of a block element (left, bottom, right). All the tutorials talk about shifting your block element up and to the left. Anyone have insights into putting a shadow on three or even four sides?
Thanks everyone. The way I ended up doing it was sorta like this: ``` <div id="top_margin"></div> <div id="left_right_shadow">this div has a 5 px tall repeating background that is a bit bigger than the width of my content block, shadow on the left, white space, shadow on the right <div id="content">Content as normal</div> </div> <div id="bottom_margin">This has the bottom shadow</div> ```
253,881
<p>Can't figure out why I'm getting 'SQL Statement ignored' and 'ORA-01775: looping chain of synonyms' on line 52 of this stored procedure. Got any ideas?</p> <pre><code>CREATE OR REPLACE PACKAGE PURGE_LOG_BY_EVENT_DAYS AS TYPE dual_cursorType IS REF CURSOR RETURN dual%ROWTYPE; PROCEDURE log_master_by_event_days (event_id NUMBER, purge_recs_older_than NUMBER, result_cursor OUT dual_cursorType); END PURGE_LOG_BY_EVENT_DAYS; / CREATE OR REPLACE PACKAGE BODY PURGE_LOG_BY_EVENT_DAYS AS err_msg VARCHAR2(4000); PROCEDURE log_master_by_event_days (event_id NUMBER, purge_recs_older_than NUMBER, result_cursor OUT dual_cursorType) IS TYPE type_rowid IS TABLE OF ROWID INDEX BY BINARY_INTEGER; TYPE type_ref_cur IS REF CURSOR; l_rid type_rowid; c1 type_ref_cur; l_sql_stmt VARCHAR2(4000); proc_start_time DATE := sysdate; purge_date DATE; l_bulk_collect_limit NUMBER := 1000; retry NUMBER := 5; retry_count NUMBER := 0; loop_count NUMBER := 0; err_code VARCHAR2(10); BEGIN purge_date := to_date(sysdate - purge_recs_older_than); l_sql_stmt := ''; l_sql_stmt := l_sql_stmt ||' SELECT rowid FROM LOG_MASTER '; l_sql_stmt := l_sql_stmt ||' WHERE last_changed_date &lt; :purge_date'; l_sql_stmt := l_sql_stmt ||' AND event_id = :event_id'; -- The following while loop -- executes the purge code -- 'retry' number of times in case of ORA-01555 WHILE retry &gt; 0 LOOP BEGIN -- START of purge code OPEN c1 FOR l_sql_stmt USING purge_date, event_id; LOOP FETCH c1 BULK COLLECT into l_rid LIMIT l_bulk_collect_limit; FORALL i IN 1..l_rid.COUNT DELETE from log_master WHERE rowid = l_rid(i); COMMIT; loop_count := loop_count + 1; EXIT WHEN c1%NOTFOUND; END LOOP; CLOSE c1; -- End of purge code -- if processing reached this point -- Process completed successfuly, set retry = 0 to exit loop retry := 0; EXCEPTION WHEN OTHERS THEN -- ==================================== -- Get error msg -- ==================================== ROLLBACK; err_code := sqlcode; dbms_output.put_line(err_code); -- ==================================== -- Check if it is 01555 -- if so retry, else exit loop -- ==================================== retry := retry - 1; if err_code = '-1555' and retry &gt; 0 THEN CLOSE c1; retry_count := retry_count + 1; else err_msg := sqlerrm; exit; end if; END; END LOOP; IF err_msg IS NULL THEN open result_cursor for select '1 - PURGE_LOG_BY_EVENT_DAYS ran successfully (event_id : '||event_id||', loop_count : '||loop_count||', bulk_limit : '||l_bulk_collect_limit||', retries : '||retry_count||') ' from dual; ELSE open result_cursor for select '2 - PURGE_LOG_BY_EVENT_DAYS After (event_id : '||event_id||', loop_count : '||loop_count||', bulk_limit : '||l_bulk_collect_limit||', retries : '||retry_count||') with Error: ' || err_msg from dual; END IF; END log_master_by_event_days; END PURGE_LOG_BY_EVENT_DAYS; </code></pre>
[ { "answer_id": 253909, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT table_owner, table_name, db_link\n FROM dba_synonyms \n WHERE owner = 'PUBLIC' and db_link is not null\n</code></pre>\n\n<p>returns 0 rows\nas far as i know, there are no synonyms.......</p>\n" }, { "answer_id": 254275, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 1, "selected": false, "text": "<p>I have no idea why you're getting the synonym error. But that's a lot of code for something that should be a single DELETE statement. I assume you've changed it to commit-every-n to avoid rollback errors. It would be nice if you could get your DBA to increase the undo space so you can actually do the work you need to do. Failing that, I think you can still make it much simpler:</p>\n\n<pre><code>LOOP\n DELETE FROM log_master\n WHERE last_changed_date &lt; :purge_date\n AND event_id = :event_id\n AND rownum &lt;= :batch_delete_limit\n USING purge_date, event_id, l_bulk_collect_limit;\n EXIT WHEN SQL%NOTFOUND;\nEND LOOP;\n</code></pre>\n\n<p>And you can throw your retry logic around that if you want.</p>\n\n<p>Apologies if I've missed some subtlety that makes this different from what you're doing.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can't figure out why I'm getting 'SQL Statement ignored' and 'ORA-01775: looping chain of synonyms' on line 52 of this stored procedure. Got any ideas? ``` CREATE OR REPLACE PACKAGE PURGE_LOG_BY_EVENT_DAYS AS TYPE dual_cursorType IS REF CURSOR RETURN dual%ROWTYPE; PROCEDURE log_master_by_event_days (event_id NUMBER, purge_recs_older_than NUMBER, result_cursor OUT dual_cursorType); END PURGE_LOG_BY_EVENT_DAYS; / CREATE OR REPLACE PACKAGE BODY PURGE_LOG_BY_EVENT_DAYS AS err_msg VARCHAR2(4000); PROCEDURE log_master_by_event_days (event_id NUMBER, purge_recs_older_than NUMBER, result_cursor OUT dual_cursorType) IS TYPE type_rowid IS TABLE OF ROWID INDEX BY BINARY_INTEGER; TYPE type_ref_cur IS REF CURSOR; l_rid type_rowid; c1 type_ref_cur; l_sql_stmt VARCHAR2(4000); proc_start_time DATE := sysdate; purge_date DATE; l_bulk_collect_limit NUMBER := 1000; retry NUMBER := 5; retry_count NUMBER := 0; loop_count NUMBER := 0; err_code VARCHAR2(10); BEGIN purge_date := to_date(sysdate - purge_recs_older_than); l_sql_stmt := ''; l_sql_stmt := l_sql_stmt ||' SELECT rowid FROM LOG_MASTER '; l_sql_stmt := l_sql_stmt ||' WHERE last_changed_date < :purge_date'; l_sql_stmt := l_sql_stmt ||' AND event_id = :event_id'; -- The following while loop -- executes the purge code -- 'retry' number of times in case of ORA-01555 WHILE retry > 0 LOOP BEGIN -- START of purge code OPEN c1 FOR l_sql_stmt USING purge_date, event_id; LOOP FETCH c1 BULK COLLECT into l_rid LIMIT l_bulk_collect_limit; FORALL i IN 1..l_rid.COUNT DELETE from log_master WHERE rowid = l_rid(i); COMMIT; loop_count := loop_count + 1; EXIT WHEN c1%NOTFOUND; END LOOP; CLOSE c1; -- End of purge code -- if processing reached this point -- Process completed successfuly, set retry = 0 to exit loop retry := 0; EXCEPTION WHEN OTHERS THEN -- ==================================== -- Get error msg -- ==================================== ROLLBACK; err_code := sqlcode; dbms_output.put_line(err_code); -- ==================================== -- Check if it is 01555 -- if so retry, else exit loop -- ==================================== retry := retry - 1; if err_code = '-1555' and retry > 0 THEN CLOSE c1; retry_count := retry_count + 1; else err_msg := sqlerrm; exit; end if; END; END LOOP; IF err_msg IS NULL THEN open result_cursor for select '1 - PURGE_LOG_BY_EVENT_DAYS ran successfully (event_id : '||event_id||', loop_count : '||loop_count||', bulk_limit : '||l_bulk_collect_limit||', retries : '||retry_count||') ' from dual; ELSE open result_cursor for select '2 - PURGE_LOG_BY_EVENT_DAYS After (event_id : '||event_id||', loop_count : '||loop_count||', bulk_limit : '||l_bulk_collect_limit||', retries : '||retry_count||') with Error: ' || err_msg from dual; END IF; END log_master_by_event_days; END PURGE_LOG_BY_EVENT_DAYS; ```
I have no idea why you're getting the synonym error. But that's a lot of code for something that should be a single DELETE statement. I assume you've changed it to commit-every-n to avoid rollback errors. It would be nice if you could get your DBA to increase the undo space so you can actually do the work you need to do. Failing that, I think you can still make it much simpler: ``` LOOP DELETE FROM log_master WHERE last_changed_date < :purge_date AND event_id = :event_id AND rownum <= :batch_delete_limit USING purge_date, event_id, l_bulk_collect_limit; EXIT WHEN SQL%NOTFOUND; END LOOP; ``` And you can throw your retry logic around that if you want. Apologies if I've missed some subtlety that makes this different from what you're doing.
253,911
<p>I have a case that keeps coming up where I'm using a ListView or similar control with a simple array such as string[].</p> <p>Is there a way to use the DataKeyNames property when you are binding to simple collections?</p>
[ { "answer_id": 253939, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 0, "selected": false, "text": "<p>Try using a Generic List with objects object. The example below is C# 3.0. Say you want a list of letters:</p>\n\n<pre><code>public class LettersInfo\n{\n public String Letter { get; set; }\n}\n</code></pre>\n\n<p>then make a list:</p>\n\n<pre><code>List&lt;LettersInfo&gt; list = new List&lt;LettersInfo&gt;();\nlist.add(new LettersInfo{ Letter = \"A\" });\nlist.add(new LettersInfo{ Letter = \"B\" });\nlist.add(new LettersInfo{ Letter = \"C\" });\n</code></pre>\n\n<p>then bind it to the listview</p>\n\n<pre><code>lv.DataKeyNames = \"Letter\";\nlv.DataSource = list;\nlv.DataBind();\n</code></pre>\n" }, { "answer_id": 264452, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 3, "selected": true, "text": "<p>You could do this with Linq:</p>\n\n<pre><code>string [] files = ...;\n\nvar list = from f in files\n select new { Letter = f };\n\n// anonymous type created with member called Letter\n\nlv.DataKeyNames = \"Letter\";\nlv.DataSource = list;\nlv.DataBind();\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10115/" ]
I have a case that keeps coming up where I'm using a ListView or similar control with a simple array such as string[]. Is there a way to use the DataKeyNames property when you are binding to simple collections?
You could do this with Linq: ``` string [] files = ...; var list = from f in files select new { Letter = f }; // anonymous type created with member called Letter lv.DataKeyNames = "Letter"; lv.DataSource = list; lv.DataBind(); ```
253,913
<p>I have a function I've written that was initially supposed to take a string field and populate an excel spreadsheet with the values. Those values continually came up null. I started tracking it back to the recordset and found that despite the query being valid and running properly through the Access query analyzer the recordset was empty or had missing fields.</p> <p>To test the problem, I created a sub in which I created a query, opened a recordset, and then paged through the values (outputting them to a messagebox). The most perplexing part of the problem seems to revolve around the "WHERE" clause of the query. If I don't put a "WHERE" clause on the query, the recordset always has data and the values for "DESCRIPTION" are normal.</p> <p>If I put <em>anything</em> in for the WHERE clause the recordset comes back either totally empty (<code>rs.EOF = true</code>) or the Description field is totally blank where the other fields have values. I want to stress again that if I debug.print the query, I can copy/paste it into the query analyzer and get a valid and returned values that I expect.</p> <p>I'd sure appreciate some help with this. Thank you!</p> <pre><code>Private Sub NewTest() ' Dimension Variables '---------------------------------------------------------- Dim rsNewTest As ADODB.Recordset Dim sqlNewTest As String Dim Counter As Integer ' Set variables '---------------------------------------------------------- Set rsNewTest = New ADODB.Recordset sqlNewTest = "SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, " &amp; _ "dbo_part.partdescription as Description, dbo_partmtl.qtyper as [Qty Per] " &amp; _ "FROM dbo_partmtl " &amp; _ "LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum " &amp; _ "WHERE dbo_partmtl.mtlpartnum=" &amp; Chr(34) &amp; "3C16470" &amp; Chr(34) ' Open recordset rsNewTest.Open sqlNewTest, CurrentProject.Connection, adOpenDynamic, adLockOptimistic Do Until rsNewTest.EOF For Counter = 0 To rsNewTest.Fields.Count - 1 MsgBox rsNewTest.Fields(Counter).Name Next MsgBox rsNewTest.Fields("Description") rsNewTest.MoveNext Loop ' close the recordset rsNewTest.Close Set rsNewTest = Nothing End Sub </code></pre> <p>EDIT: Someone requested that I post the DEBUG.PRINT of the query. Here it is:</p> <pre><code>SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, dbo_part.partdescription as [Description], dbo_partmtl.qtyper as [Qty Per] FROM dbo_partmtl LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum WHERE dbo_partmtl.mtlpartnum='3C16470' </code></pre> <hr> <p>I have tried double and single quotes using ASCII characters and implicitly.</p> <p>For example:</p> <pre><code>"WHERE dbo_partmtl.mtlpartnum='3C16470'" </code></pre> <p>I even tried your suggestion with chr(39):</p> <pre><code>"WHERE dbo_partmtl.mtlpartnum=" &amp; Chr(39) &amp; "3C16470" &amp; Chr(39) </code></pre> <p>Both return a null value for description. However, if I debug.print the query and paste it into the Access query analyzer, it displays just fine. Again (as a side note), if I do a LIKE statement in the WHERE clause, it will give me a completely empty recordset. Something is really wonky here.</p> <hr> <p>Here is an interesting tidbit. The tables are linked to a <code>SQL Server</code>. If I copy the tables (data and structure) locally, the ADO code above worked flawlessly. If I use DAO it works fine. I've tried this code on <code>Windows XP</code>, <code>Access 2003</code>, and various versions of <code>ADO (2.5, 2.6, 2.8)</code>. <code>ADO</code> will not work if the tables are linked.</p> <p>There is some flaw in ADO that causes the issue.</p> <hr> <p>Absolutely I do. Remember, the <code>DEBUG.PRINT</code> query you see runs perfectly in the query analyzer. It returns the following:</p> <pre> Job/Sub Rev Description Qty Per 36511C01 A MAIN ELECTRICAL ENCLOSURE 1 36515C0V A VISION SYSTEM 1 36529C01 A MAIN ELECTRICAL ENCLOSURE 1 </pre> <p>However, the same query returns empty values for Description (everything else is the same) when run through the recordset (messagebox errors because of "Null" value).</p> <hr> <p>I tried renaming the "description" field to "testdep", but it's still empty. The only way to make it display data is to remove the WHERE section of the query. I'm starting to believe this is a problem with ADO. Maybe I'll rewriting it with DAO and seeing what results i get.</p> <p>EDIT: I also tried compacting and repairing a couple of times. No dice.</p>
[ { "answer_id": 253926, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 1, "selected": false, "text": "<p>Description is a reserved word - put some [] brackets around it in the SELECT statement</p>\n\n<p>EDIT</p>\n\n<p>Try naming the column something besides Description</p>\n\n<p>Also are you sure you are using the same values in the where clause - because it is a left join so the Description field will be blank if there is no corresponding record in dbo_part </p>\n\n<p>EDIT AGAIN</p>\n\n<p>If you are getting funny results - try a Compact/Repair Database - It might be corrupted</p>\n" }, { "answer_id": 253953, "author": "Mr Furious", "author_id": 33124, "author_profile": "https://Stackoverflow.com/users/33124", "pm_score": 0, "selected": false, "text": "<p>I put brackets around the word \"Description\" in the SELECT statement, but it's behavior remains. It works fine as long as I don't put anything in the WHERE clause. I've found if I put anything in the where clause, the description is blank (despite showing up in the Query analyzer). If I use a LIKE statement in the WHERE clause, the entire recordset is empty but it still works properly in the Query Analyzer.</p>\n" }, { "answer_id": 254202, "author": "Mr Furious", "author_id": 33124, "author_profile": "https://Stackoverflow.com/users/33124", "pm_score": 1, "selected": false, "text": "<p>Well, what I feared is the case. It works FINE with DAO but not ADO.</p>\n\n<p>Here is the working code:</p>\n\n<pre><code>Private Sub AltTest()\n\n' Dimension Variables\n'----------------------------------------------------------\nDim rsNewTest As DAO.Recordset\nDim dbl As DAO.Database\n\nDim sqlNewTest As String\nDim Counter As Integer\n\n' Set variables\n'----------------------------------------------------------\n\nsqlNewTest = \"SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, \" &amp; _\n \"dbo_part.partdescription as [TestDep], dbo_partmtl.qtyper as [Qty Per] \" &amp; _\n \"FROM dbo_partmtl \" &amp; _\n \"LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum \" &amp; _\n \"WHERE dbo_partmtl.mtlpartnum=\" &amp; Chr(39) &amp; \"3C16470\" &amp; Chr(39)\n\n\nDebug.Print \"sqlNewTest: \" &amp; sqlNewTest\nSet dbl = CurrentDb()\nSet rsNewTest = dbl.OpenRecordset(sqlNewTest, dbOpenDynaset)\n\n\n' rsnewtest.OpenRecordset\n\n Do Until rsNewTest.EOF\n\n For Counter = 0 To rsNewTest.Fields.Count - 1\n MsgBox rsNewTest.Fields(Counter).Name\n Next\n\n MsgBox rsNewTest.Fields(\"TestDep\")\n\n rsNewTest.MoveNext\n\n Loop\n\n' close the recordset\n\ndbl.Close\nSet rsNewTest = Nothing\n</code></pre>\n\n<p>End Sub</p>\n\n<p>I don't use DAO anywhere in this database and would prefer not to start. Where do we go from here?</p>\n" }, { "answer_id": 254633, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 0, "selected": false, "text": "<p>Ultimately I think it's a problem with running ADO 2.8 on Vista 64</p>\n\n<p>Personally I have always used DAO in Access projects. </p>\n" }, { "answer_id": 441238, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>When using ADO LIKE searches must use % instead of *. I know * works in Access but for some stupid reason ADO won't work unless you use % instead. </p>\n\n<p>I had the same problem and ran accoss this forum while trying to fix it. Replacing *'s with %'s worked for me.</p>\n" }, { "answer_id": 6348698, "author": "Zac Ortiz", "author_id": 798333, "author_profile": "https://Stackoverflow.com/users/798333", "pm_score": 1, "selected": false, "text": "<p>I know some time has passed since this thread started, but just in case you're wondering, I have found out some curious about Access 2003 and the bug may have carried over to 2007 (as I can see it has).</p>\n\n<p>I've had a similar problem with a WHERE clause because I needed records from a date field that also contained time, so the entire field contents would look like #6/14/2011 11:50:25 AM# (#'s added for formatting purposes).</p>\n\n<p>Same issue as above, query works fine with the \"WHERE ((tblTransactions.TransactionDate) Like '\" &amp; QueryDate &amp; \"*');\" in the query design view, but it won't work in the VBA code using ADO.</p>\n\n<p>So I resorted to using \"WHERE ((tblTransactions.TransactionDate) Like '\" &amp; QueryDate &amp; \" %%:%%:%% %M');\" in the VBA code, with ADO and it works just fine. Displays the record I was looking for, the trick is not to use \"*\" in the Like clause; or at least that was the issue in my case.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33124/" ]
I have a function I've written that was initially supposed to take a string field and populate an excel spreadsheet with the values. Those values continually came up null. I started tracking it back to the recordset and found that despite the query being valid and running properly through the Access query analyzer the recordset was empty or had missing fields. To test the problem, I created a sub in which I created a query, opened a recordset, and then paged through the values (outputting them to a messagebox). The most perplexing part of the problem seems to revolve around the "WHERE" clause of the query. If I don't put a "WHERE" clause on the query, the recordset always has data and the values for "DESCRIPTION" are normal. If I put *anything* in for the WHERE clause the recordset comes back either totally empty (`rs.EOF = true`) or the Description field is totally blank where the other fields have values. I want to stress again that if I debug.print the query, I can copy/paste it into the query analyzer and get a valid and returned values that I expect. I'd sure appreciate some help with this. Thank you! ``` Private Sub NewTest() ' Dimension Variables '---------------------------------------------------------- Dim rsNewTest As ADODB.Recordset Dim sqlNewTest As String Dim Counter As Integer ' Set variables '---------------------------------------------------------- Set rsNewTest = New ADODB.Recordset sqlNewTest = "SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, " & _ "dbo_part.partdescription as Description, dbo_partmtl.qtyper as [Qty Per] " & _ "FROM dbo_partmtl " & _ "LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum " & _ "WHERE dbo_partmtl.mtlpartnum=" & Chr(34) & "3C16470" & Chr(34) ' Open recordset rsNewTest.Open sqlNewTest, CurrentProject.Connection, adOpenDynamic, adLockOptimistic Do Until rsNewTest.EOF For Counter = 0 To rsNewTest.Fields.Count - 1 MsgBox rsNewTest.Fields(Counter).Name Next MsgBox rsNewTest.Fields("Description") rsNewTest.MoveNext Loop ' close the recordset rsNewTest.Close Set rsNewTest = Nothing End Sub ``` EDIT: Someone requested that I post the DEBUG.PRINT of the query. Here it is: ``` SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, dbo_part.partdescription as [Description], dbo_partmtl.qtyper as [Qty Per] FROM dbo_partmtl LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum WHERE dbo_partmtl.mtlpartnum='3C16470' ``` --- I have tried double and single quotes using ASCII characters and implicitly. For example: ``` "WHERE dbo_partmtl.mtlpartnum='3C16470'" ``` I even tried your suggestion with chr(39): ``` "WHERE dbo_partmtl.mtlpartnum=" & Chr(39) & "3C16470" & Chr(39) ``` Both return a null value for description. However, if I debug.print the query and paste it into the Access query analyzer, it displays just fine. Again (as a side note), if I do a LIKE statement in the WHERE clause, it will give me a completely empty recordset. Something is really wonky here. --- Here is an interesting tidbit. The tables are linked to a `SQL Server`. If I copy the tables (data and structure) locally, the ADO code above worked flawlessly. If I use DAO it works fine. I've tried this code on `Windows XP`, `Access 2003`, and various versions of `ADO (2.5, 2.6, 2.8)`. `ADO` will not work if the tables are linked. There is some flaw in ADO that causes the issue. --- Absolutely I do. Remember, the `DEBUG.PRINT` query you see runs perfectly in the query analyzer. It returns the following: ``` Job/Sub Rev Description Qty Per 36511C01 A MAIN ELECTRICAL ENCLOSURE 1 36515C0V A VISION SYSTEM 1 36529C01 A MAIN ELECTRICAL ENCLOSURE 1 ``` However, the same query returns empty values for Description (everything else is the same) when run through the recordset (messagebox errors because of "Null" value). --- I tried renaming the "description" field to "testdep", but it's still empty. The only way to make it display data is to remove the WHERE section of the query. I'm starting to believe this is a problem with ADO. Maybe I'll rewriting it with DAO and seeing what results i get. EDIT: I also tried compacting and repairing a couple of times. No dice.
When using ADO LIKE searches must use % instead of \*. I know \* works in Access but for some stupid reason ADO won't work unless you use % instead. I had the same problem and ran accoss this forum while trying to fix it. Replacing \*'s with %'s worked for me.
253,937
<p>If I wanted to find checked check boxes on an ASP.NET page I could use the following LINQ query.</p> <pre><code>var checkBoxes = this.Controls .OfType&lt;CheckBox&gt;() .TakeWhile&lt;CheckBox&gt;(cb =&gt; cb.Checked); </code></pre> <p>That works fine if the checkboxes are nested in the current control collection, but I'd like to know how to extend the search by drilling down into the control collections of the top-level controls.</p> <p>The question was asked here:</p> <p><a href="https://stackoverflow.com/questions/28642/finding-controls-that-use-a-certain-interface-in-aspnet">Finding controls that use a certain interface in ASP.NET</a></p> <p>And received non-LINQ answers, I already have my own version of a recursive control search on type and ID as extension methods, but I just wondered how easy this is to do in LINQ?</p>
[ { "answer_id": 253962, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>Take the type/ID checking out of the recursion, so just have a \"give me all the controls, recursively\" method, e.g.</p>\n\n<pre><code>public static IEnumerable&lt;Control&gt; GetAllControls(this Control parent)\n{\n foreach (Control control in parent.Controls)\n {\n yield return control;\n foreach(Control descendant in control.GetAllControls())\n {\n yield return descendant;\n }\n }\n}\n</code></pre>\n\n<p>That's somewhat inefficient (in terms of creating lots of iterators) but I doubt that you'll have a <em>very</em> deep tree.</p>\n\n<p>You can then write your original query as:</p>\n\n<pre><code>var checkBoxes = this.GetAllControls()\n .OfType&lt;CheckBox&gt;()\n .TakeWhile&lt;CheckBox&gt;(cb =&gt; cb.Checked);\n</code></pre>\n\n<p>(EDIT: Changed AllControls to GetAllControls and use it properly as a method.)</p>\n" }, { "answer_id": 254056, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>My suggestion to make the <code>AllControls</code> recursive is:</p>\n\n<pre><code> public static IEnumerable&lt;Control&gt; AllControls(this Control parent)\n {\n foreach (Control control in parent.Controls)\n {\n yield return control;\n }\n foreach (Control control in parent.Controls)\n {\n foreach (Control cc in AllControls(control)) yield return cc;\n }\n }\n</code></pre>\n\n<p>The second <code>foreach</code> looks weird, but this is the only way I know to \"flatten\" the recursive call.</p>\n" }, { "answer_id": 5185293, "author": "Arthur Dzhelali", "author_id": 643538, "author_profile": "https://Stackoverflow.com/users/643538", "pm_score": 2, "selected": false, "text": "<pre><code>public static IEnumerable&lt;Control&gt; AllControls(this Control container)\n{\n //Get all controls\n var controls = container.Controls.Cast&lt;Control&gt;();\n\n //Get all children\n var children = controls.Select(c =&gt; c.AllControls());\n\n //combine controls and children\n var firstGen = controls.Concat(children.SelectMany(b =&gt; b));\n\n return firstGen;\n}\n</code></pre>\n\n<p>Now based on the above function, we can do something like this:</p>\n\n<pre><code>public static Control FindControl(this Control container, string Id)\n{\n var child = container.AllControls().FirstOrDefault(c =&gt; c.ID == Id);\n return child;\n}\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29294/" ]
If I wanted to find checked check boxes on an ASP.NET page I could use the following LINQ query. ``` var checkBoxes = this.Controls .OfType<CheckBox>() .TakeWhile<CheckBox>(cb => cb.Checked); ``` That works fine if the checkboxes are nested in the current control collection, but I'd like to know how to extend the search by drilling down into the control collections of the top-level controls. The question was asked here: [Finding controls that use a certain interface in ASP.NET](https://stackoverflow.com/questions/28642/finding-controls-that-use-a-certain-interface-in-aspnet) And received non-LINQ answers, I already have my own version of a recursive control search on type and ID as extension methods, but I just wondered how easy this is to do in LINQ?
Take the type/ID checking out of the recursion, so just have a "give me all the controls, recursively" method, e.g. ``` public static IEnumerable<Control> GetAllControls(this Control parent) { foreach (Control control in parent.Controls) { yield return control; foreach(Control descendant in control.GetAllControls()) { yield return descendant; } } } ``` That's somewhat inefficient (in terms of creating lots of iterators) but I doubt that you'll have a *very* deep tree. You can then write your original query as: ``` var checkBoxes = this.GetAllControls() .OfType<CheckBox>() .TakeWhile<CheckBox>(cb => cb.Checked); ``` (EDIT: Changed AllControls to GetAllControls and use it properly as a method.)
253,938
<p>I have some complex stored procedures that may return many thousands of rows, and take a long time to complete.</p> <p>Is there any way to find out how many rows are going to be returned before the query executes and fetches the data?</p> <p>This is with Visual Studio 2005, a Winforms application and SQL Server 2005.</p>
[ { "answer_id": 253952, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 0, "selected": false, "text": "<p>make a stored proc to count the rows first.</p>\n\n<p>SELECT COUNT(*) FROM table</p>\n" }, { "answer_id": 253955, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 3, "selected": false, "text": "<p>You mentioned your stored procedures take a long time to complete. Is the majority of the time taken up during the process of selecting the rows from the database or returning the rows to the caller?</p>\n\n<p>If it is the latter, maybe you can create a mirror version of your SP that just gets the count instead of the actual rows. If it is the former, well, there isn't really that much you can do since it is the act of finding the eligible rows which is slow.</p>\n" }, { "answer_id": 253956, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Unless there's some aspect of the business logic of you app that allows calculating this, no. The database it going to have to do all the where &amp; join logic to figure out how line rows, and that's the vast majority of the time spend in the SP.</p>\n" }, { "answer_id": 253957, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>You can't get the rowcount of a procedure without executing the procedure. </p>\n\n<p>You could make a different procedure that accepts the same parameters, the purpose of which is to tell you how many rows the other procedure should return. However, the steps required by this procedure would normally be so similar to those of the main procedure that it should take just about as long as just executing the main procedure.</p>\n" }, { "answer_id": 253965, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 0, "selected": false, "text": "<p>You would have to write a different version of the stored procedure to get a row count. This one would probably be much faster because you could eliminate joining tables which you aren't filtered against, remove ordering, etc. For example if your stored proc executed the sql such as:</p>\n\n<pre><code>select firstname, lastname, email, orderdate from \ncustomer inner join productorder on customer.customerid=productorder.productorderid\nwhere orderdate&gt;@orderdate order by lastname, firstname;\n</code></pre>\n\n<p>your counting version would be something like:</p>\n\n<pre><code>select count(*) from productorder where orderdate&gt;@orderdate;\n</code></pre>\n" }, { "answer_id": 253966, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>Not in general.</p>\n\n<p>Through knowledge about the operation of the stored procedure, you may be able to get either an estimate or an accurate count (for instance, if the \"core\" or \"base\" table of the query is able to be quickly calculated, but it is complex joins and/or summaries which drive the time upwards).</p>\n\n<p>But you would have to call the counting SP first and then the data SP or you could look at using a multiple result set SP.</p>\n" }, { "answer_id": 253986, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>It could take as long to get a row count as to get the actual data, so I wouldn't advodate performing a count in most cases.</p>\n\n<p>Some possibilities:</p>\n\n<p>1) Does SQL Server expose its query optimiser findings in some way? i.e. can you parse the query and then obtain an <em>estimate</em> of the rowcount? (I don't know SQL Server).</p>\n\n<p>2) Perhaps based on the criteria the user gives you can perform some estimations of your own. For example, if the user enters 'S%' in the customer surname field to query orders you could determine that that matches 7% (say) of the customer records, and extrapolate that the query <em>may</em> return about 7% of the order records.</p>\n" }, { "answer_id": 254001, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 1, "selected": true, "text": "<p>A solution to your problem might be to re-write the stored procedure so that it limits the result set to some number, like:</p>\n\n<pre><code>SELECT TOP 1000 * FROM tblWHATEVER\n</code></pre>\n\n<p>in SQL Server, or</p>\n\n<pre><code>SELECT * FROM tblWHATEVER WHERE ROWNUM &lt;= 1000\n</code></pre>\n\n<p>in Oracle. Or implement a paging solution so that the result set of each call is acceptably small.</p>\n" }, { "answer_id": 254219, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>Going on what Tony Andrews said in his answer, you can get an estimated query plan of the call to your query with:</p>\n\n<pre><code>SET showplan_text OFF\nGO\nSET showplan_all on\nGO\n--Replace with call you your stored procedure\nselect * from MyTable\nGO \nSET showplan_all ofF\nGO\n</code></pre>\n\n<p>This should return a table, or many tables which will let you get the estimated row count of your query.</p>\n" }, { "answer_id": 254643, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "<p>You need to analyze the returned data set, to determine what is a logical, (meaningful) primary key for the result set that is being returned. In general this WILL be much faster than the complete procedure, because the server is not constructing a result set from data in all the columns of each row of each table, it is simply counting the rows... In general, it may not even need to read the actual table rows off disk to do this, it may simply need to count index nodes... </p>\n\n<p>Then write another SQL statement that only includes the tables necessary to generate those key columns (Hopefully this is a subset of the tables in the main sql query), and the same where clause with the same filtering predicate values... </p>\n\n<p>Then add another Optional parameter to the Stored Proc called, say, @CountsOnly, with a default of false (0) as so...</p>\n\n<pre><code>Alter Procedure &lt;storedProcName&gt;\n@param1 Type, \n-- Other current params\n@CountsOnly TinyInt = 0\nAs\nSet NoCount On\n\n If @CountsOnly = 1\n Select Count(*) \n From TableA A \n Join TableB B On etc. etc...\n Where &lt; here put all Filtering predicates &gt;\n\n Else\n &lt;Here put old SQL That returns complete resultset with all data&gt;\n\n Return 0\n</code></pre>\n\n<p>You can then just call the same stored proc with @CountsOnly set equal to 1 to just get the count of records. Old code that calls the proc would still function as it used to, since the parameter value is set to default to false (0), if it is not included</p>\n" }, { "answer_id": 254717, "author": "SeaDrive", "author_id": 19267, "author_profile": "https://Stackoverflow.com/users/19267", "pm_score": 0, "selected": false, "text": "<p>It's at least technically possible to run a procedure that puts the result set in a temporary table. Then you can find the number of rows before you move the data from server to application and would save having to create the result set twice.</p>\n\n<p>But I doubt it's worth the trouble unless creating the result set takes a very long time, and in that case it may be big enough that the temp table would be a problem. Almost certainly the time to move the big table over the network will be many times what is needed to create it.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18854/" ]
I have some complex stored procedures that may return many thousands of rows, and take a long time to complete. Is there any way to find out how many rows are going to be returned before the query executes and fetches the data? This is with Visual Studio 2005, a Winforms application and SQL Server 2005.
A solution to your problem might be to re-write the stored procedure so that it limits the result set to some number, like: ``` SELECT TOP 1000 * FROM tblWHATEVER ``` in SQL Server, or ``` SELECT * FROM tblWHATEVER WHERE ROWNUM <= 1000 ``` in Oracle. Or implement a paging solution so that the result set of each call is acceptably small.
253,987
<p><code>select max(DELIVERY_TIMESTAMP) from DOCUMENTS;</code> will return the time that the latest document was delivered. How do I return <strong>the other columns</strong> for the latest document? For example I want <code>DOC_NAME</code> for the document that was most recently delivered?</p> <p>I'm not sure how to form the <code>WHERE</code> clause.</p>
[ { "answer_id": 253995, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>Select Max(DELIVERY_TIMESTAMP), \n Doc_Name\nFrom TableName\nGroup By Doc_Name\n</code></pre>\n\n<p>That should do it, unless I missed something in the question.</p>\n" }, { "answer_id": 253996, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT\n DELIVERY_TIMESTAMP,\n OTHER_COLUMN\nFROM\n DOCUMENTS\nWHERE\n DELIVERY_TIMESTAMP = (SELECT MAX(DELIVERY_TIMESTAMP) FROM DOCUMENTS)\n</code></pre>\n" }, { "answer_id": 254003, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 4, "selected": true, "text": "<p>You have a few options</p>\n\n<pre><code>SELECT DOC_NAME\nFROM DOCUMENTS\nWHERE DELIVERY_TIMESTAMP IN (\n SELECT MAX(DELIVERY_TIMESTAMP)\n FROM DOCUMENTS\n)\n</code></pre>\n\n<p>Or with joins</p>\n\n<pre><code>SELECT DOC_NAME\nFROM DOCUMENTS\nINNER JOIN (\n SELECT MAX(DELIVERY_TIMESTAMP) AS MAX_DELIVERY_TIMESTAMP\n FROM DOCUMENTS\n) AS M\n ON M.MAX_DELIVERY_TIMESTAMP = DOCUMENTS.DELIVERY_TIMESTAMP\n</code></pre>\n\n<p>It gets more complicated if there are duplicates in a timestamp or you need multiple columns in your \"max\" criteria (because <code>MAX()</code> is only over the one column for all rows)</p>\n\n<p>This is where the <code>JOIN</code> option is the only option available, because a construction like this is not available (say multiple orders with identical timestamp):</p>\n\n<pre><code>SELECT DOC_NAME\nFROM DOCUMENTS\nWHERE (DELIVERY_TIMESTAMP, ORDERID) IN (\n SELECT TOP 1 DELIVERY_TIMESTAMP, ORDERID\n FROM DOCUMENTS\n ORDER BY DELIVERY_TIMESTAMP DESC, ORDERID DESC\n)\n</code></pre>\n\n<p>Where you in fact, would need to do:</p>\n\n<pre><code>SELECT DOC_NAME\nFROM DOCUMENTS\nINNER JOIN (\n SELECT TOP 1 DELIVERY_TIMESTAMP, ORDERID\n FROM DOCUMENTS\n ORDER BY DELIVERY_TIMESTAMP DESC, ORDERID DESC\n) AS M\n ON M.DELIVERY_TIMESTAMP = DOCUMENTS.DELIVERY_TIMESTAMP\n AND M.ORDERID = DOCUMENTS.ORDERID\n</code></pre>\n" }, { "answer_id": 254015, "author": "TrevorD", "author_id": 12492, "author_profile": "https://Stackoverflow.com/users/12492", "pm_score": 2, "selected": false, "text": "<p>In MSSQL, the following works too:</p>\n\n<pre><code>SELECT TOP 1 * FROM DOCUMENTS ORDER BY DELIVERY_TIMESTAMP DESC\n</code></pre>\n" }, { "answer_id": 254019, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 2, "selected": false, "text": "<p>On some versions of SQL (i.e. MySQL) you can do this:</p>\n\n<pre><code>SELECT *\nFROM DOCUMENTS\nORDER BY DELIVERY_TIMESTAMP DESC\nLIMIT 1\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
`select max(DELIVERY_TIMESTAMP) from DOCUMENTS;` will return the time that the latest document was delivered. How do I return **the other columns** for the latest document? For example I want `DOC_NAME` for the document that was most recently delivered? I'm not sure how to form the `WHERE` clause.
You have a few options ``` SELECT DOC_NAME FROM DOCUMENTS WHERE DELIVERY_TIMESTAMP IN ( SELECT MAX(DELIVERY_TIMESTAMP) FROM DOCUMENTS ) ``` Or with joins ``` SELECT DOC_NAME FROM DOCUMENTS INNER JOIN ( SELECT MAX(DELIVERY_TIMESTAMP) AS MAX_DELIVERY_TIMESTAMP FROM DOCUMENTS ) AS M ON M.MAX_DELIVERY_TIMESTAMP = DOCUMENTS.DELIVERY_TIMESTAMP ``` It gets more complicated if there are duplicates in a timestamp or you need multiple columns in your "max" criteria (because `MAX()` is only over the one column for all rows) This is where the `JOIN` option is the only option available, because a construction like this is not available (say multiple orders with identical timestamp): ``` SELECT DOC_NAME FROM DOCUMENTS WHERE (DELIVERY_TIMESTAMP, ORDERID) IN ( SELECT TOP 1 DELIVERY_TIMESTAMP, ORDERID FROM DOCUMENTS ORDER BY DELIVERY_TIMESTAMP DESC, ORDERID DESC ) ``` Where you in fact, would need to do: ``` SELECT DOC_NAME FROM DOCUMENTS INNER JOIN ( SELECT TOP 1 DELIVERY_TIMESTAMP, ORDERID FROM DOCUMENTS ORDER BY DELIVERY_TIMESTAMP DESC, ORDERID DESC ) AS M ON M.DELIVERY_TIMESTAMP = DOCUMENTS.DELIVERY_TIMESTAMP AND M.ORDERID = DOCUMENTS.ORDERID ```
254,002
<p>I am looking for an expression for the .hgignore file, to ignore all files beneath a specified folder.</p> <p>eg: I would like to ignore all files and folders beneath bin</p> <p>Actually any advice on how the expressions are formed would be great</p>
[ { "answer_id": 254049, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 2, "selected": false, "text": "<p>Nevermind, I got it</p>\n\n<pre><code>syntax: regexp\nbin\\\\*\n</code></pre>\n\n<p>expressions follow standard perl regular expression syntax.</p>\n" }, { "answer_id": 255094, "author": "Ry4an Brase", "author_id": 8992, "author_profile": "https://Stackoverflow.com/users/8992", "pm_score": 8, "selected": true, "text": "<p>Alternately:</p>\n\n<pre><code>syntax: glob\nbin/**\n</code></pre>\n" }, { "answer_id": 255123, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 3, "selected": false, "text": "<p>Both of those will also filter out a directory called <code>cabin</code>, which might not be what you want. If you're filtering top-level, you can use:</p>\n\n<pre><code>^/bin/\n</code></pre>\n\n<p>For <code>bin</code> directories below your root, you can omit the ^. There is no need to specify syntax, regexp is the default.</p>\n" }, { "answer_id": 309976, "author": "user2427", "author_id": 1356709, "author_profile": "https://Stackoverflow.com/users/1356709", "pm_score": -1, "selected": false, "text": "<p>to ignore .class files </p>\n\n<pre><code>syntax: regexp\n?\\.class\n</code></pre>\n" }, { "answer_id": 346233, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": false, "text": "<p>I did some experiments and I found that the regex syntax on Windows applies to the path starting with the current repository, with backslashes transformed to slashes.</p>\n\n<p>So if your repository is in E:\\Dev for example, <code>hg status</code> will apply the patterns against foo/bar/file1.c and such. Anchors apply to this path.</p>\n\n<p>So:</p>\n\n<ul>\n<li>Glob applies to path elements and is rooted to element parts</li>\n<li>foo matches any folder (or file) named foo (not to \"foobar\" nor \"barfoo\")</li>\n<li>*foo* matches any folder or file with \"foo\" in the name</li>\n<li>foo/bar* matches all files in \"foo\" folder starting with \"bar\"</li>\n</ul>\n\n<p><br></p>\n\n<ul>\n<li>Regex is case sensitive, not anchored</li>\n<li>Of course, backslash regex special characters like . (dot)</li>\n<li>/ matches \\ path separator on Windows. \\ doesn't match this separator...</li>\n<li>foo matches all files and folders with \"foo\" inside</li>\n<li>foo/ matches only folders ending with \"foo\"</li>\n<li>/foo/ matches the folder \"foo\" somewhere in the path</li>\n<li>/foo/bar/ matches the folder \"bar\" in the folder \"foo\" somewhere in the path</li>\n<li>^foo matches file or folder starting by foo at the root of the repository</li>\n<li>foo$ matches file ending with foo</li>\n</ul>\n\n<p>I hope this will help, I found the <a href=\"http://www.selenic.com/mercurial/hgignore.5.html\" rel=\"noreferrer\" title=\"HGIGNORE(5)\">HGIGNORE(5)</a> page a bit succinct.</p>\n" }, { "answer_id": 40598637, "author": "balrob", "author_id": 1676498, "author_profile": "https://Stackoverflow.com/users/1676498", "pm_score": 2, "selected": false, "text": "<p>syntax: glob\nbin/**</p>\n\n<p>This answer is shown above, however I'd also like to add that * and ** are handled differently. ** is recursive, * is not.</p>\n\n<p>See <a href=\"https://www.selenic.com/mercurial/hg.1.html#patterns\" rel=\"nofollow noreferrer\">Hg Patterns</a></p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4642/" ]
I am looking for an expression for the .hgignore file, to ignore all files beneath a specified folder. eg: I would like to ignore all files and folders beneath bin Actually any advice on how the expressions are formed would be great
Alternately: ``` syntax: glob bin/** ```
254,004
<p>I am using the EMMA tool for code coverage yet despite my best efforts, EMMA is refusing to see the original .java files and generate coverage on a line-by-line basis.</p> <p>We are using ANT to build the code and debug is set to true. I know that EMMA is measuring coverage as the .emma files seem to be generating and merging correctly. The reports are able to present high level method coverage with percentages. </p> <p>But why won't it see the .java files? All I get is: [source file 'a/b/c/d/e/f/code.java' not found in sourcepath]</p>
[ { "answer_id": 254041, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Are you setting the <code>sourcepath</code> in your <code>report</code> element?</p>\n\n<pre><code>&lt;report&gt;\n &lt;sourcepath&gt;\n &lt;pathelement path=\"${java.src.dir}\" /&gt;\n &lt;/sourcepath&gt;\n &lt;fileset dir=\"data\"&gt;\n &lt;include name=\"*.emma\" /&gt;\n &lt;/fileset&gt;\n\n &lt;txt outfile=\"coverage.txt\" /&gt;\n &lt;html outfile=\"coverage.html\" /&gt;\n&lt;/report&gt;\n</code></pre>\n" }, { "answer_id": 254067, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<p>Could you post the portion of your <code>build.xml</code> that generates the <code>EMMA</code> reports? Sounds like a <code>report sourcepath</code> issue.</p>\n\n<p><code>report sourcepath</code> should point to your <em>java</em> source.</p>\n\n<p>See <a href=\"http://emma.sourceforge.net/reference_single/reference.html#tool-ref.report.ANT\" rel=\"nofollow noreferrer\">sourcepath</a> in the EMMA reference. This can be a <em>path-like structure</em>, so you can include multiple source directories.</p>\n\n<p>As always, with ANT:</p>\n\n<ul>\n<li>execute the smallest possible build.xml with <code>-verbose</code> </li>\n<li><code>-debug</code> for even more information.</li>\n</ul>\n" }, { "answer_id": 254087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>does <code>{java.src.dir}</code> need to point to one specific <code>src</code> directory.</p>\n\n<p>This is no one single src directory as I am compiling multiple projects. Each with their own build.xml file.</p>\n\n<p>I believe this is the portion that generates all the coverage reports:</p>\n\n<pre><code> &lt;target name=\"emma.report\" if=\"use.emma\"&gt;\n &lt;emma enabled=\"true\"&gt;\n &lt;report sourcepath=\"${test.reports.dir}\"&gt;\n &lt;!-- collect all EMMA data dumps (metadata and runtime): --&gt; \n &lt;infileset dir=\"${test.data.dir}\" includes=\"*.emma\" /&gt; \n &lt;html outfile=\"${test.reports.dir}/coverage.html\" /&gt; \n &lt;/report&gt;\n &lt;/emma&gt;\n &lt;/target&gt;\n</code></pre>\n\n<p>EDIT: I changed the sourcepath to point directly to one of the src directories. See if that works.</p>\n" }, { "answer_id": 10424368, "author": "Uma", "author_id": 1371421, "author_profile": "https://Stackoverflow.com/users/1371421", "pm_score": 1, "selected": false, "text": "<p>I ran into the same issue. But found that while setting the sourcepath we need to set to the only directory level not to the java file location. it is similar to the classpath</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using the EMMA tool for code coverage yet despite my best efforts, EMMA is refusing to see the original .java files and generate coverage on a line-by-line basis. We are using ANT to build the code and debug is set to true. I know that EMMA is measuring coverage as the .emma files seem to be generating and merging correctly. The reports are able to present high level method coverage with percentages. But why won't it see the .java files? All I get is: [source file 'a/b/c/d/e/f/code.java' not found in sourcepath]
Are you setting the `sourcepath` in your `report` element? ``` <report> <sourcepath> <pathelement path="${java.src.dir}" /> </sourcepath> <fileset dir="data"> <include name="*.emma" /> </fileset> <txt outfile="coverage.txt" /> <html outfile="coverage.html" /> </report> ```
254,009
<p>This probably has a simple answer, but I must not have had enough coffee to figure it out on my own:</p> <p>If I had a comma delimited string such as:</p> <pre><code>string list = "Fred,Sam,Mike,Sarah"; </code></pre> <p>How would get each element and add quotes around it and stick it back in a string like this:</p> <pre><code>string newList = "'Fred','Sam','Mike','Sarah'"; </code></pre> <p>I'm assuming iterating over each one would be a start, but I got stumped after that.</p> <p>One solution that is ugly:</p> <pre><code>int number = 0; string newList = ""; foreach (string item in list.Split(new char[] {','})) { if (number &gt; 0) { newList = newList + "," + "'" + item + "'"; } else { newList = "'" + item + "'"; } number++; } </code></pre>
[ { "answer_id": 254012, "author": "FOR", "author_id": 27826, "author_profile": "https://Stackoverflow.com/users/27826", "pm_score": 8, "selected": true, "text": "<pre><code>string s = \"A,B,C\";\nstring replaced = \"'\"+s.Replace(\",\", \"','\")+\"'\";\n</code></pre>\n\n<p>Thanks for the comments, I had missed the external quotes.</p>\n\n<p>Of course.. if the source was an empty string, would you want the extra quotes around it or not ? And what if the input was a bunch of whitespaces... ? I mean, to give a 100% complete solution I'd probably ask for a list of unit tests but I hope my gut instinct answered your core question.</p>\n\n<p><em>Update</em>: A LINQ-based alternative has also been suggested (with the added benefit of using String.Format and therefore not having to worry about leading/trailing quotes):</p>\n\n<pre><code>string list = \"Fred,Sam,Mike,Sarah\";\nstring newList = string.Join(\",\", list.Split(',').Select(x =&gt; string.Format(\"'{0}'\", x)).ToList());\n</code></pre>\n" }, { "answer_id": 254024, "author": "Tor Haugen", "author_id": 32050, "author_profile": "https://Stackoverflow.com/users/32050", "pm_score": 4, "selected": false, "text": "<pre><code>string[] splitList = list.Split(',');\nstring newList = \"'\" + string.Join(\"','\", splitList) + \"'\";\n</code></pre>\n" }, { "answer_id": 254025, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<pre><code>string[] bits = list.Split(','); // Param arrays are your friend\nfor (int i=0; i &lt; bits.Length; i++)\n{\n bits[i] = \"'\" + bits[i] + \"'\";\n}\nreturn string.Join(\",\", bits);\n</code></pre>\n\n<p>Or you could use LINQ, particularly with a version of String.Join which supports <code>IEnumerable&lt;string&gt;</code>...</p>\n\n<pre><code>return list.Split(',').Select(x =&gt; \"'\" + x + \"'\").JoinStrings(\",\");\n</code></pre>\n\n<p>There's an implementation of JoinStrings elsewhere on SO... I'll have a look for it.</p>\n\n<p>EDIT: Well, there isn't quite the JoinStrings I was thinking of, so here it is:</p>\n\n<pre><code>public static string JoinStrings&lt;T&gt;(this IEnumerable&lt;T&gt; source, \n string separator)\n{\n StringBuilder builder = new StringBuilder();\n bool first = true;\n foreach (T element in source)\n {\n if (first)\n {\n first = false;\n }\n else\n {\n builder.Append(separator);\n }\n builder.Append(element);\n }\n return builder.ToString();\n}\n</code></pre>\n\n<p>These days <code>string.Join</code> has a generic overload instead though, so you could just use:</p>\n\n<pre><code>return string.Join(\",\", list.Split(',').Select(x =&gt; $\"'{x}'\"));\n</code></pre>\n" }, { "answer_id": 254026, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>I can't write C# code, but this simple JavaScript code is probably easy to adapt:</p>\n\n<pre><code>var s = \"Fred,Sam,Mike,Sarah\";\nalert(s.replace(/\\b/g, \"'\"));\n</code></pre>\n\n<p>It just replace bounds (start/end of string, transition from word chars non punctuation) by single quote.</p>\n" }, { "answer_id": 254028, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 2, "selected": false, "text": "<p>I think the simplest thing would be to <a href=\"http://msdn.microsoft.com/en-us/library/b873y76a.aspx\" rel=\"nofollow noreferrer\"><code>Split</code></a> and then <a href=\"http://msdn.microsoft.com/en-us/library/57a79xd0.aspx\" rel=\"nofollow noreferrer\"><code>Join</code></a>.</p>\n\n<pre><code>string nameList = \"Fred,Sam,Mike,Sarah\";\nstring[] names = nameList.Split(',');\nstring quotedNames = \"'\" + string.Join(\"','\", names) + \"'\";\n</code></pre>\n" }, { "answer_id": 254029, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 1, "selected": false, "text": "<pre><code>string list = \"Fred,Sam,Mike,Sarah\";\n\nstring[] splitList = list.Split(',');\n\nfor (int i = 0; i &lt; splitList.Length; i++)\n splitList[i] = String.Format(\"'{0}'\", splitList[i]);\n\nstring newList = String.Join(\",\", splitList);\n</code></pre>\n" }, { "answer_id": 254077, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 0, "selected": false, "text": "<p>The C# implementation of @<a href=\"https://stackoverflow.com/questions/254009/in-c-add-quotes-around-string-in-a-comma-delimited-list-of-strings#254026\">PhiLho</a>'s JavaScript regular expression solution looks something like the following:</p>\n\n<pre><code>Regex regex = new Regex(\n @\"\\b\",\n RegexOptions.ECMAScript\n | RegexOptions.Compiled\n );\n\nstring list = \"Fred,Sam,Mike,Sarah\";\nstring newList = regex.Replace(list,\"'\");\n</code></pre>\n" }, { "answer_id": 254163, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 0, "selected": false, "text": "<p>My \"less sophisticated\" approach ...\nI suppose it's always good practice to use a StringBuilder because the list can be very large.</p>\n\n<pre><code>string list = \"Fred,Sam,Mike,Sarah\";\nStringBuilder sb = new StringBuilder();\n\nstring[] listArray = list.Split(new char[] { ',' });\n\nfor (int i = 0; i &lt; listArray.Length; i++)\n{\n sb.Append(\"'\").Append(listArray[i]).Append(\"'\");\n if (i != (listArray.Length - 1))\n sb.Append(\",\");\n}\nstring newList = sb.ToString();\nConsole.WriteLine(newList);\n</code></pre>\n" }, { "answer_id": 254527, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 0, "selected": false, "text": "<p>Are you going to be processing a lot of CSV? If so, you should also consider using a library to do this. Don't reinvent the wheel. Unfortunately I haven't found a library quite as simple as Python's CSV library, but I have seen <a href=\"http://www.filehelpers.com/\" rel=\"nofollow noreferrer\">FileHelpers</a> (free) <a href=\"http://msdn.microsoft.com/en-us/magazine/cc721607.aspx\" rel=\"nofollow noreferrer\">reviewed at MSDN Magazine</a> and it looks pretty good. There are probably other free libraries out there as well. It all depends on how much processing you will be doing though. Often it grows and grows until you realize you would be better off using a library.</p>\n" }, { "answer_id": 9705435, "author": "vcuankit", "author_id": 159272, "author_profile": "https://Stackoverflow.com/users/159272", "pm_score": 5, "selected": false, "text": "<p>Following Jon Skeet's example above, this is what worked for me. I already had a <code>List&lt;String&gt;</code> variable called __messages so this is what I did:</p>\n\n<pre><code>string sep = String.Join(\", \", __messages.Select(x =&gt; \"'\" + x + \"'\"));\n</code></pre>\n" }, { "answer_id": 16050294, "author": "Atish Narlawar", "author_id": 944663, "author_profile": "https://Stackoverflow.com/users/944663", "pm_score": 1, "selected": false, "text": "<p>If you are using JSON, following function would help</p>\n\n<pre><code>var string[] keys = list.Split(',');\nconsole.log(JSON.stringify(keys));\n</code></pre>\n" }, { "answer_id": 28570650, "author": "MikeTeeVee", "author_id": 555798, "author_profile": "https://Stackoverflow.com/users/555798", "pm_score": 1, "selected": false, "text": "<p>My Requirements:</p>\n\n<ol>\n<li>Separate items using commas.</li>\n<li>Wrap all items in list in double-quotes.</li>\n<li>Escape existing double-quotes in the string.</li>\n<li>Handle null-strings to avoid errors.</li>\n<li>Do not bother wrapping null-strings in double-quotes.</li>\n<li><p>Terminate with carriage-return and line-feed.</p>\n\n<p>string.Join(\",\", lCol.Select(s => s == null ? null : (\"\\\"\" + s.Replace(\"\\\"\", \"\\\"\\\"\") + \"\\\"\"))) + \"\\r\\n\";</p></li>\n</ol>\n" }, { "answer_id": 34294571, "author": "KenB", "author_id": 4879380, "author_profile": "https://Stackoverflow.com/users/4879380", "pm_score": 0, "selected": false, "text": "<p>Here is a C# 6 solution using String Interpolation. </p>\n\n<pre><code>string newList = string.Join(\",\", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(x =&gt; $\"'{x}'\")\n .ToList());\n</code></pre>\n\n<p>Or, if you prefer the C# 5 option with String.Format:</p>\n\n<pre><code>string newList = string.Join(\",\", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(x =&gt; String.Format(\"'{0}'\", x))\n .ToList());\n</code></pre>\n\n<p>Using the StringSplitOptions will remove any empty values so you won't have any empty quotes, if that's something you're trying to avoid.</p>\n" }, { "answer_id": 37827369, "author": "Thivan Mydeen", "author_id": 5626575, "author_profile": "https://Stackoverflow.com/users/5626575", "pm_score": 0, "selected": false, "text": "<p>I have found a new solution for this problem</p>\n\n<p>I bind a list by selected items values from the grid using linq, after that added a comma delimited string for each string collections by using String.Join() properties.</p>\n\n<pre><code>String str1 = String.Empty;\nString str2 = String.Empty; \n//str1 = String.Join(\",\", values); if you use this method,result \"X,Y,Z\"\n str1 =String.Join(\"'\" + \",\" + \"'\", values);\n//The result of str1 is \"X','Y','Z\"\n str2 = str1.Insert(0, \"'\").Insert(str1.Length+1, \"'\");\n//The result of str2 is 'X','Y','Z'\n</code></pre>\n\n<p>I hope this will helpful !!!!!!</p>\n" }, { "answer_id": 39274564, "author": "Dheeraj Palagiri", "author_id": 2263758, "author_profile": "https://Stackoverflow.com/users/2263758", "pm_score": 0, "selected": false, "text": "<p>For people who love extension methods like me, here it is:</p>\n\n<pre><code> public static string MethodA(this string[] array, string seperatedCharecter = \"|\")\n {\n return array.Any() ? string.Join(seperatedCharecter, array) : string.Empty;\n }\n\n public static string MethodB(this string[] array, string seperatedChar = \"|\")\n {\n return array.Any() ? MethodA(array.Select(x =&gt; $\"'{x}'\").ToArray(), seperatedChar) : string.Empty;\n }\n</code></pre>\n" }, { "answer_id": 59863000, "author": "dylanh724", "author_id": 6541639, "author_profile": "https://Stackoverflow.com/users/6541639", "pm_score": 3, "selected": false, "text": "<p>Based off Jon Skeet's example, but modernized for .NET 4+:</p>\n\n<pre><code>// [ \"foo\", \"bar\" ] =&gt; \"\\\"foo\\\"\", \"\\\"bar\\\"\" \nstring.Join(\", \", strList.Select(x =&gt; $\"\\\"{x}\\\"\"));\n</code></pre>\n" }, { "answer_id": 74477036, "author": "Charitha Basnayake", "author_id": 636148, "author_profile": "https://Stackoverflow.com/users/636148", "pm_score": 0, "selected": false, "text": "<p>When I work with some database queries, there are some occasions that we need to create part of the string query like this.</p>\n<p>So this is my one line approach for this using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-7.0\" rel=\"nofollow noreferrer\">Split</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-7.0\" rel=\"nofollow noreferrer\">Join</a>.</p>\n<pre><code>String newList = &quot;'&quot; + String.Join(&quot;','&quot;, list.Split(',')) + &quot;'&quot;;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ]
This probably has a simple answer, but I must not have had enough coffee to figure it out on my own: If I had a comma delimited string such as: ``` string list = "Fred,Sam,Mike,Sarah"; ``` How would get each element and add quotes around it and stick it back in a string like this: ``` string newList = "'Fred','Sam','Mike','Sarah'"; ``` I'm assuming iterating over each one would be a start, but I got stumped after that. One solution that is ugly: ``` int number = 0; string newList = ""; foreach (string item in list.Split(new char[] {','})) { if (number > 0) { newList = newList + "," + "'" + item + "'"; } else { newList = "'" + item + "'"; } number++; } ```
``` string s = "A,B,C"; string replaced = "'"+s.Replace(",", "','")+"'"; ``` Thanks for the comments, I had missed the external quotes. Of course.. if the source was an empty string, would you want the extra quotes around it or not ? And what if the input was a bunch of whitespaces... ? I mean, to give a 100% complete solution I'd probably ask for a list of unit tests but I hope my gut instinct answered your core question. *Update*: A LINQ-based alternative has also been suggested (with the added benefit of using String.Format and therefore not having to worry about leading/trailing quotes): ``` string list = "Fred,Sam,Mike,Sarah"; string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList()); ```
254,060
<p>I am using the WMD markdown editor in a project for a large number of fields that correspond to a large number of properties in a large number of Entity classes. Some classes may have multiple properties that require the markdown.</p> <p>I am storing the markdown itself since this makes it easier to edit the fields later. However, I need to convert the properties to HTML for display later on. The question is: is there some pattern that I can use to avoid writing markdown conversion code in all my entity classes?</p> <p>I created a utility class with a method that accepts a markdown string and returns the HTML. I am using markdownj and this works fine.</p> <p>The problem is for each property of each class that stores markdown I may need another method that converts to HTML:</p> <pre><code>public class Course{ private String description; . . . public String getDescription(){ return description; } public String getDescriptionAsHTML(){ return MarkdownUtil.convert(getDescription()); } . . . } </code></pre> <p>The problem there is that if the Course class has 2 more properties Tuition and Prerequisites say, that both need converters then I will have to write getTuitionAsHTML() and getPrerequisiteAsHTML().</p> <p>I find that a bit ugly and would like a cleaner solution. The classes that require this are not part of a single inheritance hierarchy. </p> <p>The other option I am considering is doing this in the controller rather than the model. What are your thoughts on this? </p> <p>Thanks.</p> <p>[EDIT]: New thoughts (Thanks Jasper). Since the project uses struts2 (I did not say this before) I could create a view component say that will convert the markdown for me. Then I use that wherever I need to display the value as HTML.</p>
[ { "answer_id": 254114, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>The classes that require this are not part of a single inheritance hierarchy.</p>\n</blockquote>\n\n<p>They should at least implement a common interface, otherwise coming up with a clean generic solution is going to be cumbersome.</p>\n\n<blockquote>\n <p>The other option I am considering is doing this in the controller rather than the model. What are your thoughts on this?</p>\n</blockquote>\n\n<p>This clearly is a responsibility of the View. The #1 MVC rule is that the Model doesn't care about its representation, the markdown in this case.</p>\n\n<p>However, I feel that there is to little detail about your current architecture to give a meaningful answer to your question.</p>\n" }, { "answer_id": 254140, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 1, "selected": false, "text": "<p>You do have one option for doing this if you can't use inheritance or an interface. I know, I know refactor but this is reality and *hit happens.</p>\n\n<p>You can use reflection to iterate over your properties and apply the formatting to them. You could either tag them with an attribute or you could adopt a naming scheme (brittle, but still an option).</p>\n" }, { "answer_id": 254148, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 1, "selected": false, "text": "<p>Ignoring the architectural problems, I think the simple answer could be:</p>\n\n<pre><code>public String getDescription(MarkDownUtil converter)\n{\n if (converter == null) return description;\n else return MarkdownUtil.convert(description);\n}\n</code></pre>\n\n<p>Even better would be to make MarkDownUtil implement IStringConverter, and you could have \nseveral different StringConverters for different jobs.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27439/" ]
I am using the WMD markdown editor in a project for a large number of fields that correspond to a large number of properties in a large number of Entity classes. Some classes may have multiple properties that require the markdown. I am storing the markdown itself since this makes it easier to edit the fields later. However, I need to convert the properties to HTML for display later on. The question is: is there some pattern that I can use to avoid writing markdown conversion code in all my entity classes? I created a utility class with a method that accepts a markdown string and returns the HTML. I am using markdownj and this works fine. The problem is for each property of each class that stores markdown I may need another method that converts to HTML: ``` public class Course{ private String description; . . . public String getDescription(){ return description; } public String getDescriptionAsHTML(){ return MarkdownUtil.convert(getDescription()); } . . . } ``` The problem there is that if the Course class has 2 more properties Tuition and Prerequisites say, that both need converters then I will have to write getTuitionAsHTML() and getPrerequisiteAsHTML(). I find that a bit ugly and would like a cleaner solution. The classes that require this are not part of a single inheritance hierarchy. The other option I am considering is doing this in the controller rather than the model. What are your thoughts on this? Thanks. [EDIT]: New thoughts (Thanks Jasper). Since the project uses struts2 (I did not say this before) I could create a view component say that will convert the markdown for me. Then I use that wherever I need to display the value as HTML.
> > The classes that require this are not part of a single inheritance hierarchy. > > > They should at least implement a common interface, otherwise coming up with a clean generic solution is going to be cumbersome. > > The other option I am considering is doing this in the controller rather than the model. What are your thoughts on this? > > > This clearly is a responsibility of the View. The #1 MVC rule is that the Model doesn't care about its representation, the markdown in this case. However, I feel that there is to little detail about your current architecture to give a meaningful answer to your question.
254,066
<p>On Windows XP, the following command in a script will prevent any power saving options from being enabled on the PC (monitor sleep, HD sleep, etc.). This is useful for kiosk applications.</p> <pre><code>powercfg.exe /setactive presentation </code></pre> <p>What is the equivalent on Vista?</p>
[ { "answer_id": 254112, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 0, "selected": false, "text": "<p>In Vista you create a power profile and use the commandline powercfg to select that profile <a href=\"http://www.nooblet.org/blog/tag/powercfg/\" rel=\"nofollow noreferrer\">see here</a></p>\n" }, { "answer_id": 254117, "author": "user15071", "author_id": 15071, "author_profile": "https://Stackoverflow.com/users/15071", "pm_score": 1, "selected": false, "text": "<p>C:\\Windows\\system32>powercfg /list</p>\n\n<h2>Existing Power Schemes (* Active)</h2>\n\n<p>Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced) *</p>\n\n<p>Power Scheme GUID: 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c (High performance)</p>\n\n<p>Power Scheme GUID: a1841308-3541-4fab-bc81-f71556f20b4a (Power saver)</p>\n\n<p>C:\\Windows\\system32>powercfg /setactive a1841308-3541-4fab-bc81-f71556f20b4a</p>\n" }, { "answer_id": 254131, "author": "jeremyasnyder", "author_id": 33143, "author_profile": "https://Stackoverflow.com/users/33143", "pm_score": 3, "selected": true, "text": "<p>powercfg.exe works a little differently in Vista, and the \"presentation\" profile isn't included by default (at least on my machine. so you can setup a \"presentation\" profile and then use the following to get the GUID</p>\n\n<blockquote>\n<pre><code>powercfg.exe -list\n</code></pre>\n</blockquote>\n\n<p>and the following to set it to that GUID:</p>\n\n<blockquote>\n<pre><code>powercfg.exe -setactive GUID\n</code></pre>\n</blockquote>\n\n<p>Alternatively, you can use powercfg.exe with the -change or -X to change specific parameters on the current power scheme.</p>\n\n<p>Snippet from \"powercfg.exe /?\":</p>\n\n<blockquote>\n <p>-CHANGE, -X Modifies a setting value in the current power scheme.</p>\n\n<pre><code> Usage: POWERCFG -X &lt;SETTING&gt; &lt;VALUE&gt;\n\n &lt;SETTING&gt; Specifies one of the following options:\n -monitor-timeout-ac &lt;minutes&gt;\n -monitor-timeout-dc &lt;minutes&gt;\n -disk-timeout-ac &lt;minutes&gt;\n -disk-timeout-dc &lt;minutes&gt;\n -standby-timeout-ac &lt;minutes&gt;\n -standby-timeout-dc &lt;minutes&gt;\n -hibernate-timeout-ac &lt;minutes&gt;\n -hibernate-timeout-dc &lt;minutes&gt;\n\n Example:\n POWERCFG -Change -monitor-timeout-ac 5\n\n This would set the monitor idle timeout value to 5 minutes\n when on AC power.\n</code></pre>\n</blockquote>\n" }, { "answer_id": 258777, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 3, "selected": false, "text": "<p>Setting a value to never can be done by passing a value of <code>0</code> to the <code>-change</code> option, i.e.:</p>\n\n<pre><code>powercfg.exe -change -monitor-timeout-ac 0\n</code></pre>\n\n<p>means the monitor timeout will be set to \"Never\". So the presentation plan can be achieved via:</p>\n\n<pre><code>powercfg.exe -change -monitor-timeout-ac 0\npowercfg.exe -change -disk-timeout-ac 0\npowercfg.exe -change -standby-timeout-ac 0\npowercfg.exe -change -hibernate-timeout-ac 0\n</code></pre>\n" }, { "answer_id": 24095715, "author": "kai klein", "author_id": 3717476, "author_profile": "https://Stackoverflow.com/users/3717476", "pm_score": 2, "selected": false, "text": "<p>(at least) for windows 7:</p>\n\n<p>Nice Shortcuts are:</p>\n\n<ul>\n<li>powercfg -ALIASES # Lists named aliases for available profiles.</li>\n<li>powercfg -S SCHEME_MIN #Activates the (High-Performance) Scheme with the alias SCHEME_MIN</li>\n<li>powercfg -S SCHEME_MAX #Activates the (Max-Energie-Saving) Scheme with the alias SCHEME_MAX</li>\n<li>powercfg -S SCHEME_BALANCED # ... Balanced Energie Scheme</li>\n</ul>\n\n<p>cheers</p>\n\n<p>Kai</p>\n" }, { "answer_id": 40845554, "author": "Binu AN", "author_id": 7220425, "author_profile": "https://Stackoverflow.com/users/7220425", "pm_score": 0, "selected": false, "text": "<pre><code>@ECHO OFF\n\npowercfg -change -monitor-timeout-ac 0\npowercfg -change -standby-timeout-ac 0\npowercfg -change -disk-timeout-ac 0\npowercfg -change -hibernate-timeout-ac 0\n</code></pre>\n\n<p>This will work</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
On Windows XP, the following command in a script will prevent any power saving options from being enabled on the PC (monitor sleep, HD sleep, etc.). This is useful for kiosk applications. ``` powercfg.exe /setactive presentation ``` What is the equivalent on Vista?
powercfg.exe works a little differently in Vista, and the "presentation" profile isn't included by default (at least on my machine. so you can setup a "presentation" profile and then use the following to get the GUID > > > ``` > powercfg.exe -list > > ``` > > and the following to set it to that GUID: > > > ``` > powercfg.exe -setactive GUID > > ``` > > Alternatively, you can use powercfg.exe with the -change or -X to change specific parameters on the current power scheme. Snippet from "powercfg.exe /?": > > -CHANGE, -X Modifies a setting value in the current power scheme. > > > > ``` > Usage: POWERCFG -X <SETTING> <VALUE> > > <SETTING> Specifies one of the following options: > -monitor-timeout-ac <minutes> > -monitor-timeout-dc <minutes> > -disk-timeout-ac <minutes> > -disk-timeout-dc <minutes> > -standby-timeout-ac <minutes> > -standby-timeout-dc <minutes> > -hibernate-timeout-ac <minutes> > -hibernate-timeout-dc <minutes> > > Example: > POWERCFG -Change -monitor-timeout-ac 5 > > This would set the monitor idle timeout value to 5 minutes > when on AC power. > > ``` > >
254,071
<p>I tried to use <code>OPTION (MAXRECURSION 0)</code> in a view to generate a list of dates. This seems to be unsupported. Is there a workaround for this issue?</p> <p>EDIT to Explain what I actually want to do:</p> <p>I have 2 tables.</p> <p>table1: int weekday, bool available</p> <p>table2: datetime date, bool available</p> <p>I want the result: view1: date (here all days in this year), available(from table2 or from table1 when not in table2).</p> <p>That means I have to apply a join on a date with a weekday. I hope this explanation is understandable, because I actually use more tables with more fields in the query.</p> <p>I found this code to generate the recursion:</p> <pre><code>WITH Dates AS ( SELECT cast('2008-01-01' as datetime) Date UNION ALL SELECT Date + 1 FROM Dates WHERE Date + 1 &lt; DATEADD(yy, 1, GETDATE()) ) </code></pre>
[ { "answer_id": 254174, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 0, "selected": false, "text": "<p>You can use a <a href=\"http://blog.crowe.co.nz/archive/2007/09/06/Microsoft-SQL-Server-2005---CTE-Example-of-a-simple.aspx\" rel=\"nofollow noreferrer\">CTE</a> for hierarchical queries.</p>\n" }, { "answer_id": 254424, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124653\" rel=\"nofollow noreferrer\">No</a> - if you can find a way to do it within 100 levels of recusion (have a table of numbers), which will get you to within 100 recursion levels, you'll be able to do it. But if you have a numbers or pivot table, you won't need the recursion anyway...</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/10819/sql-auxiliary-table-of-numbers\">this question</a> (but I would create a table and not a table-valued function), <a href=\"https://stackoverflow.com/questions/40456/sql-missing-rows-when-grouped-by-day-month-year\">this question</a> and <a href=\"http://andre-silva-cardoso.blogspot.com/2007/11/sql-trickspatterns-1-numbers-table.html\" rel=\"nofollow noreferrer\">this link</a> and <a href=\"http://www.sqlmag.com/Article/ArticleID/94376/sql_server_94376.html\" rel=\"nofollow noreferrer\">this link</a></p>\n" }, { "answer_id": 13417526, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 0, "selected": false, "text": "<p>Here you go:</p>\n\n<pre><code>;WITH CTE_Stack(IsPartOfRecursion, Depth, MyDate) AS\n(\n SELECT \n 0 AS IsPartOfRecursion\n ,0 AS Dept \n ,DATEADD(DAY, -1, CAST('01.01.2012' as datetime)) AS MyDate \n UNION ALL\n\n SELECT \n 1 AS IsPartOfRecursion \n ,Parent.Depth + 1 AS Depth \n --,DATEADD(DAY, 1, Parent.MyDate) AS MyDate\n ,DATEADD(DAY, 1, Parent.MyDate) AS MyDate\n FROM \n (\n SELECT 0 AS Nothing \n ) AS TranquillizeSyntaxCheckBecauseWeDontHaveAtable \n\n INNER JOIN CTE_Stack AS Parent \n --ON Parent.Depth &lt; 2005 \n ON DATEADD(DAY, 1, Parent.MyDate) &lt; DATEADD(YEAR, 1, CAST('01.01.2012' as datetime)) \n)\n\nSELECT * FROM CTE_Stack \nWHERE IsPartOfRecursion = 1\nOPTION (MAXRECURSION 367) -- Accounting for leap-years\n;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376/" ]
I tried to use `OPTION (MAXRECURSION 0)` in a view to generate a list of dates. This seems to be unsupported. Is there a workaround for this issue? EDIT to Explain what I actually want to do: I have 2 tables. table1: int weekday, bool available table2: datetime date, bool available I want the result: view1: date (here all days in this year), available(from table2 or from table1 when not in table2). That means I have to apply a join on a date with a weekday. I hope this explanation is understandable, because I actually use more tables with more fields in the query. I found this code to generate the recursion: ``` WITH Dates AS ( SELECT cast('2008-01-01' as datetime) Date UNION ALL SELECT Date + 1 FROM Dates WHERE Date + 1 < DATEADD(yy, 1, GETDATE()) ) ```
[No](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124653) - if you can find a way to do it within 100 levels of recusion (have a table of numbers), which will get you to within 100 recursion levels, you'll be able to do it. But if you have a numbers or pivot table, you won't need the recursion anyway... See [this question](https://stackoverflow.com/questions/10819/sql-auxiliary-table-of-numbers) (but I would create a table and not a table-valued function), [this question](https://stackoverflow.com/questions/40456/sql-missing-rows-when-grouped-by-day-month-year) and [this link](http://andre-silva-cardoso.blogspot.com/2007/11/sql-trickspatterns-1-numbers-table.html) and [this link](http://www.sqlmag.com/Article/ArticleID/94376/sql_server_94376.html)
254,076
<p>This is the error Dependency Walker gives me on an executable that I am building with VC++ 2005 Express Edition. When trying to run the .exe, I get:</p> <pre><code>This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. </code></pre> <p>(I am new to the manifest/SxS/etc. way of doing things post VC++ 2003.)</p> <p>EDIT: I am running on the same machine I am building the .exe with. In Event Viewer, I have the unhelpful:</p> <pre><code>Faulting application blah.exe, version 0.0.0.0, faulting module blah.exe, version 0.0.0.0, fault address 0x004239b0. </code></pre>
[ { "answer_id": 254106, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 2, "selected": false, "text": "<p>Run Event Viewer: it'll have more information.</p>\n\n<p>Probably you've attempted to run your program on a machine that doesn't have the VC redistributables installed, or you're attempting to run a debug build on a machine that doesn't have Visual Studio installed (the debug libraries aren't redistributable).</p>\n" }, { "answer_id": 255934, "author": "Cameron", "author_id": 21475, "author_profile": "https://Stackoverflow.com/users/21475", "pm_score": 3, "selected": false, "text": "<p>I've had this problem. The solution has two steps:<br>\n1. Compile your program in \"Release\" mode instead of \"Debug\" mode (there's usually a combo-box in the toolbar)<br>\n2. Download from Microsoft their <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=32bc1bee-a3f9-4c13-9c99-220b62a191ee&amp;displaylang=en\" rel=\"noreferrer\">Redistributable Package</a> of runtime components. Make sure to download the x86 edition for 32-bit computers and the x64 edition for 64-bit computers/OSes. Install this package on the target computer, and your application should run fine</p>\n\n<p>P.S. This <em>is</em> a SxS thing<br>\nP.P.S. Alternatively, use a different compiler (like GCC, for example with Dev-Cpp) to compile your program's source, and your headaches will disappear.</p>\n" }, { "answer_id": 416859, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 5, "selected": true, "text": "<p>Open the properties sheet for your project, go to the Configuration Properties -> C/C++ -> Code Generation page, and change the Runtime Library selection to /MT or /MTd so that your project does not use the DLL runtime libraries.</p>\n\n<p>The C/C++ DLL runtimes used by VS2003 and up are not automatically distributed with the latest version of the OS and are a real pain to install and get working without this kind of problem. statically link the c-runtime and just avoid the total mess that is manifests and version specific runtime dlls.</p>\n" }, { "answer_id": 1093162, "author": "Ian Kemp", "author_id": 70345, "author_profile": "https://Stackoverflow.com/users/70345", "pm_score": 3, "selected": false, "text": "<p>Sorry to bump an old question, but I was able to get around this exact issue and thought I'd post a solution in case someone else needs it...</p>\n\n<p>Even after installing Microsoft's redistributable DLLs I was getting this error, the fix was to copy the</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 8\\VC\\redist\\x86\\Microsoft.VC80.CRT\n</code></pre>\n\n<p>folder into the application's directory on the target PC. After that, no more problems.</p>\n\n<p>BTW, the DLL that was giving me issues was a 3rd-party DLL that had never had problems before on over 100 other computers... go figure.</p>\n" }, { "answer_id": 3077841, "author": "Sundar", "author_id": 102423, "author_profile": "https://Stackoverflow.com/users/102423", "pm_score": 2, "selected": false, "text": "<p>I have had the same issue with VS 2008-built debug binaries on other winxp sp3 machines. </p>\n\n<ol>\n<li>I first tried installing the client machine with vc redist package,as it seemed sensible. Annoyingly, it <strong>didn't work</strong>.</li>\n<li>I tried copying all the dependent dlls to the application's directory - still <strong>didn't work</strong></li>\n<li>After being struck over this issue for hours, I found that the latest VS builds require manifests and policies to link with the dlls. After copying them into their respective \"C:\\WINDOWS\\WinSxS\\\" folders, I got it <strong>working</strong>.</li>\n</ol>\n\n<p>The problem was caused due to the fact that the vc redist package did not install debug versions of dlls, they somehow thought its up to the programmer to figure out.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2666/" ]
This is the error Dependency Walker gives me on an executable that I am building with VC++ 2005 Express Edition. When trying to run the .exe, I get: ``` This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. ``` (I am new to the manifest/SxS/etc. way of doing things post VC++ 2003.) EDIT: I am running on the same machine I am building the .exe with. In Event Viewer, I have the unhelpful: ``` Faulting application blah.exe, version 0.0.0.0, faulting module blah.exe, version 0.0.0.0, fault address 0x004239b0. ```
Open the properties sheet for your project, go to the Configuration Properties -> C/C++ -> Code Generation page, and change the Runtime Library selection to /MT or /MTd so that your project does not use the DLL runtime libraries. The C/C++ DLL runtimes used by VS2003 and up are not automatically distributed with the latest version of the OS and are a real pain to install and get working without this kind of problem. statically link the c-runtime and just avoid the total mess that is manifests and version specific runtime dlls.
254,080
<p>I am using the SoundEngine sample code from Apple in the CrashLanding sample to play back multiple audio files. Using the sample caf files included with CrashLanding everything works fine but when I try and use my own samplesconverted to CAF using afconvert all I get is a stony silence ;)</p> <p>Does anyone have settings for afconvert that will produce a CAF file capable of being played back through OpenAL?</p>
[ { "answer_id": 255151, "author": "Dave Verwer", "author_id": 4496, "author_profile": "https://Stackoverflow.com/users/4496", "pm_score": 9, "selected": true, "text": "<pre><code>afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf\n</code></pre>\n\n<p>References:</p>\n\n<ul>\n<li>Apple's <a href=\"https://developer.apple.com/library/ios/documentation/audiovideo/conceptual/multimediapg/usingaudio/usingaudio.html#//apple_ref/doc/uid/TP40009767-CH2-SW28\" rel=\"noreferrer\">Multimedia Programming Guide: Using Audio: Preferred Audio Formats in iOS</a></li>\n<li><a href=\"https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man1/afconvert.1.html\" rel=\"noreferrer\">afconvert(1) man page</a> (use <code>afconvert -h</code> for complete info)</li>\n</ul>\n" }, { "answer_id": 294257, "author": "Steph Thirion", "author_id": 36182, "author_profile": "https://Stackoverflow.com/users/36182", "pm_score": 2, "selected": false, "text": "<p>thanks for the info.</p>\n\n<p>also, if you're looking into additional compression with openAL, this might be of interest:</p>\n\n<p>\"iPhone, OpenAL, and IMA4/ADPCM\"\n<a href=\"http://www.wooji-juice.com/blog/iphone-openal-ima4-adpcm.html\" rel=\"nofollow noreferrer\">http://www.wooji-juice.com/blog/iphone-openal-ima4-adpcm.html</a></p>\n" }, { "answer_id": 2413799, "author": "tomwilson", "author_id": 290115, "author_profile": "https://Stackoverflow.com/users/290115", "pm_score": 6, "selected": false, "text": "<p>Simple bash script to convert the mp3 files in a folder to caf for iphone</p>\n\n<pre><code>#!/bin/bash\nfor f in *.mp3; do\n echo \"Processing $f file...\"\n afconvert -f caff -d LEI16@44100 -c 1 \"$f\" \"${f/mp3/caf}\"\ndone\n</code></pre>\n" }, { "answer_id": 10392106, "author": "scurioni", "author_id": 1108587, "author_profile": "https://Stackoverflow.com/users/1108587", "pm_score": 4, "selected": false, "text": "<p>this is the best for size:</p>\n\n<blockquote>\n <p>afconvert -f caff -d ima4 original.wav</p>\n</blockquote>\n" }, { "answer_id": 15102464, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It looks like the -c is not working today, I got it with following:</p>\n\n<blockquote>\n <p>afconvert -f caff -d LEI16 input.m4a output.caf</p>\n</blockquote>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4496/" ]
I am using the SoundEngine sample code from Apple in the CrashLanding sample to play back multiple audio files. Using the sample caf files included with CrashLanding everything works fine but when I try and use my own samplesconverted to CAF using afconvert all I get is a stony silence ;) Does anyone have settings for afconvert that will produce a CAF file capable of being played back through OpenAL?
``` afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf ``` References: * Apple's [Multimedia Programming Guide: Using Audio: Preferred Audio Formats in iOS](https://developer.apple.com/library/ios/documentation/audiovideo/conceptual/multimediapg/usingaudio/usingaudio.html#//apple_ref/doc/uid/TP40009767-CH2-SW28) * [afconvert(1) man page](https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man1/afconvert.1.html) (use `afconvert -h` for complete info)
254,099
<p>I'm trying to write some LINQ To SQL code that would generate SQL like</p> <pre><code>SELECT t.Name, g.Name FROM Theme t INNER JOIN ( SELECT TOP 5 * FROM [Group] ORDER BY TotalMembers ) as g ON t.K = g.ThemeK </code></pre> <p>So far I have</p> <pre><code>var q = from t in dc.Themes join g in dc.Groups on t.K equals g.ThemeK into groups select new { t.Name, Groups = (from z in groups orderby z.TotalMembers select z.Name ) }; </code></pre> <p>but I need to do a top/take on the ordered groups subquery. According to <a href="http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx</a> in VB I could just add TAKE 5 on the end, but I can't get this syntax to work in c#. How do you use the take syntax in c#?</p> <p>edit: PS adding .Take(5) at the end causes it to run loads of individual queries</p> <p>edit 2: I made a slight mistake with the intent of the SQL above, but the question still stands. <b>The problem is that if you use extension methods in the query like .Take(5), LinqToSql runs lots of SQL queries instead of a single query.</b></p>
[ { "answer_id": 254105, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Just bracket your query expression and call Take on it:</p>\n\n<pre><code>var q = from t in dc.Themes \njoin g in dc.Groups on t.K equals g.ThemeK into groups \nselect new { t.Name, Groups = \n (from z in groups orderby z.TotalMembers select z.Name).Take(5) };\n</code></pre>\n\n<p>In fact, the query expression isn't really making things any simpler for you - you might as well call OrderBy directly:</p>\n\n<pre><code>var q = from t in dc.Themes \njoin g in dc.Groups on t.K equals g.ThemeK into groups \nselect new { t.Name, Groups = groups.OrderBy(z =&gt; z.TotalMembers).Take(5) };\n</code></pre>\n" }, { "answer_id": 254128, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Second answer, now I've reread the original question.</p>\n\n<p>Are you sure the SQL you've shown is actually correct? It won't give the top 5 groups within each theme - it'll match each theme just against the top 5 groups <em>overall</em>.</p>\n\n<p>In short, I suspect you'll get your original SQL if you use:</p>\n\n<pre><code>var q = from t in dc.Themes \njoin g in dc.Groups.OrderBy(z =&gt; z.TotalMembers).Take(5)\n on t.K equals g.ThemeK into groups \nselect new { t.Name, Groups = groups };\n</code></pre>\n\n<p>But I don't think that's what you actually want...</p>\n" }, { "answer_id": 254455, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": "<p>Here's a faithful translation of the original query. This should not generate repeated roundtrips.</p>\n\n<pre><code>var subquery =\n dc.Groups\n .OrderBy(g =&gt; g.TotalMembers)\n .Take(5);\n\nvar query =\n dc.Themes\n .Join(subquery, t =&gt; t.K, g =&gt; g.ThemeK, (t, g) =&gt; new\n {\n ThemeName = t.Name, GroupName = g.Name\n }\n );\n</code></pre>\n\n<p>The roundtrips in the question are caused by the groupjoin (join into). Groups in LINQ have a heirarchical shape. Groups in SQL have a row/column shape (grouped keys + aggregates). In order for LinqToSql to fill its hierarchy from row/column results, it must query the child nodes seperately using the group's keys. It only does this if the children are used outside of an aggregate.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086/" ]
I'm trying to write some LINQ To SQL code that would generate SQL like ``` SELECT t.Name, g.Name FROM Theme t INNER JOIN ( SELECT TOP 5 * FROM [Group] ORDER BY TotalMembers ) as g ON t.K = g.ThemeK ``` So far I have ``` var q = from t in dc.Themes join g in dc.Groups on t.K equals g.ThemeK into groups select new { t.Name, Groups = (from z in groups orderby z.TotalMembers select z.Name ) }; ``` but I need to do a top/take on the ordered groups subquery. According to <http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx> in VB I could just add TAKE 5 on the end, but I can't get this syntax to work in c#. How do you use the take syntax in c#? edit: PS adding .Take(5) at the end causes it to run loads of individual queries edit 2: I made a slight mistake with the intent of the SQL above, but the question still stands. **The problem is that if you use extension methods in the query like .Take(5), LinqToSql runs lots of SQL queries instead of a single query.**
Here's a faithful translation of the original query. This should not generate repeated roundtrips. ``` var subquery = dc.Groups .OrderBy(g => g.TotalMembers) .Take(5); var query = dc.Themes .Join(subquery, t => t.K, g => g.ThemeK, (t, g) => new { ThemeName = t.Name, GroupName = g.Name } ); ``` The roundtrips in the question are caused by the groupjoin (join into). Groups in LINQ have a heirarchical shape. Groups in SQL have a row/column shape (grouped keys + aggregates). In order for LinqToSql to fill its hierarchy from row/column results, it must query the child nodes seperately using the group's keys. It only does this if the children are used outside of an aggregate.
254,111
<p>I have a flash app in my page, and when a user interacts with the flash app, the browser/html/javascript stops receiving keyboard input. </p> <p>For example, in Firefox control-t no longer opens a new tab.</p> <p>However, if I click on part of the page that isn't flash, the browser starts receiving these events again.</p> <p>Is there anyway to programatically (either through flash or javascript) to return focus to the browser?</p> <p>After the user clicks a button in flash, I have the flash executing a javascript callback, so I've tried giving focus to a form field (and to the body) through javascript, but that approach doesn't seem to be working.</p> <p>A perhaps more concrete example is Youtube. They also have this problem. When I click the play/pause button, or adjust the volume, I would expect my browser keyboard controls to still work, but they don't, I have to click somewhere on the page outside the movie area. This is the exact problem I'm trying to solve.</p>
[ { "answer_id": 254130, "author": "user32141", "author_id": 32141, "author_profile": "https://Stackoverflow.com/users/32141", "pm_score": 2, "selected": false, "text": "<p>I think Adobe needs to drop the focus when the mouse goes out of its client area, or provide an option to do so. </p>\n\n<p>However I think most Flash developers (and especially those who make games) rely on the fact that keyboard input is caught by the flash application regardless of where the mouse is.</p>\n" }, { "answer_id": 254180, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>You can return the focus to the browser by doing a geturl can calling javascript on the HTML page:</p>\n\n<pre><code>document.body.focus()\n</code></pre>\n\n<p>How you do this in your Flash movie will depend on how the user interaction with the movie works. You could keep doing it on a timer, or when a control loses focus, or when the mouse moves. It depends.</p>\n" }, { "answer_id": 254440, "author": "discorax", "author_id": 30408, "author_profile": "https://Stackoverflow.com/users/30408", "pm_score": 3, "selected": false, "text": "<p>You can use the ExternalInterface class within Flash to call JavaScript. For example you could set up a function on an interval (Event.ENTER_FRAME for example) to call the JavaScript function that @Diodeus mentioned:</p>\n\n<pre><code>document.body.focus();\n</code></pre>\n\n<p>Or, an even better solution would be to add an event listener to the flash root (stage) to listen for when the mouse leaves Flash. You can set up this event to move focus to the document.body.</p>\n\n<p>AS3</p>\n\n<pre><code>package {\n import flash.display.*;\n import flash.events.*;\n import flash.external.ExternalInterface;\n\n public class TestMouseLeave extends Sprite\n {\n public function TestMouseLeave()\n {\n // Add event listener for when the mouse LEAVES FLASH\n addEventListener(MouseEvent.MOUSE_OUT, onMouseLeave);\n }\n\n private function onMouseLeave(ev:Event):void\n {\n var jslink = new ExternalInterface();\n jslink.call(\"changeFocus\");\n }\n }\n\n}\n</code></pre>\n\n<p>Javascript on your page:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" language=\"javascript\"&gt;\n function changeFocus(){\n document.body.focus();\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>Let me know if you want an AS2 example, and I'll post it up.</p>\n\n<p><em>Wanted to make a note about this solution: Once you push focus back to the browser, you will require that the user click on the Flash plug-in again to activate user input inside the flash plug-in. This could be a jarring user experience, and is something to consider when using this solution.</em> </p>\n" }, { "answer_id": 657143, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code> &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\" creationComplete=\"init();\"&gt;\n &lt;mx:Script&gt;\n &lt;![CDATA[\n private function init():void {\n i.setFocus();\n this.addEventListener(KeyboardEvent.KEY_UP,keyPressed);\n }\n\n private function keyPressed(event:KeyboardEvent):void {\n if(event.keyCode.toString()==\"84\" &amp;&amp; event.ctrlKey==true)\n ExternalInterface.call('newtab');\n }\n\n ]]&gt;\n &lt;/mx:Script&gt;\n &lt;mx:TextInput x=\"23\" y=\"268\" width=\"256\" id=\"i\" text=\"Text Box\"/&gt;\n&lt;/mx:Application&gt;\n\n&lt;script type=\"text/javascript\"&gt;\nfunction newtab(e){\n document.body.focus();\n window.open('about:blank');\n}\n&lt;/script&gt; \n</code></pre>\n\n<p>Now, what happens with other keyboards? is 84 standard for T? I like the focus idea, but in full browser apps there is not as much room to lose the focus. \nThe user could change the key combo as well, I don't think these is much of a complete fix for this one without flash polling the command config from the browser and then listening for the combo as we are basically doing here. I dunno.</p>\n\n<p>This also just attempts to open a new window after giving focus, there is no sense to me in making the user press it twice unless they block the window like a popup. But focus is called first so, if that happens the second attempt should work. You could alert the user in a browser app if needed.</p>\n" }, { "answer_id": 4565102, "author": "Chris Anthony", "author_id": 552555, "author_profile": "https://Stackoverflow.com/users/552555", "pm_score": 2, "selected": false, "text": "<p>In Firefox, <code>document.body.focus();</code> doesn't work. Using the same idea as Cláudio Silva's solution to this <a href=\"https://stackoverflow.com/questions/594821/object-focus-problem-with-safari-and-chrome-browsers\">Chrome issue</a>, the following JavaScript will work in Firefox:</p>\n\n<pre><code>document.body.tabIndex = 0;\ndocument.body.focus();\n</code></pre>\n" }, { "answer_id": 4821469, "author": "distill", "author_id": 589481, "author_profile": "https://Stackoverflow.com/users/589481", "pm_score": 0, "selected": false, "text": "<p>There's a solution below in case somebody needs it. For me, that works quite nicely. I can click around my Flash but still use all the browser keyboard functionality (the focus is shifted to the html part when clicked inside the Flash).</p>\n\n<p><a href=\"http://forums.adobe.com/message/3431403#3431403\" rel=\"nofollow\">http://forums.adobe.com/message/3431403#3431403</a></p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32951/" ]
I have a flash app in my page, and when a user interacts with the flash app, the browser/html/javascript stops receiving keyboard input. For example, in Firefox control-t no longer opens a new tab. However, if I click on part of the page that isn't flash, the browser starts receiving these events again. Is there anyway to programatically (either through flash or javascript) to return focus to the browser? After the user clicks a button in flash, I have the flash executing a javascript callback, so I've tried giving focus to a form field (and to the body) through javascript, but that approach doesn't seem to be working. A perhaps more concrete example is Youtube. They also have this problem. When I click the play/pause button, or adjust the volume, I would expect my browser keyboard controls to still work, but they don't, I have to click somewhere on the page outside the movie area. This is the exact problem I'm trying to solve.
You can use the ExternalInterface class within Flash to call JavaScript. For example you could set up a function on an interval (Event.ENTER\_FRAME for example) to call the JavaScript function that @Diodeus mentioned: ``` document.body.focus(); ``` Or, an even better solution would be to add an event listener to the flash root (stage) to listen for when the mouse leaves Flash. You can set up this event to move focus to the document.body. AS3 ``` package { import flash.display.*; import flash.events.*; import flash.external.ExternalInterface; public class TestMouseLeave extends Sprite { public function TestMouseLeave() { // Add event listener for when the mouse LEAVES FLASH addEventListener(MouseEvent.MOUSE_OUT, onMouseLeave); } private function onMouseLeave(ev:Event):void { var jslink = new ExternalInterface(); jslink.call("changeFocus"); } } } ``` Javascript on your page: ``` <script type="text/javascript" language="javascript"> function changeFocus(){ document.body.focus(); } </script> ``` Let me know if you want an AS2 example, and I'll post it up. *Wanted to make a note about this solution: Once you push focus back to the browser, you will require that the user click on the Flash plug-in again to activate user input inside the flash plug-in. This could be a jarring user experience, and is something to consider when using this solution.*
254,121
<p>I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned:</p> <pre><code>{"authentication":"required"} </code></pre> <p>The JavaScript function which submits all AJAX requests handles this response by showing a popup message and redirecting the user back to the login page.</p> <p>However, when a non-AJAX request receives this response the JSON is simply shown in the browser because the response is processed directly by the browser (i.e. the aforementioned JavaScript function is bypassed). Obviously this is not ideal and I would like the non-AJAX requests that receive this response to behave the same as the AJAX requests. In order to achieve this, I can think of 2 options:</p> <ol> <li><p>Go through the application and convert all the requests to AJAX requests. This would work, but could also take a long time!</p></li> <li><p>The JSON shown above is generated by a very simple JSP. I'm wondering if it might be possible to add a JavaScript event handler to this JSP which is run just before the content is displayed in the browser - I'm assuming this would never be called for AJAX requests? This handler could call the other JavaScript code that displays the popup and performs the redirection.</p></li> </ol> <p>If anyone knows how exactly I can implement the handler I've outlined in (2), or has any other potential solutions, I'd be very grateful if they'd pass them on.</p> <p>Cheers, Don</p>
[ { "answer_id": 254142, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>3) Change your AJAX code to add a variable to the GET or POST: <code>outputJson=1</code></p>\n" }, { "answer_id": 254145, "author": "Rontologist", "author_id": 13925, "author_profile": "https://Stackoverflow.com/users/13925", "pm_score": 2, "selected": true, "text": "<p>You cannot add a handler to the JSP that way. Anything you add to it will make it a non-JSON producing page.</p>\n\n<p>There are two options that I can see:\nAdd a parameter to the page by appending a URL parameter to the screen that modifies the output.</p>\n\n<p>URL: <a href=\"http://domain/page.jsp?ajaxRequest=true\" rel=\"nofollow noreferrer\">http://domain/page.jsp?ajaxRequest=true</a>\nwould output json only</p>\n\n<p>URL: <a href=\"http://domain/page.jsp\" rel=\"nofollow noreferrer\">http://domain/page.jsp</a>\nwould display a jsp page that could forward to another page.</p>\n\n<p>OR</p>\n\n<p>change the response to have the forwarding code in the JSP that will get executed by the web browser if it is hit directly. Then have your calling AJAX to strip the forwarding code out, and then process what is left.</p>\n" }, { "answer_id": 254157, "author": "AlexJReid", "author_id": 32320, "author_profile": "https://Stackoverflow.com/users/32320", "pm_score": 0, "selected": false, "text": "<p>4) Read up on the 'Accept' request HTTP header.</p>\n\n<p>Then, on the server side tailor the output:</p>\n\n<p>e.g.</p>\n\n<pre><code>if(Accept contains application/json...) { // client asking for json, likely to be XHR\n return {\"foo\":\"bar\"}\n} else { // other\n return \"Location: /login-please\";\n}\n</code></pre>\n" }, { "answer_id": 306411, "author": "Kent Brewster", "author_id": 1151280, "author_profile": "https://Stackoverflow.com/users/1151280", "pm_score": 0, "selected": false, "text": "<p>Start with a smarter error message, like this:</p>\n\n<pre><code>{\"error\":\"authentication required\"}\n</code></pre>\n\n<p>Wrap the JSON output in a callback:</p>\n\n<pre><code>errorHandler({\"error\":\"authentication required\"});\n</code></pre>\n\n<p>Have a handler waiting in your script:</p>\n\n<pre><code>function errorHandler(r) {\n alert(r.error);\n}\n</code></pre>\n\n<p>And don't forget to send it down as <code>text/javascript</code> and not <code>application/x-json</code>.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned: ``` {"authentication":"required"} ``` The JavaScript function which submits all AJAX requests handles this response by showing a popup message and redirecting the user back to the login page. However, when a non-AJAX request receives this response the JSON is simply shown in the browser because the response is processed directly by the browser (i.e. the aforementioned JavaScript function is bypassed). Obviously this is not ideal and I would like the non-AJAX requests that receive this response to behave the same as the AJAX requests. In order to achieve this, I can think of 2 options: 1. Go through the application and convert all the requests to AJAX requests. This would work, but could also take a long time! 2. The JSON shown above is generated by a very simple JSP. I'm wondering if it might be possible to add a JavaScript event handler to this JSP which is run just before the content is displayed in the browser - I'm assuming this would never be called for AJAX requests? This handler could call the other JavaScript code that displays the popup and performs the redirection. If anyone knows how exactly I can implement the handler I've outlined in (2), or has any other potential solutions, I'd be very grateful if they'd pass them on. Cheers, Don
You cannot add a handler to the JSP that way. Anything you add to it will make it a non-JSON producing page. There are two options that I can see: Add a parameter to the page by appending a URL parameter to the screen that modifies the output. URL: <http://domain/page.jsp?ajaxRequest=true> would output json only URL: <http://domain/page.jsp> would display a jsp page that could forward to another page. OR change the response to have the forwarding code in the JSP that will get executed by the web browser if it is hit directly. Then have your calling AJAX to strip the forwarding code out, and then process what is left.
254,125
<p>I'm writing a mapping app that uses a Canvas for positioning elements. For each element I have to programatically convert element's Lat/Long to the canvas' coordinate, then set the Canvas.Top and Canvas.Left properties.</p> <p>If I had a 360x180 Canvas, can I convert the coordinates on the canvas to go from -180 to 180 rather than 0 to 360 on the X axis and 90 to -90 rather than 0 to 180 on the Y axis?</p> <p>Scaling requirements:</p> <ul> <li>The canvas can be any size, so should still work if it's 360x180 or 5000x100.</li> <li>The Lat/Long area may not always be (-90,-180)x(90,180), it could be anything (ie (5,-175)x(89,-174)).</li> <li>Elements such as PathGeometry which are point base, rather than Canvas.Top/Left based need to work.</li> </ul>
[ { "answer_id": 254155, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure you can't do that exactly, but it would be pretty trivial to have a method which translated from lat/long to Canvas coordinates.</p>\n\n<pre><code>Point ToCanvas(double lat, double lon) {\n double x = ((lon * myCanvas.ActualWidth) / 360.0) - 180.0;\n double y = ((lat * myCanvas.ActualHeight) / 180.0) - 90.0;\n return new Point(x,y);\n}\n</code></pre>\n\n<p>(Or something along those lines)</p>\n" }, { "answer_id": 254186, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 0, "selected": false, "text": "<p>I guess another option would be to extend canvas and override the measure / arrange to make it behave the way you want.</p>\n" }, { "answer_id": 254729, "author": "Dylan", "author_id": 4580, "author_profile": "https://Stackoverflow.com/users/4580", "pm_score": 1, "selected": false, "text": "<p>I was able to get it to by creating my own custom canvas and overriding the ArrangeOverride function like so:</p>\n\n<pre><code> public class CustomCanvas : Canvas\n {\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n foreach (UIElement child in InternalChildren)\n {\n double left = Canvas.GetLeft(child);\n double top = Canvas.GetTop(child);\n Point canvasPoint = ToCanvas(top, left);\n child.Arrange(new Rect(canvasPoint, child.DesiredSize));\n }\n return arrangeSize;\n }\n Point ToCanvas(double lat, double lon)\n {\n double x = this.Width / 360;\n x *= (lon - -180);\n double y = this.Height / 180;\n y *= -(lat + -90);\n return new Point(x, y);\n }\n }\n</code></pre>\n\n<p>Which works for my described problem, but it probably would not work for another need I have, which is a PathGeometry. It wouldn't work because the points are not defined as Top and Left, but as actual points.</p>\n" }, { "answer_id": 254757, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 3, "selected": false, "text": "<p>Here's an all-XAML solution. Well, mostly XAML, because you have to have the IValueConverter in code. So: Create a new WPF project and add a class to it. The class is MultiplyConverter:</p>\n\n<pre><code>namespace YourProject\n{\n public class MultiplyConverter : System.Windows.Data.IValueConverter\n {\n public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n return AsDouble(value)* AsDouble(parameter);\n }\n double AsDouble(object value)\n {\n var valueText = value as string;\n if (valueText != null)\n return double.Parse(valueText);\n else\n return (double)value;\n }\n\n public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new System.NotSupportedException();\n }\n }\n}\n</code></pre>\n\n<p>Then use this XAML for your Window. Now you should see the results right in your XAML preview window.</p>\n\n<p><strong>EDIT</strong>: You can fix the Background problem by putting your Canvas inside another Canvas. Kind of weird, but it works. In addition, I've added a ScaleTransform which flips the Y-axis so that positive Y is up and negative is down. Note carefully which Names go where:</p>\n\n<pre><code>&lt;Canvas Name=\"canvas\" Background=\"Moccasin\"&gt;\n &lt;Canvas Name=\"innerCanvas\"&gt;\n &lt;Canvas.RenderTransform&gt;\n &lt;TransformGroup&gt;\n &lt;TranslateTransform x:Name=\"translate\"&gt;\n &lt;TranslateTransform.X&gt;\n &lt;Binding ElementName=\"canvas\" Path=\"ActualWidth\"\n Converter=\"{StaticResource multiplyConverter}\" ConverterParameter=\"0.5\" /&gt;\n &lt;/TranslateTransform.X&gt;\n &lt;TranslateTransform.Y&gt;\n &lt;Binding ElementName=\"canvas\" Path=\"ActualHeight\"\n Converter=\"{StaticResource multiplyConverter}\" ConverterParameter=\"0.5\" /&gt;\n &lt;/TranslateTransform.Y&gt;\n &lt;/TranslateTransform&gt;\n &lt;ScaleTransform ScaleX=\"1\" ScaleY=\"-1\" CenterX=\"{Binding ElementName=translate,Path=X}\"\n CenterY=\"{Binding ElementName=translate,Path=Y}\" /&gt;\n &lt;/TransformGroup&gt;\n &lt;/Canvas.RenderTransform&gt;\n &lt;Rectangle Canvas.Top=\"-50\" Canvas.Left=\"-50\" Height=\"100\" Width=\"200\" Fill=\"Blue\" /&gt;\n &lt;Rectangle Canvas.Top=\"0\" Canvas.Left=\"0\" Height=\"200\" Width=\"100\" Fill=\"Green\" /&gt;\n &lt;Rectangle Canvas.Top=\"-25\" Canvas.Left=\"-25\" Height=\"50\" Width=\"50\" Fill=\"HotPink\" /&gt;\n &lt;/Canvas&gt;\n&lt;/Canvas&gt;\n</code></pre>\n\n<p>As for your new requirements that you need varying ranges, a more complex ValueConverter would probably do the trick.</p>\n" }, { "answer_id": 256718, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 0, "selected": false, "text": "<p>You can use transform to translate between the coordinate systems, maybe a TransformGroup with a TranslateTranform to move (0,0) to the center of the canvas and a ScaleTransform to get the coordinates to the right range.</p>\n\n<p>With data binding and maybe a value converter or two you can get the transforms to update automatically based on the canvas size.</p>\n\n<p>The advantage of this is that it will work for any element (including a PathGeometry), a possible disadvantage is that it will scale everything and not just points - so it will change the size of icons and text on the map.</p>\n" }, { "answer_id": 3070365, "author": "FTLPhysicsGuy", "author_id": 226888, "author_profile": "https://Stackoverflow.com/users/226888", "pm_score": 0, "selected": false, "text": "<p>Another possible solution:</p>\n\n<p>Embed a custom canvas (the draw-to canvas) in another canvas (the background canvas) and set the draw-to canvas so that it is transparent and does not clip to bounds. Transform the draw-to canvas with a matrix that makes y flip (M22 = -1) and translates/scales the canvas inside the parent canvas to view the extend of the world you're looking at.</p>\n\n<p>In effect, if you draw at -115, 42 in the draw-to canvas, the item you are drawing is \"off\" the canvas, but shows up anyway because the canvas is not clipping to bounds. You then transform the draw-to canvas so that the point shows up in the right spot on the background canvas.</p>\n\n<p>This is something I'll be trying myself soon. Hope it helps.</p>\n" }, { "answer_id": 13547289, "author": "dharmatech", "author_id": 268581, "author_profile": "https://Stackoverflow.com/users/268581", "pm_score": 0, "selected": false, "text": "<p>Here's <a href=\"https://stackoverflow.com/questions/13079610/equivalent-of-glortho-in-wpf/13093518#13093518\">an answer</a> which describes a <code>Canvas</code> extension method that allows you to apply a Cartesian coordinate system. I.e.:</p>\n\n<pre><code>canvas.SetCoordinateSystem(-10, 10, -10, 10)\n</code></pre>\n\n<p>will set the coordinate system of <code>canvas</code> so that <code>x</code> goes from -10 to 10 and <code>y</code> goes from -10 to 10.</p>\n" }, { "answer_id": 41152256, "author": "Morten Brask Jensen", "author_id": 7222150, "author_profile": "https://Stackoverflow.com/users/7222150", "pm_score": 0, "selected": false, "text": "<p>i have nearly the same problem. so i went online. and this guy uses matrix to transform from 'device pixel' to what he calls 'world coordinates' and by that he means real world numbers instead of 'device pixels' see the link</p>\n\n<p><a href=\"http://csharphelper.com/blog/2014/09/use-transformations-draw-graph-wpf-c/\" rel=\"nofollow noreferrer\">http://csharphelper.com/blog/2014/09/use-transformations-draw-graph-wpf-c/</a></p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4580/" ]
I'm writing a mapping app that uses a Canvas for positioning elements. For each element I have to programatically convert element's Lat/Long to the canvas' coordinate, then set the Canvas.Top and Canvas.Left properties. If I had a 360x180 Canvas, can I convert the coordinates on the canvas to go from -180 to 180 rather than 0 to 360 on the X axis and 90 to -90 rather than 0 to 180 on the Y axis? Scaling requirements: * The canvas can be any size, so should still work if it's 360x180 or 5000x100. * The Lat/Long area may not always be (-90,-180)x(90,180), it could be anything (ie (5,-175)x(89,-174)). * Elements such as PathGeometry which are point base, rather than Canvas.Top/Left based need to work.
Here's an all-XAML solution. Well, mostly XAML, because you have to have the IValueConverter in code. So: Create a new WPF project and add a class to it. The class is MultiplyConverter: ``` namespace YourProject { public class MultiplyConverter : System.Windows.Data.IValueConverter { public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { return AsDouble(value)* AsDouble(parameter); } double AsDouble(object value) { var valueText = value as string; if (valueText != null) return double.Parse(valueText); else return (double)value; } public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new System.NotSupportedException(); } } } ``` Then use this XAML for your Window. Now you should see the results right in your XAML preview window. **EDIT**: You can fix the Background problem by putting your Canvas inside another Canvas. Kind of weird, but it works. In addition, I've added a ScaleTransform which flips the Y-axis so that positive Y is up and negative is down. Note carefully which Names go where: ``` <Canvas Name="canvas" Background="Moccasin"> <Canvas Name="innerCanvas"> <Canvas.RenderTransform> <TransformGroup> <TranslateTransform x:Name="translate"> <TranslateTransform.X> <Binding ElementName="canvas" Path="ActualWidth" Converter="{StaticResource multiplyConverter}" ConverterParameter="0.5" /> </TranslateTransform.X> <TranslateTransform.Y> <Binding ElementName="canvas" Path="ActualHeight" Converter="{StaticResource multiplyConverter}" ConverterParameter="0.5" /> </TranslateTransform.Y> </TranslateTransform> <ScaleTransform ScaleX="1" ScaleY="-1" CenterX="{Binding ElementName=translate,Path=X}" CenterY="{Binding ElementName=translate,Path=Y}" /> </TransformGroup> </Canvas.RenderTransform> <Rectangle Canvas.Top="-50" Canvas.Left="-50" Height="100" Width="200" Fill="Blue" /> <Rectangle Canvas.Top="0" Canvas.Left="0" Height="200" Width="100" Fill="Green" /> <Rectangle Canvas.Top="-25" Canvas.Left="-25" Height="50" Width="50" Fill="HotPink" /> </Canvas> </Canvas> ``` As for your new requirements that you need varying ranges, a more complex ValueConverter would probably do the trick.
254,129
<p>How can I display a sort arrow in the header of the sorted column in a list view which follows the native look of the operating system?</p>
[ { "answer_id": 254139, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 7, "selected": true, "text": "<p>You can use the following extension method to set the sort arrow to a particular column:</p>\n\n<pre><code>[EditorBrowsable(EditorBrowsableState.Never)]\npublic static class ListViewExtensions\n{\n [StructLayout(LayoutKind.Sequential)]\n public struct HDITEM\n {\n public Mask mask;\n public int cxy;\n [MarshalAs(UnmanagedType.LPTStr)] public string pszText;\n public IntPtr hbm;\n public int cchTextMax;\n public Format fmt;\n public IntPtr lParam;\n // _WIN32_IE &gt;= 0x0300 \n public int iImage;\n public int iOrder;\n // _WIN32_IE &gt;= 0x0500\n public uint type;\n public IntPtr pvFilter;\n // _WIN32_WINNT &gt;= 0x0600\n public uint state;\n\n [Flags]\n public enum Mask\n {\n Format = 0x4, // HDI_FORMAT\n };\n\n [Flags]\n public enum Format\n {\n SortDown = 0x200, // HDF_SORTDOWN\n SortUp = 0x400, // HDF_SORTUP\n };\n };\n\n public const int LVM_FIRST = 0x1000;\n public const int LVM_GETHEADER = LVM_FIRST + 31;\n\n public const int HDM_FIRST = 0x1200;\n public const int HDM_GETITEM = HDM_FIRST + 11;\n public const int HDM_SETITEM = HDM_FIRST + 12;\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref HDITEM lParam);\n\n public static void SetSortIcon(this ListView listViewControl, int columnIndex, SortOrder order)\n {\n IntPtr columnHeader = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);\n for (int columnNumber = 0; columnNumber &lt;= listViewControl.Columns.Count - 1; columnNumber++)\n {\n var columnPtr = new IntPtr(columnNumber);\n var item = new HDITEM\n {\n mask = HDITEM.Mask.Format\n };\n\n if (SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero)\n {\n throw new Win32Exception();\n }\n\n if (order != SortOrder.None &amp;&amp; columnNumber == columnIndex)\n {\n switch (order)\n {\n case SortOrder.Ascending:\n item.fmt &amp;= ~HDITEM.Format.SortDown;\n item.fmt |= HDITEM.Format.SortUp;\n break;\n case SortOrder.Descending:\n item.fmt &amp;= ~HDITEM.Format.SortUp;\n item.fmt |= HDITEM.Format.SortDown;\n break;\n }\n }\n else\n {\n item.fmt &amp;= ~HDITEM.Format.SortDown &amp; ~HDITEM.Format.SortUp;\n }\n\n if (SendMessage(columnHeader, HDM_SETITEM, columnPtr, ref item) == IntPtr.Zero)\n {\n throw new Win32Exception();\n }\n }\n }\n}\n</code></pre>\n\n<p>Then, you can call the extension method like such:</p>\n\n<pre><code>myListView.SetSortIcon(0, SortOrder.Ascending);\n</code></pre>\n\n<p>It works by using P/Invoke to:</p>\n\n<ul>\n<li>Get the handle to the header control for a list view using the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb774937%28v=vs.85%29.aspx\" rel=\"noreferrer\">LVM_GETHEADER</a> message.</li>\n<li>Get the information about a header column using the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb775335%28v=vs.85%29.aspx\" rel=\"noreferrer\">HDM_GETITEM</a> message.</li>\n<li>It then modifies the <code>fmt</code> to set / clear the <code>HDF_SORTDOWN</code> and <code>HDF_SORTUP</code> flags on the returned <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb775247%28v=vs.85%29.aspx\" rel=\"noreferrer\">HDITEM</a> structure.</li>\n<li>Finally it re-sets the information usintg the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb775367%28v=vs.85%29.aspx\" rel=\"noreferrer\">HDM_SETITEM</a> message.</li>\n</ul>\n\n<p>This is what it looks like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/4deP5.png\" alt=\"Arrows on a list view column\"></p>\n" }, { "answer_id": 26974367, "author": "Jesse", "author_id": 2969067, "author_profile": "https://Stackoverflow.com/users/2969067", "pm_score": 3, "selected": false, "text": "<p>Great answer by Andrew. If Anyone is looking for the VB.net equivalent here it is:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Module ListViewExtensions\n Public Enum SortOrder\n None\n Ascending\n Descending\n End Enum\n\n &lt;StructLayout(LayoutKind.Sequential)&gt;\n Public Structure HDITEM\n Public theMask As Mask\n Public cxy As Integer\n &lt;MarshalAs(UnmanagedType.LPTStr)&gt;\n Public pszText As String\n Public hbm As IntPtr\n Public cchTextMax As Integer\n Public fmt As Format\n Public lParam As IntPtr\n ' _WIN32_IE &gt;= 0x0300 \n Public iImage As Integer\n Public iOrder As Integer\n ' _WIN32_IE &gt;= 0x0500\n Public type As UInteger\n Public pvFilter As IntPtr\n ' _WIN32_WINNT &gt;= 0x0600\n Public state As UInteger\n\n &lt;Flags()&gt;\n Public Enum Mask\n Format = &amp;H4 ' HDI_FORMAT\n End Enum\n\n\n &lt;Flags()&gt;\n Public Enum Format\n SortDown = &amp;H200 ' HDF_SORTDOWN\n SortUp = &amp;H400 ' HDF_SORTUP\n End Enum\n End Structure\n\n Public Const LVM_FIRST As Integer = &amp;H1000\n Public Const LVM_GETHEADER As Integer = LVM_FIRST + 31\n\n Public Const HDM_FIRST As Integer = &amp;H1200\n Public Const HDM_GETITEM As Integer = HDM_FIRST + 11\n Public Const HDM_SETITEM As Integer = HDM_FIRST + 12\n\n &lt;DllImport(\"user32.dll\", CharSet:=CharSet.Auto, SetLastError:=True)&gt;\n Public Function SendMessage(hWnd As IntPtr, msg As UInt32, wParam As IntPtr, lParam As IntPtr) As IntPtr\n End Function\n\n &lt;DllImport(\"user32.dll\", CharSet:=CharSet.Auto, SetLastError:=True)&gt;\n Public Function SendMessage(hWnd As IntPtr, msg As UInt32, wParam As IntPtr, ByRef lParam As HDITEM) As IntPtr\n End Function\n\n &lt;Extension()&gt;\n Public Sub SetSortIcon(listViewControl As ListView, columnIndex As Integer, order As SortOrder)\n Dim columnHeader As IntPtr = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero)\n For columnNumber As Integer = 0 To listViewControl.Columns.Count - 1\n\n Dim columnPtr As New IntPtr(columnNumber)\n Dim item As New HDITEM\n\n item.theMask = HDITEM.Mask.Format\n\n If SendMessage(columnHeader, HDM_GETITEM, columnPtr, item) = IntPtr.Zero Then Throw New Win32Exception\n\n If order &lt;&gt; SortOrder.None AndAlso columnNumber = columnIndex Then\n Select Case order\n Case SortOrder.Ascending\n item.fmt = item.fmt And Not HDITEM.Format.SortDown\n item.fmt = item.fmt Or HDITEM.Format.SortUp\n Case SortOrder.Descending\n item.fmt = item.fmt And Not HDITEM.Format.SortUp\n item.fmt = item.fmt Or HDITEM.Format.SortDown\n End Select\n Else\n item.fmt = item.fmt And Not HDITEM.Format.SortDown And Not HDITEM.Format.SortUp\n End If\n\n If SendMessage(columnHeader, HDM_SETITEM, columnPtr, item) = IntPtr.Zero Then Throw New Win32Exception\n Next\n End Sub\nEnd Module\n</code></pre>\n" }, { "answer_id": 45310194, "author": "Mordachai", "author_id": 112755, "author_profile": "https://Stackoverflow.com/users/112755", "pm_score": 2, "selected": false, "text": "<p>For any other lazy C++ programmers (like me):</p>\n\n<pre><code>// possible sorting header icons / indicators\nenum class ListViewSortArrow { None, Ascending, Descending };\n\nBOOL LVHeader_SetSortArrow(HWND hHeader, int nColumn, ListViewSortArrow sortArrow)\n{\n ASSERT(hHeader);\n\n HDITEM hdrItem = { 0 };\n hdrItem.mask = HDI_FORMAT;\n if (Header_GetItem(hHeader, nColumn, &amp;hdrItem))\n {\n switch (sortArrow)\n {\n default:\n ASSERT(false);\n case ListViewSortArrow::None:\n hdrItem.fmt = hdrItem.fmt &amp; ~(HDF_SORTDOWN | HDF_SORTUP);\n break;\n case ListViewSortArrow::Ascending:\n hdrItem.fmt = (hdrItem.fmt &amp; ~HDF_SORTDOWN) | HDF_SORTUP;\n break;\n case ListViewSortArrow::Descending:\n hdrItem.fmt = (hdrItem.fmt &amp; ~HDF_SORTUP) | HDF_SORTDOWN;\n break;\n }\n\n return Header_SetItem(hHeader, nColumn, &amp;hdrItem);\n }\n\n return FALSE;\n}\n\nBOOL ListView_SetSortArrow(HWND hListView, int nColumn, ListViewSortArrow sortArrow)\n{\n ASSERT(hListView);\n\n if (HWND hHeader = ListView_GetHeader(hListView))\n return LVHeader_SetSortArrow(hHeader, nColumn, sortArrow);\n\n return FALSE;\n}\n</code></pre>\n" }, { "answer_id": 55549628, "author": "symbiont", "author_id": 2411916, "author_profile": "https://Stackoverflow.com/users/2411916", "pm_score": 2, "selected": false, "text": "<p>instead of messing with the Windows API, you can compromise and use characters that look like arrows (i picked them using charmap)</p>\n\n<pre><code>private void SetSortArrow(ColumnHeader head, SortOrder order)\n{\n const string ascArrow = \" ▲\";\n const string descArrow = \" ▼\";\n\n // remove arrow\n if(head.Text.EndsWith(ascArrow) || head.Text.EndsWith(descArrow))\n head.Text = head.Text.Substring(0, head.Text.Length-2);\n\n // add arrow\n switch (order)\n {\n case SortOrder.Ascending: head.Text += ascArrow; break;\n case SortOrder.Descending: head.Text += descArrow; break;\n }\n}\n\nSetSortArrow(listView1.Columns[0], SortOrder.None); // remove arrow from first column if present\nSetSortArrow(listView1.Columns[1], SortOrder.Ascending); // set second column arrow to ascending\nSetSortArrow(listView1.Columns[1], SortOrder.Descending); // set second column arrow to descending\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26210/" ]
How can I display a sort arrow in the header of the sorted column in a list view which follows the native look of the operating system?
You can use the following extension method to set the sort arrow to a particular column: ``` [EditorBrowsable(EditorBrowsableState.Never)] public static class ListViewExtensions { [StructLayout(LayoutKind.Sequential)] public struct HDITEM { public Mask mask; public int cxy; [MarshalAs(UnmanagedType.LPTStr)] public string pszText; public IntPtr hbm; public int cchTextMax; public Format fmt; public IntPtr lParam; // _WIN32_IE >= 0x0300 public int iImage; public int iOrder; // _WIN32_IE >= 0x0500 public uint type; public IntPtr pvFilter; // _WIN32_WINNT >= 0x0600 public uint state; [Flags] public enum Mask { Format = 0x4, // HDI_FORMAT }; [Flags] public enum Format { SortDown = 0x200, // HDF_SORTDOWN SortUp = 0x400, // HDF_SORTUP }; }; public const int LVM_FIRST = 0x1000; public const int LVM_GETHEADER = LVM_FIRST + 31; public const int HDM_FIRST = 0x1200; public const int HDM_GETITEM = HDM_FIRST + 11; public const int HDM_SETITEM = HDM_FIRST + 12; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref HDITEM lParam); public static void SetSortIcon(this ListView listViewControl, int columnIndex, SortOrder order) { IntPtr columnHeader = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero); for (int columnNumber = 0; columnNumber <= listViewControl.Columns.Count - 1; columnNumber++) { var columnPtr = new IntPtr(columnNumber); var item = new HDITEM { mask = HDITEM.Mask.Format }; if (SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero) { throw new Win32Exception(); } if (order != SortOrder.None && columnNumber == columnIndex) { switch (order) { case SortOrder.Ascending: item.fmt &= ~HDITEM.Format.SortDown; item.fmt |= HDITEM.Format.SortUp; break; case SortOrder.Descending: item.fmt &= ~HDITEM.Format.SortUp; item.fmt |= HDITEM.Format.SortDown; break; } } else { item.fmt &= ~HDITEM.Format.SortDown & ~HDITEM.Format.SortUp; } if (SendMessage(columnHeader, HDM_SETITEM, columnPtr, ref item) == IntPtr.Zero) { throw new Win32Exception(); } } } } ``` Then, you can call the extension method like such: ``` myListView.SetSortIcon(0, SortOrder.Ascending); ``` It works by using P/Invoke to: * Get the handle to the header control for a list view using the [LVM\_GETHEADER](http://msdn.microsoft.com/en-us/library/windows/desktop/bb774937%28v=vs.85%29.aspx) message. * Get the information about a header column using the [HDM\_GETITEM](http://msdn.microsoft.com/en-us/library/windows/desktop/bb775335%28v=vs.85%29.aspx) message. * It then modifies the `fmt` to set / clear the `HDF_SORTDOWN` and `HDF_SORTUP` flags on the returned [HDITEM](http://msdn.microsoft.com/en-us/library/windows/desktop/bb775247%28v=vs.85%29.aspx) structure. * Finally it re-sets the information usintg the [HDM\_SETITEM](http://msdn.microsoft.com/en-us/library/windows/desktop/bb775367%28v=vs.85%29.aspx) message. This is what it looks like: ![Arrows on a list view column](https://i.stack.imgur.com/4deP5.png)
254,132
<p>I am wondering what are the possible value for *_la_LDFLAGS in Makefile.am ? </p> <p>If I ask this question, it is because I would like the following :</p> <pre><code>Actual shared library : libA.so (or with the version number I don't care) Symbolic links : libA-X.Y.Z.so, libA-X.so, libA.so soname : libA-X.so </code></pre> <p>However here is what I get by using the <em>-release</em> flag :</p> <pre><code>Actual shared library : libA-X.Y.Z.so Symbolic links : libA.so soname : libA-X.Y.Z.so !!! this is not what I want </code></pre> <p>I also tried with no flags at all and got </p> <pre><code>Actual shared library : libA-0.0.0.so !!! 0.0.0 and not the real version Symbolic links : libA.so, libA-0.so soname : libA-0.so !!! 0.0.0 and not the real version </code></pre> <p>How should I do ? which flag should I use ? </p> <p>Thanks in advance</p>
[ { "answer_id": 255663, "author": "adl", "author_id": 27835, "author_profile": "https://Stackoverflow.com/users/27835", "pm_score": 3, "selected": true, "text": "<p>You should use the <code>-version-info</code> option of Libtool to specify the interface version of the library, but be sure to read \n<a href=\"http://sources.redhat.com/autobook/autobook/autobook_91.html\" rel=\"nofollow noreferrer\">how versioning works</a> (or <a href=\"http://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning\" rel=\"nofollow noreferrer\">here</a> for the official manual.)</p>\n\n<p>You can additionally play with <code>-release</code> to make the version number of your package more apparent, but I doubt you will ever get the exact naming you'd like. Libtool has its own set of rules to define how to name the file and what symlinks to create depending on the system: these should really be regarded as implementation details of how a shared library is installed.</p>\n" }, { "answer_id": 255683, "author": "Sherm Pendley", "author_id": 27631, "author_profile": "https://Stackoverflow.com/users/27631", "pm_score": 1, "selected": false, "text": "<p>IMHO, the layout you want is broken. Apps that are linked to your library will depend on libA-X.so because of the soname. But what happens when libA.so is version X+1? To what will the libA-X.so symlink point?</p>\n\n<p>The idea behind the layout you get with the -release flag is, when an app links with -lA, it will result in it being linked against the latest version. It will then, because of the soname, depend on libA-X.Y.Z.so at runtime. When you install a new version of the library, that will install a new libA-X.Y.Q.so, but it will leave the old one alone - exactly as old apps that depend on it expect. New apps will still, because of the libA symlink, link against the latest version.</p>\n\n<p>Years of thought by some very smart people have went into a versioning scheme that allows new apps to link against the latest version of a library, while allowing multiple versions to co-exist peacefully to satisfy dependencies for apps that need them. My advice is, don't second-guess all that.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20986/" ]
I am wondering what are the possible value for \*\_la\_LDFLAGS in Makefile.am ? If I ask this question, it is because I would like the following : ``` Actual shared library : libA.so (or with the version number I don't care) Symbolic links : libA-X.Y.Z.so, libA-X.so, libA.so soname : libA-X.so ``` However here is what I get by using the *-release* flag : ``` Actual shared library : libA-X.Y.Z.so Symbolic links : libA.so soname : libA-X.Y.Z.so !!! this is not what I want ``` I also tried with no flags at all and got ``` Actual shared library : libA-0.0.0.so !!! 0.0.0 and not the real version Symbolic links : libA.so, libA-0.so soname : libA-0.so !!! 0.0.0 and not the real version ``` How should I do ? which flag should I use ? Thanks in advance
You should use the `-version-info` option of Libtool to specify the interface version of the library, but be sure to read [how versioning works](http://sources.redhat.com/autobook/autobook/autobook_91.html) (or [here](http://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning) for the official manual.) You can additionally play with `-release` to make the version number of your package more apparent, but I doubt you will ever get the exact naming you'd like. Libtool has its own set of rules to define how to name the file and what symlinks to create depending on the system: these should really be regarded as implementation details of how a shared library is installed.
254,152
<p>I'm curious to know how NULLs are stored into a database ?</p> <p>It surely depends on the database server but I would like to have an general idea about it.</p> <hr> <p>First try:</p> <p>Suppose that the server put a undefined value (could be anything) into the field for a NULL value.</p> <p>Could you be very lucky and retrieve the NULL value with</p> <pre><code>...WHERE field = 'the undefined value (remember, could be anything...)' </code></pre> <hr> <p>Second try:</p> <p>Does the server have a flag or any meta-data somewhere to indicate this field is NULL ?</p> <p>Then the server must read this meta data to verify the field.</p> <p>If the meta-data indicates a NULL value and if the query doesn't have "field IS NULL", then the record is ignored.</p> <hr> <p>It seems too easy...</p>
[ { "answer_id": 254162, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>The server typically uses meta information rather than a magic value. So there's a bit off someplace that specifies whether the field is null.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 254165, "author": "Thomas Jones-Low", "author_id": 23030, "author_profile": "https://Stackoverflow.com/users/23030", "pm_score": 3, "selected": false, "text": "<p>MySql uses the second method. It stores an array of bits (one per column) with the data for each row to indicate which columns are null and then leaves the data for that field blank. I'm pretty sure this is true for all other databases as well. </p>\n\n<p>The problem with the first method is, are you sure that whatever value you select for your data won't show up as valid data? For some values (like dates, or floating point numbers) this is true. For others (like integers) this is false. </p>\n" }, { "answer_id": 254201, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 4, "selected": true, "text": "<p>On PostgreSQL, it uses an optional bitmap with one bit per column (0 is null, 1 is not null). If the bitmap is not present, all columns are not null.</p>\n\n<p>This is completely separate from the storage of the data itself, but is on the same page as the row (so both the row and the bitmap are read together).</p>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"http://www.postgresql.org/docs/8.3/interactive/storage-page-layout.html\" rel=\"noreferrer\">http://www.postgresql.org/docs/8.3/interactive/storage-page-layout.html</a></li>\n</ul>\n" }, { "answer_id": 255600, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>IBM Informix Dynamic Server uses special values to indicate nulls. For example, the valid range of values for a SMALLINT (16-bit, signed) is -32767..+32767. The other value, -32768, is reserved to indicate NULL. Similarly for INTEGER (4-byte, signed) and BIGINT (8-byte, signed). For other types, it uses other special representations (for example, all bits 1 for SQL FLOAT and SMALLFLOAT - aka C double and float, respectively). This means that it doesn't have to use extra space.</p>\n\n<p>IBM DB2 for Linux, Unix, Windows uses extra bytes to store the null indicators; AFAIK, it uses a separate byte for each nullable field, but I could be wrong on that detail.</p>\n\n<p>So, as was pointed out, the mechanisms differ depending on the DBMS.</p>\n" }, { "answer_id": 266692, "author": "Bjarke Ebert", "author_id": 31890, "author_profile": "https://Stackoverflow.com/users/31890", "pm_score": 1, "selected": false, "text": "<p>The problem with special values to indicate NULL is that sooner or later that special value will be inserted. For example, it will be inserted into a table specifying the special NULL indicators for different database servers</p>\n\n<pre><code>| DBServer | SpecialValue |\n+--------------+--------------+\n| 'Oracle' | 'Glyph' |\n| 'SQL Server' | 'Redmond' |\n</code></pre>\n\n<p>;-)</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14673/" ]
I'm curious to know how NULLs are stored into a database ? It surely depends on the database server but I would like to have an general idea about it. --- First try: Suppose that the server put a undefined value (could be anything) into the field for a NULL value. Could you be very lucky and retrieve the NULL value with ``` ...WHERE field = 'the undefined value (remember, could be anything...)' ``` --- Second try: Does the server have a flag or any meta-data somewhere to indicate this field is NULL ? Then the server must read this meta data to verify the field. If the meta-data indicates a NULL value and if the query doesn't have "field IS NULL", then the record is ignored. --- It seems too easy...
On PostgreSQL, it uses an optional bitmap with one bit per column (0 is null, 1 is not null). If the bitmap is not present, all columns are not null. This is completely separate from the storage of the data itself, but is on the same page as the row (so both the row and the bitmap are read together). References: * <http://www.postgresql.org/docs/8.3/interactive/storage-page-layout.html>
254,168
<p>I have two tables:</p> <p>Table 1: ID, PersonCode, Name, </p> <p>Table 2: ID, Table1ID, Location, ServiceDate</p> <p>I've got a query joining table 1 to table 2 on table1.ID = table2.Table1ID where PersonCode = 'XYZ'</p> <p>What I want to do is return Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate, I don't want all rows, In table 2 I'm only interested in the row with the most recent ServiceDate for each location. How would I go about doing this?</p>
[ { "answer_id": 254176, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 0, "selected": false, "text": "<p>Use MAX(ServiceDate)</p>\n" }, { "answer_id": 254185, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>select Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate\nfrom Table1\njoin Table2 on table1.ID = table2.Table1ID \nwhere table1.PersonCode = 'XYZ'\nand table2.ServiceDate = (select max(t2.ServiceDate)\n from table2 t2\n where t2.table1ID = table2.table1ID\n and t2.location = table2.location\n );\n</code></pre>\n" }, { "answer_id": 254187, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 3, "selected": true, "text": "<p>Something like this:</p>\n\n<pre><code>SELECT\n Table1.PersonCode, Table1.Name, Table2.Location, MAX(Table2.ServiceDate)\nFROM\n Table1 \n INNER JOIN Table2 on Table1.ID = Table2.Table1ID \nWHERE\n TABLE1.PersonCode = 'XYZ'\nGROUP BY\n Table1.PersonCode,Table1.Name, Table2.Location\n</code></pre>\n" }, { "answer_id": 254226, "author": "Julius A", "author_id": 13370, "author_profile": "https://Stackoverflow.com/users/13370", "pm_score": 0, "selected": false, "text": "<p>I would use an <code>INNER JOIN</code> and select the first record, having ordered the records in reverse chronological order based on Table2.ServiceDate.</p>\n\n<pre><code>SELECT TOP 1\n Table1.PersonCode, Table1.Name, Table2.Location, Table2.ServiceDate\nFROM\n Table1 \n INNER JOIN Table2 on Table1.ID = Table2.Table1ID \nWHERE\n TABLE1.PersonCode = 'XYZ'\nORDER BY Table2.ServiceDate DESC\nGROUP BY\n Table1.PersonCode,Table1.Name, Table2.Location\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
I have two tables: Table 1: ID, PersonCode, Name, Table 2: ID, Table1ID, Location, ServiceDate I've got a query joining table 1 to table 2 on table1.ID = table2.Table1ID where PersonCode = 'XYZ' What I want to do is return Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate, I don't want all rows, In table 2 I'm only interested in the row with the most recent ServiceDate for each location. How would I go about doing this?
Something like this: ``` SELECT Table1.PersonCode, Table1.Name, Table2.Location, MAX(Table2.ServiceDate) FROM Table1 INNER JOIN Table2 on Table1.ID = Table2.Table1ID WHERE TABLE1.PersonCode = 'XYZ' GROUP BY Table1.PersonCode,Table1.Name, Table2.Location ```
254,178
<p>Currently I'm using</p> <pre><code>var x = dict.ContainsKey(key) ? dict[key] : defaultValue </code></pre> <p>I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like</p> <pre><code>var x = dict[key] ?? defaultValue; </code></pre> <p>this also winds up being part of linq queries etc. so I'd prefer one-line solutions. </p>
[ { "answer_id": 254188, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 3, "selected": false, "text": "<p>You can use a helper method:</p>\n\n<pre><code>public abstract class MyHelper {\n public static V GetValueOrDefault&lt;K,V&gt;( Dictionary&lt;K,V&gt; dic, K key ) {\n V ret;\n bool found = dic.TryGetValue( key, out ret );\n if ( found ) { return ret; }\n return default(V);\n }\n}\n\nvar x = MyHelper.GetValueOrDefault( dic, key );\n</code></pre>\n" }, { "answer_id": 254221, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 5, "selected": true, "text": "<p>With an extension method:</p>\n\n<pre><code>public static class MyHelper\n{\n public static V GetValueOrDefault&lt;K, V&gt;(this IDictionary&lt;K, V&gt; dic, \n K key, \n V defaultVal = default(V))\n {\n V ret;\n bool found = dic.TryGetValue(key, out ret);\n if (found) { return ret; }\n return defaultVal;\n }\n void Example()\n {\n var dict = new Dictionary&lt;int, string&gt;();\n dict.GetValueOrDefault(42, \"default\");\n }\n}\n</code></pre>\n" }, { "answer_id": 10746505, "author": "Matt Connolly", "author_id": 365932, "author_profile": "https://Stackoverflow.com/users/365932", "pm_score": 0, "selected": false, "text": "<p>Isn't simply <code>TryGetValue(key, out value)</code> what you are looking for? Quoting MSDN:</p>\n\n<pre><code>When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.\n</code></pre>\n\n<p>from <a href=\"http://msdn.microsoft.com/en-us/library/bb347013(v=vs.90).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb347013(v=vs.90).aspx</a></p>\n" }, { "answer_id": 12632553, "author": "Mike Chamberlain", "author_id": 289319, "author_profile": "https://Stackoverflow.com/users/289319", "pm_score": 3, "selected": false, "text": "<p>Here is the \"ultimate\" solution, in that it is implemented as an extension method, uses the IDictionary interface, provides an optional default value, and is written concisely.</p>\n\n<pre><code>public static TV GetValueOrDefault&lt;TK, TV&gt;(this IDictionary&lt;TK, TV&gt; dic, TK key,\n TV defaultVal=default(TV))\n{\n TV val;\n return dic.TryGetValue(key, out val) \n ? val \n : defaultVal;\n}\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4435/" ]
Currently I'm using ``` var x = dict.ContainsKey(key) ? dict[key] : defaultValue ``` I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like ``` var x = dict[key] ?? defaultValue; ``` this also winds up being part of linq queries etc. so I'd prefer one-line solutions.
With an extension method: ``` public static class MyHelper { public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dic, K key, V defaultVal = default(V)) { V ret; bool found = dic.TryGetValue(key, out ret); if (found) { return ret; } return defaultVal; } void Example() { var dict = new Dictionary<int, string>(); dict.GetValueOrDefault(42, "default"); } } ```
254,184
<p>I have a simple HTML upload form, and I want to specify a default extension ("*.drp" for example). I've read that the way to do this is through the ACCEPT attribute of the input tag, but I don't know how exactly.</p> <pre><code>&lt;form enctype="multipart/form-data" action="uploader.php" method="POST"&gt; Upload DRP File: &lt;input name="Upload Saved Replay" type="file" accept="*.drp"/&gt;&lt;br /&gt; &lt;input type="submit" value="Upload File" /&gt; &lt;/form&gt; </code></pre> <p><strong>Edit</strong> I know validation is possible using javascript, but I would like the user to only see ".drp" files in his popup dialog. Also, I don't care much about server-side validation in this application.</p>
[ { "answer_id": 254195, "author": "Brian Cline", "author_id": 32536, "author_profile": "https://Stackoverflow.com/users/32536", "pm_score": 3, "selected": false, "text": "<p>The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept=\"image/png\". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you <strong>might</strong> have to accept a generic MIME type.</p>\n\n<p>Additionally, it appears that most browsers may not honor this attribute.</p>\n\n<p>The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.</p>\n\n<p>Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is \".drp\". This is probably going to be much more supported than the accept attribute.</p>\n" }, { "answer_id": 254203, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 1, "selected": false, "text": "<p>The accept attribute specifies a comma-separated list of content types (MIME types) that the target of the form will process correctly. Unfortunately this attribute is ignored by all the major browsers, so it does not affect the browser's file dialog in any way.</p>\n" }, { "answer_id": 254205, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 1, "selected": false, "text": "<p>You can do it using javascript. Grab the value of the form field in your submit function, parse out the extension.</p>\n\n<p>You can start with something like this:</p>\n\n<pre><code>&lt;form name=\"someform\"enctype=\"multipart/form-data\" action=\"uploader.php\" method=\"POST\"&gt;\n&lt;input type=file name=\"file1\" /&gt;\n&lt;input type=button onclick=\"val()\" value=\"xxxx\" /&gt;\n&lt;/form&gt;\n&lt;script&gt;\nfunction val() {\n alert(document.someform.file1.value)\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>I agree with alexmac - do it server-side as well.</p>\n" }, { "answer_id": 254253, "author": "alexmac", "author_id": 23066, "author_profile": "https://Stackoverflow.com/users/23066", "pm_score": 1, "selected": false, "text": "<p>I wouldnt use this attribute as most browsers ignore it as CMS points out. </p>\n\n<p>By all means use client side validation but only in conjunction with server side. Any client side validation can be got round. </p>\n\n<p>Slightly off topic but some people check the content type to validate the uploaded file. You need to be careful about this as an attacker can easily change it and upload a php file for example. See the example at: <a href=\"http://www.scanit.be/uploads/php-file-upload.pdf\" rel=\"nofollow noreferrer\">http://www.scanit.be/uploads/php-file-upload.pdf</a></p>\n" }, { "answer_id": 6788623, "author": "Nazri", "author_id": 857723, "author_profile": "https://Stackoverflow.com/users/857723", "pm_score": 5, "selected": false, "text": "<p>I use javascript to check file extension. Here is my code:</p>\n\n<p>HTML</p>\n\n<pre><code>&lt;input name=\"fileToUpload\" type=\"file\" onchange=\"check_file()\" &gt;\n</code></pre>\n\n<p>..\n..</p>\n\n<p>javascript</p>\n\n<pre><code>function check_file(){\n str=document.getElementById('fileToUpload').value.toUpperCase();\n suffix=\".JPG\";\n suffix2=\".JPEG\";\n if(str.indexOf(suffix, str.length - suffix.length) == -1||\n str.indexOf(suffix2, str.length - suffix2.length) == -1){\n alert('File type not allowed,\\nAllowed file: *.jpg,*.jpeg');\n document.getElementById('fileToUpload').value='';\n }\n }\n</code></pre>\n" }, { "answer_id": 16858214, "author": "Alistair R", "author_id": 376164, "author_profile": "https://Stackoverflow.com/users/376164", "pm_score": -1, "selected": false, "text": "<p>Another solution with a few lines</p>\n\n<pre><code>function checkFile(i){\n i = i.substr(i.length - 4, i.length).toLowerCase();\n i = i.replace('.','');\n switch(i){\n case 'jpg':\n case 'jpeg':\n case 'png':\n case 'gif':\n // do OK stuff\n break;\n default:\n // do error stuff\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 17042197, "author": "ParaMeterz", "author_id": 1192220, "author_profile": "https://Stackoverflow.com/users/1192220", "pm_score": 5, "selected": false, "text": "<p>For specific formats like yours \".drp \". You can directly pass that in accept=\".drp\" it will work for that. </p>\n\n<blockquote>\n <p>But without \" * \"</p>\n</blockquote>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input name=\"Upload Saved Replay\" type=\"file\" accept=\".drp\" /&gt;\r\n&lt;br/&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I have a simple HTML upload form, and I want to specify a default extension ("\*.drp" for example). I've read that the way to do this is through the ACCEPT attribute of the input tag, but I don't know how exactly. ``` <form enctype="multipart/form-data" action="uploader.php" method="POST"> Upload DRP File: <input name="Upload Saved Replay" type="file" accept="*.drp"/><br /> <input type="submit" value="Upload File" /> </form> ``` **Edit** I know validation is possible using javascript, but I would like the user to only see ".drp" files in his popup dialog. Also, I don't care much about server-side validation in this application.
I use javascript to check file extension. Here is my code: HTML ``` <input name="fileToUpload" type="file" onchange="check_file()" > ``` .. .. javascript ``` function check_file(){ str=document.getElementById('fileToUpload').value.toUpperCase(); suffix=".JPG"; suffix2=".JPEG"; if(str.indexOf(suffix, str.length - suffix.length) == -1|| str.indexOf(suffix2, str.length - suffix2.length) == -1){ alert('File type not allowed,\nAllowed file: *.jpg,*.jpeg'); document.getElementById('fileToUpload').value=''; } } ```
254,197
<p>What I am looking for is the equivalent of <code>System.Windows.SystemParameters.WorkArea</code> for the monitor that the window is currently on.</p> <p><strong>Clarification:</strong> The window in question is <code>WPF</code>, not <code>WinForm</code>.</p>
[ { "answer_id": 254241, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 8, "selected": true, "text": "<p><code>Screen.FromControl</code>, <code>Screen.FromPoint</code> and <code>Screen.FromRectangle</code> should help you with this. For example in WinForms it would be:</p>\n\n<pre><code>class MyForm : Form\n{\n public Rectangle GetScreen()\n {\n return Screen.FromControl(this).Bounds;\n }\n}\n</code></pre>\n\n<p>I don't know of an equivalent call for WPF. Therefore, you need to do something like this extension method.</p>\n\n<pre><code>static class ExtensionsForWPF\n{\n public static System.Windows.Forms.Screen GetScreen(this Window window)\n {\n return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);\n }\n}\n</code></pre>\n" }, { "answer_id": 254258, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 4, "selected": false, "text": "<p>Add on to ffpf</p>\n\n<pre><code>Screen.FromControl(this).Bounds\n</code></pre>\n" }, { "answer_id": 744306, "author": "Pyttroll", "author_id": 88118, "author_profile": "https://Stackoverflow.com/users/88118", "pm_score": 6, "selected": false, "text": "<p>You can use this to get desktop workspace bounds of the primary screen:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.workarea.aspx\" rel=\"noreferrer\"><code>System.Windows.SystemParameters.WorkArea</code></a></p>\n\n<p>This is also useful for getting just the size of the primary screen:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.primaryscreenwidth.aspx\" rel=\"noreferrer\"><code>System.Windows.SystemParameters.PrimaryScreenWidth</code></a>\n<a href=\"http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.primaryscreenheight.aspx\" rel=\"noreferrer\"><code>System.Windows.SystemParameters.PrimaryScreenHeight</code></a></p>\n" }, { "answer_id": 2902734, "author": "742", "author_id": 325094, "author_profile": "https://Stackoverflow.com/users/325094", "pm_score": 5, "selected": false, "text": "<p>Also you may need:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.virtualscreenwidth.aspx\" rel=\"noreferrer\">SystemParameters.VirtualScreenWidth</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.virtualscreenheight.aspx\" rel=\"noreferrer\">SystemParameters.VirtualScreenHeight</a></li>\n</ul>\n\n<p>to get the combined size of all monitors and not one in particular.</p>\n" }, { "answer_id": 12265169, "author": "Andre", "author_id": 1603918, "author_profile": "https://Stackoverflow.com/users/1603918", "pm_score": 3, "selected": false, "text": "<p>I wanted to have the screen resolution before opening the first of my windows, so here a quick solution to open an invisible window before actually measuring screen dimensions (you need to adapt the window parameters to your window in order to ensure that both are openend on the same screen - mainly the <code>WindowStartupLocation</code> is important)</p>\n\n<pre><code>Window w = new Window();\nw.ResizeMode = ResizeMode.NoResize;\nw.WindowState = WindowState.Normal;\nw.WindowStyle = WindowStyle.None;\nw.Background = Brushes.Transparent;\nw.Width = 0;\nw.Height = 0;\nw.AllowsTransparency = true;\nw.IsHitTestVisible = false;\nw.WindowStartupLocation = WindowStartupLocation.Manual;\nw.Show();\nScreen scr = Screen.FromHandle(new WindowInteropHelper(w).Handle);\nw.Close();\n</code></pre>\n" }, { "answer_id": 17574075, "author": "Ricardo Magalhães", "author_id": 1735425, "author_profile": "https://Stackoverflow.com/users/1735425", "pm_score": 2, "selected": false, "text": "<p>I needed to set the maximum size of my window application. This one could changed accordingly the application is is been showed in the primary screen or in the secondary. To overcome this problem e created a simple method that i show you next:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Set the max size of the application window taking into account the current monitor\n/// &lt;/summary&gt;\npublic static void SetMaxSizeWindow(ioConnect _receiver)\n{\n Point absoluteScreenPos = _receiver.PointToScreen(Mouse.GetPosition(_receiver));\n\n if (System.Windows.SystemParameters.VirtualScreenLeft == System.Windows.SystemParameters.WorkArea.Left)\n {\n //Primary Monitor is on the Left\n if (absoluteScreenPos.X &lt;= System.Windows.SystemParameters.PrimaryScreenWidth)\n {\n //Primary monitor\n _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;\n _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;\n }\n else\n {\n //Secondary monitor\n _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;\n _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;\n }\n }\n\n if (System.Windows.SystemParameters.VirtualScreenLeft &lt; 0)\n {\n //Primary Monitor is on the Right\n if (absoluteScreenPos.X &gt; 0)\n {\n //Primary monitor\n _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;\n _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;\n }\n else\n {\n //Secondary monitor\n _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;\n _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 19295701, "author": "Nasenbaer", "author_id": 375368, "author_profile": "https://Stackoverflow.com/users/375368", "pm_score": 2, "selected": false, "text": "<p>This is a \"Center Screen <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.systemparameters_properties.aspx\" rel=\"nofollow noreferrer\">DotNet 4.5 solution</a>\", using <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.aspx\" rel=\"nofollow noreferrer\">SystemParameters</a> instead of <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx\" rel=\"nofollow noreferrer\">System.Windows.Forms</a> or <a href=\"http://msdn.microsoft.com/en-us/library/hswx1e8z%28v=vs.90%29.aspx\" rel=\"nofollow noreferrer\">My.Compuer.Screen</a>:\nSince <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">Windows 8 has changed</a> the screen dimension calculation, the only way it works for me looks like that (Taskbar calculation included):</p>\n\n<pre><code>Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded\n Dim BarWidth As Double = SystemParameters.VirtualScreenWidth - SystemParameters.WorkArea.Width\n Dim BarHeight As Double = SystemParameters.VirtualScreenHeight - SystemParameters.WorkArea.Height\n Me.Left = (SystemParameters.VirtualScreenWidth - Me.ActualWidth - BarWidth) / 2\n Me.Top = (SystemParameters.VirtualScreenHeight - Me.ActualHeight - BarHeight) / 2 \nEnd Sub\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/4M784.jpg\" alt=\"Center Screen WPF XAML\"></p>\n" }, { "answer_id": 19973955, "author": "aDoubleSo", "author_id": 2294365, "author_profile": "https://Stackoverflow.com/users/2294365", "pm_score": 4, "selected": false, "text": "<p>Beware of the scale factor of your windows (100% / 125% / 150% / 200%).\nYou can get the real screen size by using the following code:</p>\n\n<pre><code>SystemParameters.FullPrimaryScreenHeight\nSystemParameters.FullPrimaryScreenWidth\n</code></pre>\n" }, { "answer_id": 36920187, "author": "R.Rusev", "author_id": 5788595, "author_profile": "https://Stackoverflow.com/users/5788595", "pm_score": 4, "selected": false, "text": "<p>Adding a solution that doesn't use WinForms but NativeMethods instead.\nFirst you need to define the native methods needed.</p>\n\n<pre><code>public static class NativeMethods\n{\n public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;\n public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;\n\n\n [DllImport( \"user32.dll\" )]\n public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );\n\n\n [DllImport( \"user32.dll\" )]\n public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );\n\n\n [Serializable, StructLayout( LayoutKind.Sequential )]\n public struct NativeRectangle\n {\n public Int32 Left;\n public Int32 Top;\n public Int32 Right;\n public Int32 Bottom;\n\n\n public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )\n {\n this.Left = left;\n this.Top = top;\n this.Right = right;\n this.Bottom = bottom;\n }\n }\n\n\n [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]\n public sealed class NativeMonitorInfo\n {\n public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );\n public NativeRectangle Monitor;\n public NativeRectangle Work;\n public Int32 Flags;\n }\n}\n</code></pre>\n\n<p>And then get the monitor handle and the monitor info like this.</p>\n\n<pre><code> var hwnd = new WindowInteropHelper( this ).EnsureHandle();\n var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );\n\n if ( monitor != IntPtr.Zero )\n {\n var monitorInfo = new NativeMonitorInfo();\n NativeMethods.GetMonitorInfo( monitor, monitorInfo );\n\n var left = monitorInfo.Monitor.Left;\n var top = monitorInfo.Monitor.Top;\n var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );\n var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );\n }\n</code></pre>\n" }, { "answer_id": 44985172, "author": "Oleg Bash", "author_id": 8274657, "author_profile": "https://Stackoverflow.com/users/8274657", "pm_score": 1, "selected": false, "text": "<p>in C# winforms I have got start point (for case when we have several monitor/diplay and one form is calling another one) with help of the following method:</p>\n\n<pre><code>private Point get_start_point()\n {\n return\n new Point(Screen.GetBounds(parent_class_with_form.ActiveForm).X,\n Screen.GetBounds(parent_class_with_form.ActiveForm).Y\n );\n }\n</code></pre>\n" }, { "answer_id": 60250152, "author": "user3424480", "author_id": 3424480, "author_profile": "https://Stackoverflow.com/users/3424480", "pm_score": 2, "selected": false, "text": "<h2>WinForms</h2>\n<p>For multi-monitor setups you will also need account for the X and Y position:</p>\n<pre><code>Rectangle activeScreenDimensions = Screen.FromControl(this).Bounds;\nthis.Size = new Size(activeScreenDimensions.Width + activeScreenDimensions.X, activeScreenDimensions.Height + activeScreenDimensions.Y);\n</code></pre>\n" }, { "answer_id": 63028215, "author": "Daniel Santos", "author_id": 5001161, "author_profile": "https://Stackoverflow.com/users/5001161", "pm_score": 0, "selected": false, "text": "<p>This <em>debugging</em> code should do the trick well:</p>\n<p>You can explore the properties of the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.screen?view=netcore-3.1\" rel=\"nofollow noreferrer\">Screen Class</a></p>\n<p>Put all displays in an array or list using <em>Screen.AllScreens</em> then capture the index of the current display and its properties.</p>\n<p><a href=\"https://i.stack.imgur.com/iaKAg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iaKAg.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>C#</strong> <em>(Converted from VB by Telerik - Please double check)</em></p>\n<pre><code> {\n List&lt;Screen&gt; arrAvailableDisplays = new List&lt;Screen&gt;();\n List&lt;string&gt; arrDisplayNames = new List&lt;string&gt;();\n\n foreach (Screen Display in Screen.AllScreens)\n {\n arrAvailableDisplays.Add(Display);\n arrDisplayNames.Add(Display.DeviceName);\n }\n\n Screen scrCurrentDisplayInfo = Screen.FromControl(this);\n string strDeviceName = Screen.FromControl(this).DeviceName;\n int idxDevice = arrDisplayNames.IndexOf(strDeviceName);\n\n MessageBox.Show(this, &quot;Number of Displays Found: &quot; + arrAvailableDisplays.Count.ToString() + Constants.vbCrLf + &quot;ID: &quot; + idxDevice.ToString() + Constants.vbCrLf + &quot;Device Name: &quot; + scrCurrentDisplayInfo.DeviceName.ToString + Constants.vbCrLf + &quot;Primary: &quot; + scrCurrentDisplayInfo.Primary.ToString + Constants.vbCrLf + &quot;Bounds: &quot; + scrCurrentDisplayInfo.Bounds.ToString + Constants.vbCrLf + &quot;Working Area: &quot; + scrCurrentDisplayInfo.WorkingArea.ToString + Constants.vbCrLf + &quot;Bits per Pixel: &quot; + scrCurrentDisplayInfo.BitsPerPixel.ToString + Constants.vbCrLf + &quot;Width: &quot; + scrCurrentDisplayInfo.Bounds.Width.ToString + Constants.vbCrLf + &quot;Height: &quot; + scrCurrentDisplayInfo.Bounds.Height.ToString + Constants.vbCrLf + &quot;Work Area Width: &quot; + scrCurrentDisplayInfo.WorkingArea.Width.ToString + Constants.vbCrLf + &quot;Work Area Height: &quot; + scrCurrentDisplayInfo.WorkingArea.Height.ToString, &quot;Current Info for Display '&quot; + scrCurrentDisplayInfo.DeviceName.ToString + &quot;' - ID: &quot; + idxDevice.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);\n}\n</code></pre>\n<p><strong>VB</strong> <em>(Original code)</em></p>\n<pre><code> Dim arrAvailableDisplays As New List(Of Screen)()\n Dim arrDisplayNames As New List(Of String)()\n\n For Each Display As Screen In Screen.AllScreens\n arrAvailableDisplays.Add(Display)\n arrDisplayNames.Add(Display.DeviceName)\n Next\n\n Dim scrCurrentDisplayInfo As Screen = Screen.FromControl(Me)\n Dim strDeviceName As String = Screen.FromControl(Me).DeviceName\n Dim idxDevice As Integer = arrDisplayNames.IndexOf(strDeviceName)\n\n MessageBox.Show(Me,\n &quot;Number of Displays Found: &quot; + arrAvailableDisplays.Count.ToString &amp; vbCrLf &amp;\n &quot;ID: &quot; &amp; idxDevice.ToString + vbCrLf &amp;\n &quot;Device Name: &quot; &amp; scrCurrentDisplayInfo.DeviceName.ToString + vbCrLf &amp;\n &quot;Primary: &quot; &amp; scrCurrentDisplayInfo.Primary.ToString + vbCrLf &amp;\n &quot;Bounds: &quot; &amp; scrCurrentDisplayInfo.Bounds.ToString + vbCrLf &amp;\n &quot;Working Area: &quot; &amp; scrCurrentDisplayInfo.WorkingArea.ToString + vbCrLf &amp;\n &quot;Bits per Pixel: &quot; &amp; scrCurrentDisplayInfo.BitsPerPixel.ToString + vbCrLf &amp;\n &quot;Width: &quot; &amp; scrCurrentDisplayInfo.Bounds.Width.ToString + vbCrLf &amp;\n &quot;Height: &quot; &amp; scrCurrentDisplayInfo.Bounds.Height.ToString + vbCrLf &amp;\n &quot;Work Area Width: &quot; &amp; scrCurrentDisplayInfo.WorkingArea.Width.ToString + vbCrLf &amp;\n &quot;Work Area Height: &quot; &amp; scrCurrentDisplayInfo.WorkingArea.Height.ToString,\n &quot;Current Info for Display '&quot; &amp; scrCurrentDisplayInfo.DeviceName.ToString &amp; &quot;' - ID: &quot; &amp; idxDevice.ToString, MessageBoxButtons.OK, MessageBoxIcon.Information)\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/HaDAa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HaDAa.png\" alt=\"Screens List\" /></a></p>\n" }, { "answer_id": 71232027, "author": "HemmaRoyD", "author_id": 12781899, "author_profile": "https://Stackoverflow.com/users/12781899", "pm_score": 0, "selected": false, "text": "<p>I Know it's an old question, but others may get some value from this</p>\n<pre><code>int formWidth = form.Width;\nint formHeight = form.Height;\nint formTop = form.Top;\nint formLeft = form.Left;\n\nScreen screen = Screen.PrimaryScreen;\nRectangle rect = screen.Bounds;\nint screenWidth = rect.Width;\nint screenHeight = rect.Height;\nint screenTop = rect.Top;\nint screenLeft = rect.Left;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28736/" ]
What I am looking for is the equivalent of `System.Windows.SystemParameters.WorkArea` for the monitor that the window is currently on. **Clarification:** The window in question is `WPF`, not `WinForm`.
`Screen.FromControl`, `Screen.FromPoint` and `Screen.FromRectangle` should help you with this. For example in WinForms it would be: ``` class MyForm : Form { public Rectangle GetScreen() { return Screen.FromControl(this).Bounds; } } ``` I don't know of an equivalent call for WPF. Therefore, you need to do something like this extension method. ``` static class ExtensionsForWPF { public static System.Windows.Forms.Screen GetScreen(this Window window) { return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle); } } ```
254,200
<p>Unsure if I've phrased this correctly, but in the callback how do I reference the controls property of the base class?</p> <p>This has been bugging me for some time and I usually work around it, but I'd be grateful if anybody can enlighten me on how I should do this properly.</p> <pre><code>var base = function() { var controls = {}; return { init: function(c) { this.controls = c }, foo: function(args) { this.init(args.controls); $(this.controls.DropDown).change(function() { $(this.controls.PlaceHolder).toggle(); }); } } }; </code></pre> <p>Much Obliged,</p> <p>Paul</p>
[ { "answer_id": 254233, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 1, "selected": false, "text": "<p>You need to leverage closures here.</p>\n\n<pre><code>var base = function() {\nvar controls = {};\n\nreturn {\n init: function(c) {\n this.controls = c\n },\n foo: function(args) {\n this.init(args.controls);\n $(this.controls.DropDown).change(function(controls) {\n return function(){\n $(controls.PlaceHolder).toggle();\n }\n }(this.controls));\n }\n}\n</code></pre>\n\n<p>};</p>\n" }, { "answer_id": 254237, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 3, "selected": true, "text": "<p>Use the power of closures:</p>\n\n<pre><code>var base = function() {\n var controls = {};\n\n return {\n init: function(c) {\n this.controls = c\n },\n foo: function(args) {\n var self = this;\n\n this.init(args.controls);\n $(this.controls.DropDown).change(function() {\n $(self.controls.PlaceHolder).toggle();\n });\n }\n }\n};\n</code></pre>\n" }, { "answer_id": 254589, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 2, "selected": false, "text": "<p>Although <a href=\"https://stackoverflow.com/questions/254200/access-parent-property-in-jquery-callback#254233\">closures</a> are <a href=\"https://stackoverflow.com/questions/254200/access-parent-property-in-jquery-callback#254237\">preferred</a>, you could also use jquery <code>bind</code> to pass an object along:</p>\n\n<pre><code>var base = function() {\n var controls = {};\n\n return {\n init: function(c) {\n this.controls = c\n },\n foo: function(args) {\n this.init(args.controls);\n $(this.controls.DropDown).bind('change', {controls: this.controls}, function(event) {\n $(event.data.controls.PlaceHolder).toggle();\n });\n }\n }\n};\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9948/" ]
Unsure if I've phrased this correctly, but in the callback how do I reference the controls property of the base class? This has been bugging me for some time and I usually work around it, but I'd be grateful if anybody can enlighten me on how I should do this properly. ``` var base = function() { var controls = {}; return { init: function(c) { this.controls = c }, foo: function(args) { this.init(args.controls); $(this.controls.DropDown).change(function() { $(this.controls.PlaceHolder).toggle(); }); } } }; ``` Much Obliged, Paul
Use the power of closures: ``` var base = function() { var controls = {}; return { init: function(c) { this.controls = c }, foo: function(args) { var self = this; this.init(args.controls); $(this.controls.DropDown).change(function() { $(self.controls.PlaceHolder).toggle(); }); } } }; ```
254,207
<p>Anyone familiar with error below? When I run my webapp to generate a dynamic excel doc from my local machine it works fine but when the same piece of code is invoked on the server I get the below error. It seems like it's a permissions issues since it works on my machine but not the server but I don't know where to start in order to pinpoint the problem. Any guidance/help is greatly appreciated!</p> <pre><code>Server Error in '/' Application. -------------------------------------------------------------------------------- This command is unavailable because the license to use this application has expired. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Runtime.InteropServices.COMException: This command is unavailable because the license to use this application has expired. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [COMException (0x800a03ec): This command is unavailable because the license to use this application has expired.] Microsoft.Office.Interop.Excel.Workbooks.Add(Object Template) +0 PaymentsReport.Page_Load(Object sender, EventArgs e) +70 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061 </code></pre> <hr> <p>Office/Excel is installed on the server and I can open/save excel docs on the server. Could it be the version of excel on the server vs. my local machine? If so how can I make sure I have the latest on the server?</p>
[ { "answer_id": 254218, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": true, "text": "<p>Using Office Interop requires that the Office components you're using actually be installed on the server.</p>\n" }, { "answer_id": 254231, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Do you have a licensed, activated copy of Excel on the server? It probably works on your local machine because you have Office/Excel installed locally.</p>\n" }, { "answer_id": 254239, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I'm gonna take a WAG and say that you just can't slap any old copy of Office on a server and let multiple users access it via your website. You need to look at the licensing restrictions for using MS office in a server environment. </p>\n" }, { "answer_id": 3821505, "author": "Simon D", "author_id": 161040, "author_profile": "https://Stackoverflow.com/users/161040", "pm_score": 3, "selected": false, "text": "<p>Apart from being installed, you need to make sure the application is activated on the server:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/294973\" rel=\"noreferrer\">http://support.microsoft.com/kb/294973</a></p>\n\n<p>Has details on how to do this.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877/" ]
Anyone familiar with error below? When I run my webapp to generate a dynamic excel doc from my local machine it works fine but when the same piece of code is invoked on the server I get the below error. It seems like it's a permissions issues since it works on my machine but not the server but I don't know where to start in order to pinpoint the problem. Any guidance/help is greatly appreciated! ``` Server Error in '/' Application. -------------------------------------------------------------------------------- This command is unavailable because the license to use this application has expired. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Runtime.InteropServices.COMException: This command is unavailable because the license to use this application has expired. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [COMException (0x800a03ec): This command is unavailable because the license to use this application has expired.] Microsoft.Office.Interop.Excel.Workbooks.Add(Object Template) +0 PaymentsReport.Page_Load(Object sender, EventArgs e) +70 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061 ``` --- Office/Excel is installed on the server and I can open/save excel docs on the server. Could it be the version of excel on the server vs. my local machine? If so how can I make sure I have the latest on the server?
Using Office Interop requires that the Office components you're using actually be installed on the server.
254,213
<p>I need to handle resultsets returning stored procedures/functions for three databases (Oracle, sybase, MS-Server). The procedures/functions are generally the same but the call is a little different in Oracle.</p> <pre><code>statement.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR); ... statement.execute(); ResultSet rs = (ResultSet)statement.getObject(1); </code></pre> <p>JDBC doesn't provide a generic way to handle this, so I'll need to distinguish the different types of DBs in my code. I'm given the connection but don't know the best way to determine if the DB is oracle. I can use the driver name but would rather find a cleaner way.</p>
[ { "answer_id": 254220, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 6, "selected": false, "text": "<p>I suspect you would want to use the DatabaseMetaData class. Most likely <a href=\"http://docs.oracle.com/javase/8/docs/api/java/sql/DatabaseMetaData.html#getDatabaseProductName--\" rel=\"noreferrer\">DatabaseMetaData.getDatabaseProductName</a> would be sufficient, though you may also want to use the getDatabaseProductVersion method if you have code that depends on the particular version of the particular database you're working with.</p>\n" }, { "answer_id": 9064789, "author": "Rinat Tainov", "author_id": 479625, "author_profile": "https://Stackoverflow.com/users/479625", "pm_score": 2, "selected": false, "text": "<p>You can use org.apache.ddlutils, class <a href=\"http://db.apache.org/ddlutils/api/org/apache/ddlutils/PlatformUtils.html\" rel=\"nofollow\">Platformutils</a>: </p>\n\n<pre><code>databaseName = new PlatformUtils().determineDatabaseType(dataSource)\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to handle resultsets returning stored procedures/functions for three databases (Oracle, sybase, MS-Server). The procedures/functions are generally the same but the call is a little different in Oracle. ``` statement.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR); ... statement.execute(); ResultSet rs = (ResultSet)statement.getObject(1); ``` JDBC doesn't provide a generic way to handle this, so I'll need to distinguish the different types of DBs in my code. I'm given the connection but don't know the best way to determine if the DB is oracle. I can use the driver name but would rather find a cleaner way.
I suspect you would want to use the DatabaseMetaData class. Most likely [DatabaseMetaData.getDatabaseProductName](http://docs.oracle.com/javase/8/docs/api/java/sql/DatabaseMetaData.html#getDatabaseProductName--) would be sufficient, though you may also want to use the getDatabaseProductVersion method if you have code that depends on the particular version of the particular database you're working with.
254,214
<p>Is there any good software that will allow me to search through my SVN respository for code snippets? I found 'FishEye' but the cost is 1,200 and well outside my budget.</p>
[ { "answer_id": 254305, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 1, "selected": false, "text": "<p>A lot of SVN repos are \"simply\" HTTP sites, so you might consider looking at some off the shelf \"web crawling\" search app that you can point at the SVN root and it will give you basic functionality. Updating it will probably be a bit of a trick, perhaps some SVN check in hackery can tickle the index to discard or reindex changes as you go.</p>\n\n<p>Just thinking out loud.</p>\n" }, { "answer_id": 254338, "author": "Brendon-Van-Heyzen", "author_id": 1425, "author_profile": "https://Stackoverflow.com/users/1425", "pm_score": 1, "selected": false, "text": "<p>theres krugle and koders but both are expensive. Both have ide plugins for eclipse.</p>\n" }, { "answer_id": 254492, "author": "Kai", "author_id": 24083, "author_profile": "https://Stackoverflow.com/users/24083", "pm_score": 2, "selected": false, "text": "<p>I do like TRAC - this plugin might be helpful for your task: <a href=\"http://trac-hacks.org/wiki/RepoSearchPlugin\" rel=\"nofollow noreferrer\">http://trac-hacks.org/wiki/RepoSearchPlugin</a></p>\n" }, { "answer_id": 254545, "author": "Ben Noland", "author_id": 32899, "author_profile": "https://Stackoverflow.com/users/32899", "pm_score": 3, "selected": false, "text": "<p>We use <a href=\"http://opensolaris.org/os/project/opengrok/\" rel=\"noreferrer\">http://opensolaris.org/os/project/opengrok/</a></p>\n" }, { "answer_id": 254609, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 2, "selected": false, "text": "<p>If you're really desperate, do a dump of the repo (look at \"svnadmin dump\") and then grep through it. It's not pretty, but you can look around the search results to find the metadata that indicates the file and revision, then check it out for a better look.</p>\n\n<p>Not a good solution, to be sure, but it is free :) SVN provides no feature for searching past checkins (or even past log files, AFAIK).</p>\n" }, { "answer_id": 254801, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "<p>Painfully slow (and crudely implemented) but a combination of svn log and svn cat works if you are searching the history of single files or small repositories:</p>\n\n<pre><code>svn log filetosearch |\n grep '^r' |\n cut -f1 -d' ' |\n xargs -i bash -c \"echo '{}'; svn cat filetosearch -'{}'\" \n</code></pre>\n\n<p>will output each revision number where file changed and the file. You could always cat each revision into a different file and then grep for changes.</p>\n\n<p>PS. Massive upvotes to anyone that shows me how to do this properly!</p>\n" }, { "answer_id": 1287096, "author": "Elmar Weber", "author_id": 19935, "author_profile": "https://Stackoverflow.com/users/19935", "pm_score": 5, "selected": false, "text": "<p>There is <a href=\"http://sourceforge.net/projects/svn-search/\" rel=\"noreferrer\">sourceforge.net/projects/svn-search</a>.</p>\n\n<p>There is also a Windows application directly from the SVN home called SvnQuery available at <a href=\"http://svnquery.tigris.org/\" rel=\"noreferrer\">http://svnquery.tigris.org</a></p>\n" }, { "answer_id": 3064429, "author": "phil_w", "author_id": 369665, "author_profile": "https://Stackoverflow.com/users/369665", "pm_score": 6, "selected": false, "text": "<p>If you're searching only for the filename, use:</p>\n\n<pre><code>svn list -R file:///subversion/repository | grep filename\n</code></pre>\n\n<p>Windows:</p>\n\n<pre><code>svn list -R file:///subversion/repository | findstr filename\n</code></pre>\n\n<p>Otherwise checkout and do filesystem search:</p>\n\n<pre><code>egrep -r _code_ .\n</code></pre>\n" }, { "answer_id": 3064621, "author": "Vi.", "author_id": 266720, "author_profile": "https://Stackoverflow.com/users/266720", "pm_score": 3, "selected": false, "text": "<ol>\n<li>Create <code>git-svn</code> mirror of that repository.</li>\n<li>Search for added or removed strings inside git: <code>git log -S'my line of code'</code> or the same in <code>gitk</code></li>\n</ol>\n\n<p>The advantage is that you can do many searches locally, without loading the server and network connection.</p>\n" }, { "answer_id": 3203886, "author": "David d C e Freitas", "author_id": 40961, "author_profile": "https://Stackoverflow.com/users/40961", "pm_score": 2, "selected": false, "text": "<p>Just a note, <a href=\"https://www.atlassian.com/software/fisheye/overview\" rel=\"nofollow noreferrer\"><strong>FishEye</strong></a> (and a lot of other Atlassian products) have a $10 Starter Editions, which in the case of FishEye gives you 5 repositories and access for up to 10 committers.\nThe money goes to charity in this case.</p>\n\n<blockquote>\n <p><a href=\"http://www.atlassian.com/starter/\" rel=\"nofollow noreferrer\">www.atlassian.com/starter</a></p>\n</blockquote>\n" }, { "answer_id": 4052505, "author": "Kuryaki", "author_id": 391628, "author_profile": "https://Stackoverflow.com/users/391628", "pm_score": 1, "selected": false, "text": "<p>I started using this tool</p>\n\n<p><a href=\"http://www.supose.org/wiki/supose\" rel=\"nofollow\">http://www.supose.org/wiki/supose</a></p>\n\n<p>It works fine just lacking a visual UI, but is fast and somewhat maintained</p>\n" }, { "answer_id": 6510268, "author": "jek", "author_id": 459642, "author_profile": "https://Stackoverflow.com/users/459642", "pm_score": 0, "selected": false, "text": "<p>// Edit: Tool was already mentioned in another answer, so give all credits to Kuryaki.</p>\n\n<p>Just found <a href=\"http://www.supose.org/wiki/supose\" rel=\"nofollow\">SupoSE</a> which is a java based command line tool which scans a repository to create an index and afterwards is able to answer certain kinds of queries. We're still evaluating the tool but it looks promising. It's worth to mention that it makes a full index of all revisions including source code files and common office formats.</p>\n" }, { "answer_id": 19297190, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 3, "selected": false, "text": "<p>This example pipes the complete contents of the repository to a file, which you can then quickly search for filenames within an editor:</p>\n\n<pre><code>svn list -R svn://svn &gt; filelist.txt\n</code></pre>\n\n<p>This is useful if the repository is relatively static and you want to do rapid searches without having to repeatedly load everything from the SVN server.</p>\n" }, { "answer_id": 20397195, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 4, "selected": false, "text": "<h2>Update April, 2022</h2>\n<p>VisualSVN Server 5.0 supports <a href=\"https://www.visualsvn.com/server/features/search/\" rel=\"nofollow noreferrer\">full-text repository search</a> through the contents and history. Try out the new full-text search feature on the <a href=\"https://demo-server.visualsvn.com/!/#asf/view/head/subversion/trunk\" rel=\"nofollow noreferrer\">demo server</a>.</p>\n<h2>Update January, 2020</h2>\n<p>VisualSVN Server 4.2 supports finding files and folders in the web interface. Try out the new feature on one of the <a href=\"https://demo-server.visualsvn.com/!/#\" rel=\"nofollow noreferrer\">demo server’s repositories</a>!</p>\n<p>See the <a href=\"https://www.visualsvn.com/server/changes/4.2/\" rel=\"nofollow noreferrer\">version 4.2 Release Notes</a>, and download VisualSVN Server 4.2.0 from the <a href=\"https://www.visualsvn.com/server/download/\" rel=\"nofollow noreferrer\">main download page</a>.</p>\n<p><a href=\"https://i.stack.imgur.com/F5uRw.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/F5uRw.gif\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p><strong>Old answer</strong></p>\n<p>Beginning with <a href=\"http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.log.html\" rel=\"nofollow noreferrer\">Subversion 1.8, you can use <code>--search</code> option with <code>svn log</code> command</a>. Note that the command does not perform full-text search inside a repository, it considers the following data only:</p>\n<ul>\n<li>revision's author (<code>svn:author</code> unversioned property),</li>\n<li>date (<code>svn:date</code> unversioned property),</li>\n<li>log message text (<code>svn:log</code> unversioned property),</li>\n<li>list of changed paths (i.e. paths affected by the particular revision).</li>\n</ul>\n<p>Here is the help page about these new search options:</p>\n<pre><code> If the --search option is used, log messages are displayed only if the\n provided search pattern matches any of the author, date, log message\n text (unless --quiet is used), or, if the --verbose option is also\n provided, a changed path.\n The search pattern may include &quot;glob syntax&quot; wildcards:\n ? matches any single character\n * matches a sequence of arbitrary characters\n [abc] matches any of the characters listed inside the brackets\n If multiple --search options are provided, a log message is shown if\n it matches any of the provided search patterns. If the --search-and\n option is used, that option's argument is combined with the pattern\n from the previous --search or --search-and option, and a log message\n is shown only if it matches the combined search pattern.\n If --limit is used in combination with --search, --limit restricts the\n number of log messages searched, rather than restricting the output\n to a particular number of matching log messages.\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33149/" ]
Is there any good software that will allow me to search through my SVN respository for code snippets? I found 'FishEye' but the cost is 1,200 and well outside my budget.
If you're searching only for the filename, use: ``` svn list -R file:///subversion/repository | grep filename ``` Windows: ``` svn list -R file:///subversion/repository | findstr filename ``` Otherwise checkout and do filesystem search: ``` egrep -r _code_ . ```
254,216
<p>My table structure looks like this:</p> <pre><code> tbl.users tbl.issues +--------+-----------+ +---------+------------+-----------+ | userid | real_name | | issueid | assignedid | creatorid | +--------+-----------+ +---------+------------+-----------+ | 1 | test_1 | | 1 | 1 | 1 | | 2 | test_2 | | 2 | 1 | 2 | +--------+-----------+ +---------+------------+-----------+ </code></pre> <p>Basically I want to write a query that will end in a results table looking like this:</p> <pre><code> (results table) +---------+------------+---------------+-----------+--------------+ | issueid | assignedid | assigned_name | creatorid | creator_name | +---------+------------+---------------+-----------+--------------+ | 1 | 1 | test_1 | 1 | test_1 | | 2 | 1 | test_1 | 2 | test_2 | +---------+------------+---------------+-----------+--------------+ </code></pre> <p>My SQL looks like this at the moment:</p> <pre><code>SELECT `issues`.`issueid`, `issues`.`creatorid`, `issues`.`assignedid`, `users`.`real_name` FROM `issues` JOIN `users` ON ( `users`.`userid` = `issues`.`creatorid` ) OR (`users`.`userid` = `issues`.`assignedid`) ORDER BY `issueid` ASC LIMIT 0 , 30 </code></pre> <p>This returns something like this:</p> <pre><code> (results table) +---------+------------+-----------+-----------+ | issueid | assignedid | creatorid | real_name | +---------+------------+-----------+-----------+ | 1 | 1 | 1 | test_1 | | 2 | 1 | 2 | test_1 | | 2 | 1 | 2 | test_2 | +---------+------------+-----------+-----------+ </code></pre> <p>Can anyone help me get to the desired results table?</p>
[ { "answer_id": 254232, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT DISTINCT (i.issueid, i.creatorid, i.assignedid, u.real_name)\nFROM issues i, users u\nWHERE u.userid = i.creatorid OR u.userid = assignedid\nORDER BY i.issueid ASC\nLIMIT 0 , 30\n</code></pre>\n\n<p>Not sure if the parenthesis are needed or not.</p>\n" }, { "answer_id": 254234, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 4, "selected": true, "text": "<pre><code>SELECT \n IssueID, \n AssignedID, \n CreatorID, \n AssignedUser.real_name AS AssignedName, \n CreatorUser.real_name AS CreatorName\nFROM Issues\n LEFT JOIN Users AS AssignedUser\n ON Issues.AssignedID = AssignedUser.UserID\n LEFT JOIN Users AS CreatorUser\n ON Issues.CreatorID = CreatorUser.UserID\nORDER BY `issueid` ASC\nLIMIT 0, 30\n</code></pre>\n" }, { "answer_id": 254235, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 1, "selected": false, "text": "<p>Use this:</p>\n\n<pre><code>SELECT \n`issues`.`issueid`,\n`issues`.`creatorid`,\n`creator`.`real_name`,\n`issues`.`assignedid`,\n`assigned`.`real_name`\nFROM `issues` i\nINNER JOIN `users` creator ON ( `creator`.`userid` = `issues`.`creatorid` )\nINNER JOIN `users` assigned ON (`assigned`.`userid` = `issues`.`assignedid`)\nORDER BY `issueid` ASC\nLIMIT 0 , 30\n</code></pre>\n" }, { "answer_id": 254243, "author": "JGW", "author_id": 26288, "author_profile": "https://Stackoverflow.com/users/26288", "pm_score": 0, "selected": false, "text": "<p>Does this work?</p>\n\n<p>SELECT\ni.issueid,\ni.assignedid,\nu1.real_name as assigned_name,\ni.creatorid,\nu2.real_name as creator_name\nFROM users u1\nINNER JOIN issues i ON u1.userid = i.assignedid\nINNER JOIN users u2 ON u2.userid = i.creatorid\nORDER BY i.issueid</p>\n" }, { "answer_id": 254292, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>SELECT<br>\ni.issueid,<br>\ni.assignedid,<br>\na.real_name,<br>\ni.creatorid,<br>\nc.real_name<br>\nFROM<br>\nissues i<br>\nINNER JOIN users c<br>\nON c.userid = i.creatorid<br>\nINNER JOIN users a<br>\nON a.userid = i.assignedid<br>\nORDER BY<br>\ni.issueid ASC</p>\n" }, { "answer_id": 254301, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 2, "selected": false, "text": "<p>On the general knowledge front, our illustrious site founder wrote a very nice blog article on this subject which I find myself referring to over and over again.</p>\n<h2><a href=\"https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/\" rel=\"nofollow noreferrer\">Visual Explanation of SQL Joins</a></h2>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
My table structure looks like this: ``` tbl.users tbl.issues +--------+-----------+ +---------+------------+-----------+ | userid | real_name | | issueid | assignedid | creatorid | +--------+-----------+ +---------+------------+-----------+ | 1 | test_1 | | 1 | 1 | 1 | | 2 | test_2 | | 2 | 1 | 2 | +--------+-----------+ +---------+------------+-----------+ ``` Basically I want to write a query that will end in a results table looking like this: ``` (results table) +---------+------------+---------------+-----------+--------------+ | issueid | assignedid | assigned_name | creatorid | creator_name | +---------+------------+---------------+-----------+--------------+ | 1 | 1 | test_1 | 1 | test_1 | | 2 | 1 | test_1 | 2 | test_2 | +---------+------------+---------------+-----------+--------------+ ``` My SQL looks like this at the moment: ``` SELECT `issues`.`issueid`, `issues`.`creatorid`, `issues`.`assignedid`, `users`.`real_name` FROM `issues` JOIN `users` ON ( `users`.`userid` = `issues`.`creatorid` ) OR (`users`.`userid` = `issues`.`assignedid`) ORDER BY `issueid` ASC LIMIT 0 , 30 ``` This returns something like this: ``` (results table) +---------+------------+-----------+-----------+ | issueid | assignedid | creatorid | real_name | +---------+------------+-----------+-----------+ | 1 | 1 | 1 | test_1 | | 2 | 1 | 2 | test_1 | | 2 | 1 | 2 | test_2 | +---------+------------+-----------+-----------+ ``` Can anyone help me get to the desired results table?
``` SELECT IssueID, AssignedID, CreatorID, AssignedUser.real_name AS AssignedName, CreatorUser.real_name AS CreatorName FROM Issues LEFT JOIN Users AS AssignedUser ON Issues.AssignedID = AssignedUser.UserID LEFT JOIN Users AS CreatorUser ON Issues.CreatorID = CreatorUser.UserID ORDER BY `issueid` ASC LIMIT 0, 30 ```
254,229
<p>I have a project that I thought was going to be relatively easy, but is turning out to be more of a pain that I had hoped. First, most of the code I'm interacting with is legacy code that I don't have control over, so I can't do big paradigm changes.</p> <p>Here's a simplified explanation of what I need to do: Say I have a large number of simple programs that read from stdin and write to stdout. (These I can't touch). Basically, input to stdin is a command like "Set temperature to 100" or something like that. And the output is an event "Temperature has been set to 100" or "Temperature has fallen below setpoint".</p> <p>What I'd like to do is write an application that can start a bunch of these simple programs, watch for events and then send commands to them as necessary. My initial plan was to something like popen, but I need a bidrectional popen to get both read and write pipes. I hacked something together that I call popen2 where I pass it the command to run and two FILE* that get filled with the read and write stream. Then all I need to do is write a simple loop that reads from each of the stdouts from each of the processes, does the logic that it needs and then writes commands back to the proper process.</p> <p>Here's some pseudocode</p> <pre><code>FILE *p1read, *p1write; FILE *p2read, *p2write; FILE *p3read, *p3write; //start each command, attach to stdin and stdout popen2("process1",&amp;p1read,&amp;p1write); popen2("process2",&amp;p2read,&amp;p2write); popen2("process3",&amp;p3read,&amp;p3write); while (1) { //read status from each process char status1[1024]; char status2[1024]; char status3[1024]; fread(status1,1024,p1read); fread(status2,1024,p2read); fread(status3,1024,p3read); char command1[1024]; char command2[1024]; char command3[1024]; //do some logic here //write command back to each process fwrite(command1,p1write); fwrite(command2,p2write); fwrite(command3,p3write); } </code></pre> <p>The real program is more complicated where it peeks in the stream to see if anything is waiting, if not, it will skip that process, likewise if it doesn't need to send a command to a certain process it doesn't. But this code gives the basic idea.</p> <p>Now this works great on my UNIX box and even pretty good on a Windows XP box with cygwin. However, now I need to get it to work on Win32 natively. </p> <p>The hard part is that my popen2 uses fork() and execl() to start the process and assign the streams to stdin and stdout of the child processes. Is there a clean way I can do this in windows? Basically, I'd like to create a popen2 that works in windows the same way as my unix version. This way the only windows specific code would be in that function and I could get away with everything else working the same way.</p> <p>Any Ideas?</p> <p>Thanks!</p>
[ { "answer_id": 254283, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>I think you've made a very good start to your problem by using the popen2() function to abstract away the cross-platform issues. I was expecting to come and suggest 'sockets', but I'm sure that's not relevant after reading the question. You could use sockets instead of pipes - it would be hidden in the popen2() function.</p>\n\n<p>I am 99% sure you can implement the required functionality on Windows, using Windows APIs. What I cannot do is point you to the right functions reliably. However, you should be aware the Microsoft has most of the POSIX-like API calls available, but the name is prefixed with '_'. There are also native API calls that achieve the effects of <code>fork</code> and <code>exec</code>.</p>\n\n<p>Your comments suggest that you are aware of issues with availability of data and possible deadlocks - be cautious.</p>\n" }, { "answer_id": 254361, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": true, "text": "<p>On Windows, you invoke CreatePipe first (similar to pipe(2)), then CreateProcess. The trick here is that CreateProcess has a parameter where you can pass stdin, stdout, stderr of the newly-created process.</p>\n\n<p>Notice that when you use stdio, you need to do fdopen to create the file object afterwards, which expects file numbers. In the Microsoft CRT, file numbers are different from OS file handles. So to return the other end of CreatePipe to the caller, you first need _open_osfhandle to get a CRT file number, and then fdopen on that.</p>\n\n<p>If you want to see working code, check out _PyPopen in</p>\n\n<p><a href=\"http://svn.python.org/view/python/trunk/Modules/posixmodule.c?view=markup\" rel=\"noreferrer\">http://svn.python.org/view/python/trunk/Modules/posixmodule.c?view=markup</a></p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33152/" ]
I have a project that I thought was going to be relatively easy, but is turning out to be more of a pain that I had hoped. First, most of the code I'm interacting with is legacy code that I don't have control over, so I can't do big paradigm changes. Here's a simplified explanation of what I need to do: Say I have a large number of simple programs that read from stdin and write to stdout. (These I can't touch). Basically, input to stdin is a command like "Set temperature to 100" or something like that. And the output is an event "Temperature has been set to 100" or "Temperature has fallen below setpoint". What I'd like to do is write an application that can start a bunch of these simple programs, watch for events and then send commands to them as necessary. My initial plan was to something like popen, but I need a bidrectional popen to get both read and write pipes. I hacked something together that I call popen2 where I pass it the command to run and two FILE\* that get filled with the read and write stream. Then all I need to do is write a simple loop that reads from each of the stdouts from each of the processes, does the logic that it needs and then writes commands back to the proper process. Here's some pseudocode ``` FILE *p1read, *p1write; FILE *p2read, *p2write; FILE *p3read, *p3write; //start each command, attach to stdin and stdout popen2("process1",&p1read,&p1write); popen2("process2",&p2read,&p2write); popen2("process3",&p3read,&p3write); while (1) { //read status from each process char status1[1024]; char status2[1024]; char status3[1024]; fread(status1,1024,p1read); fread(status2,1024,p2read); fread(status3,1024,p3read); char command1[1024]; char command2[1024]; char command3[1024]; //do some logic here //write command back to each process fwrite(command1,p1write); fwrite(command2,p2write); fwrite(command3,p3write); } ``` The real program is more complicated where it peeks in the stream to see if anything is waiting, if not, it will skip that process, likewise if it doesn't need to send a command to a certain process it doesn't. But this code gives the basic idea. Now this works great on my UNIX box and even pretty good on a Windows XP box with cygwin. However, now I need to get it to work on Win32 natively. The hard part is that my popen2 uses fork() and execl() to start the process and assign the streams to stdin and stdout of the child processes. Is there a clean way I can do this in windows? Basically, I'd like to create a popen2 that works in windows the same way as my unix version. This way the only windows specific code would be in that function and I could get away with everything else working the same way. Any Ideas? Thanks!
On Windows, you invoke CreatePipe first (similar to pipe(2)), then CreateProcess. The trick here is that CreateProcess has a parameter where you can pass stdin, stdout, stderr of the newly-created process. Notice that when you use stdio, you need to do fdopen to create the file object afterwards, which expects file numbers. In the Microsoft CRT, file numbers are different from OS file handles. So to return the other end of CreatePipe to the caller, you first need \_open\_osfhandle to get a CRT file number, and then fdopen on that. If you want to see working code, check out \_PyPopen in <http://svn.python.org/view/python/trunk/Modules/posixmodule.c?view=markup>
254,238
<p>I have a table with columns</p> <blockquote> <p>Index, Date</p> </blockquote> <p>where an Index may have multiple Dates, and my goal is the following: select a list that looks like</p> <blockquote> <p>Index, MinDate, MaxDate</p> </blockquote> <p>where each Index is listed only once, and MinDate (MaxDate) represents the earliest (latest) date present <em>in the entire table for that index</em>. That's easy enough, but then let's constrain this list to appear only for Indexes that are present in a given range of dates. </p> <p>So far, I have the following:</p> <pre><code>SELECT Index, MIN([Date]), MAX([Date]) FROM myTable WHERE Index IN (SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000') GROUP BY Index ORDER BY Index ASC </code></pre> <p>This is excruciatingly slow. Any way to speed this up? [I am running SQL Server 2000.]</p> <p>Thanks!</p> <p>Edited: For clarity.</p>
[ { "answer_id": 254249, "author": "John", "author_id": 33149, "author_profile": "https://Stackoverflow.com/users/33149", "pm_score": -1, "selected": false, "text": "<p>You don't need the sub-select in the where clause. Also, you could add indexes to the date column. How many rows in the table?</p>\n\n<pre><code>SELECT\n [INDEX],\n MIN ( [Date] ),\n MAX ( [Date] )\nFROM\n myTable\nWHERE \n [Date] Between '1/1/2000' And '12/31/2000'\nGROUP BY\n [Index]\nORDER BY\n [INDEX] ASC\n</code></pre>\n" }, { "answer_id": 254254, "author": "Chris Aitchison", "author_id": 33125, "author_profile": "https://Stackoverflow.com/users/33125", "pm_score": 0, "selected": false, "text": "<p>Putting a clustered index on the date column would greatly speed up this query, but obviously it may slow down other currently fast running queries on the table.</p>\n" }, { "answer_id": 254285, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 2, "selected": false, "text": "<p>I am not an SQL Server expert, but if you can do sub-selects like so, this is potentially faster.</p>\n\n<pre><code>SELECT Index,\n (SELECT MIN([Date] FROM myTable WHERE Index = m.Index),\n (SELECT MAX([Date] FROM myTable WHERE Index = m.Index)\nFrom myTable m \nWHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000'\n</code></pre>\n" }, { "answer_id": 254290, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 3, "selected": true, "text": "<p>I would recommend a derived table approach. Like this:</p>\n\n<pre><code>SELECT \n myTable.Index,\n MIN(myTable.[Date]),\n MAX(myTable.[Date])\nFROM myTable\n Inner Join (\n SELECT Index \n From myTable \n WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000') As AliasName\n On myTable.Index = AliasName.Index\nGROUP BY myTable.Index\nORDER BY myTable.Index ASC\n</code></pre>\n\n<p>EDIT: Upon further review, there is another way you can create this query. The following query may be faster, slower, or execute in the same amount of time. This, of course, depends on how the table is indexed.</p>\n\n<pre><code>Select [Index],\n Min([Date]),\n Max([Date])\nFrom myTable\nGroup By [Index]\nHaving Sum(Case When [Date] Between '1/1/2000' And '12/31/2000' Then 1 Else 0 End) &gt; 0\n</code></pre>\n\n<p>Under the best circumstances, this query will cause an index scan (not a seek) to filter out rows you don't want to display. I encourage you to run both queries and pick this oen the executes the fastest.</p>\n" }, { "answer_id": 254316, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": "<p>Jake,</p>\n\n<p>I think you may need to take a different POV at this problem.</p>\n\n<p>The grouped selected of <code>**Index, Min(Date), Max(Date)**</code> isn't going to change drastically over the course of a day, in comparison with the range of data its covers (presumably many years)</p>\n\n<p>So one option would be to create a summary table based on the data in the main table... e.g.</p>\n\n<pre><code> SELECT \n Index, \n Min(Date) as MinDate, \n Max(Date) as MaxDate\n INTO \n MySummaryTable\n FROM \n MyOriginalTable\n GROUP BY\n Index\n</code></pre>\n\n<p>This table could be dropped and recreated on a semi-regular (daily) base via a sql job.\nEqually I'd stick an index on the id column of it.</p>\n\n<p>Then when you need to run you're daily query, </p>\n\n<pre><code>SELECT \n summary.Index,\n summary.MinDate,\n summary.MaxDate\nFROM\n MyOriginalTable mot\n INNER JOIN MySummaryTable summary\n ON mot.Index = summary.Index --THIS IS WHERE YOUR CLUSTERED INDEX WILL PAY OFF\nWHERE\n mot.Date BETWEEN '2000-01-01' AND '2000-12-31' --THIS IS WHERE A SECOND NC INDEX WILL PAY OFF\n</code></pre>\n" }, { "answer_id": 254339, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 0, "selected": false, "text": "<p>Your explanation isn't very clear:</p>\n\n<blockquote>\n <p>where each Index is listed only once, and MinDate (MaxDate) represents the earliest (latest) date present in the entire table.</p>\n</blockquote>\n\n<p>If that is the case, you should either return two resultsets or store the answer such as:</p>\n\n<pre><code>DECLARE @MaxDate datetime, @MinDate datetime\nSELECT\n @MinDate = MIN([Date]),\n @MaxDate = MAX([Date])\nFROM myTable\n--\nSELECT\n [Index],\n @MinDate,\n @MaxDate\nFROM myTable\nWHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000'\n</code></pre>\n\n<p>If you want to know the minimum/maximum for the entire table as well as for the [Index], then try the following in combination with the previous code:</p>\n\n<pre><code>SELECT\n [Index],\n MIN([Date]) AS IndexMinDate,\n MAX([Date]) AS IndexMaxDate,\n @MinDate AS TableMinDate,\n @MaxDate AS TableMaxDate\nFROM myTable\nWHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000'\nGROUP BY [Index]\nORDER BY [Index] ASC\n</code></pre>\n\n<p>Also look into indexing the columns if possible and the query plan. Good luck.</p>\n" }, { "answer_id": 254416, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 0, "selected": false, "text": "<p>An EXISTS operator might be faster than the subquery:</p>\n\n<pre><code>SELECT\n t1.Index,\n MIN(t1.[Date]),\n MAX(t1.[Date])\nFROM\n myTable t1\nWHERE\n EXISTS (SELECT * FROM myTable t2 WHERE t2.Index = t1.Index AND t2.[Date] &gt;= '1/1/2000' AND t2.[Date] &lt; '1/1/2001')\n GROUP BY\n t1.Index\n</code></pre>\n\n<p>It would depend on table size and indexing I suppose. I like G Mastros HAVING clause solution too.</p>\n\n<p>Another important note... if your date is actually a DATETIME and there is a time component in any of your dates (either now or in the future) you could potentially miss some results if an index had a date of 12/31/2000 with any sort of time besides midnight. Just something to keep in mind. You could alternatively use YEAR([Date]) = 2000 (assuming MS SQL Server here). I don't know if the DB would be smart enough to use an index on the date column if you did that though.</p>\n\n<p>EDIT: Added GROUP BY and changed date logic thanks to the comment</p>\n" }, { "answer_id": 254582, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>This should do it in two table scans.</p>\n\n<pre><code>SELECT\n Index,\n MIN([Date]),\n MAX([Date])\nFROM myTable\nWHERE\n Index IN\n (SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000')\nGROUP BY Index\nORDER BY Index ASC\nOPTION (MERGE JOIN)\n</code></pre>\n\n<hr>\n\n<p>Here's another query. This query gets <strong>different results</strong> than was originally asked for. This will get all Indexes that have date ranges that overlap the period of interest (even if there is not any actual activity in the period of interest for that index).</p>\n\n<pre><code>SELECT\n Index,\n MIN([Date]),\n MAX([Date])\nFROM myTable\nGROUP BY Index\nHAVING MIN([Date]) &lt; '2001-01-01' AND MAX([Date]) &gt;= '2000-01-01')\nORDER BY Index ASC\n</code></pre>\n\n<p>So this will return, even if 3 has no data in the 2000 year.</p>\n\n<p>3, 1998-01-01, 2005-01-01</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
I have a table with columns > > Index, Date > > > where an Index may have multiple Dates, and my goal is the following: select a list that looks like > > Index, MinDate, MaxDate > > > where each Index is listed only once, and MinDate (MaxDate) represents the earliest (latest) date present *in the entire table for that index*. That's easy enough, but then let's constrain this list to appear only for Indexes that are present in a given range of dates. So far, I have the following: ``` SELECT Index, MIN([Date]), MAX([Date]) FROM myTable WHERE Index IN (SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000') GROUP BY Index ORDER BY Index ASC ``` This is excruciatingly slow. Any way to speed this up? [I am running SQL Server 2000.] Thanks! Edited: For clarity.
I would recommend a derived table approach. Like this: ``` SELECT myTable.Index, MIN(myTable.[Date]), MAX(myTable.[Date]) FROM myTable Inner Join ( SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000') As AliasName On myTable.Index = AliasName.Index GROUP BY myTable.Index ORDER BY myTable.Index ASC ``` EDIT: Upon further review, there is another way you can create this query. The following query may be faster, slower, or execute in the same amount of time. This, of course, depends on how the table is indexed. ``` Select [Index], Min([Date]), Max([Date]) From myTable Group By [Index] Having Sum(Case When [Date] Between '1/1/2000' And '12/31/2000' Then 1 Else 0 End) > 0 ``` Under the best circumstances, this query will cause an index scan (not a seek) to filter out rows you don't want to display. I encourage you to run both queries and pick this oen the executes the fastest.
254,244
<p>I am wrestling with a php 5.2.6 problem. An api we use returns dates in this format DDMMYYYYHHMM. Exactly that format, fixed length, no delimiters. However, in my experimentation, this format seems to break strptime, which returns a false (fail) when I feed it a date in this format. It can reproduced, at least on my system, with this example:</p> <pre><code>$format = "%d%m%Y%H%M"; echo print_r(strptime(strftime($format,1225405967),$format),true); </code></pre> <p>If I add any character between the date and the time, it works, even a space. So, this DOES work:</p> <pre><code>$format = "%d%m%Y %H%M"; echo print_r(strptime(strftime($format,1225405967),$format),true); </code></pre> <p>Am I missing something obvious?</p> <p>edit: further to this and owing to the results indicated by the comments, this seems to be platform specific. I can reproduce it on the Macs running OSX Leopard in the office but the Linux boxes parse it fine. I assume it is a bug or idiosyncrasy of the strptime in the underlying C library in the *nix of OSX.</p>
[ { "answer_id": 254398, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 0, "selected": false, "text": "<p>Nothing obvious since both versions work fine in PHP 5.2.0. I can't readily check 5.2.6 at the moment, though. That will have to wait until I get home.</p>\n" }, { "answer_id": 256018, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 1, "selected": false, "text": "<p>This function is locale-dependent. Have you tried setting different locale? (see <code>setlocale()</code>)</p>\n" }, { "answer_id": 256053, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<p>It's very likely that this is isolated to Macs only, as this hasn't even been implemented on Windows yet (although I've passed that suggestion along).</p>\n\n<pre><code>5.2.6\nFatal error: Call to undefined function strptime() in F:\\htdocs\\strptime.php on line 5\n</code></pre>\n\n<p>I would go ahead and submit a bug at <a href=\"http://bugs.php.net/\" rel=\"nofollow noreferrer\">bugs.php.net</a>.</p>\n" }, { "answer_id": 256131, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>If you think the problem is on MacOS X and in the C library, then you could produce a test case to demonstrate it. For example, I ran the code below on MacOS X 10.4.11 (PPC, G4, 32-bit), and got the output:</p>\n\n<pre><code>Now: 1225573977\nFormatted (12): 011120082112\nEnd: 0xBFFFF553 (Buffer: 0xBFFFF547)\nThen: year = 2008, month = 11, day = 1, hour = 21, minute = 12\nReformatted (12): 011120082112\n</code></pre>\n\n<p>The code I used is:</p>\n\n<pre><code>#include &lt;time.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(void)\n{\n time_t now = time(0);\n struct tm *tm = gmtime(&amp;now);\n char format[] = \"%d%m%Y%H%M\";\n char buffer1[64];\n char buffer2[64];\n size_t f_len = strftime(buffer1, sizeof(buffer1), format, tm);\n struct tm then;\n char *end = strptime(buffer1, format, &amp;then);\n size_t p_len = strftime(buffer2, sizeof(buffer2), format, &amp;then);\n\n printf(\"Now: %ld\\n\", (long)now);\n printf(\"Formatted (%lu): %s\\n\", (unsigned long)f_len, buffer1);\n printf(\"End: 0x%08lX (Buffer: 0x%08lX)\\n\", (unsigned long)end, (unsigned long)buffer1);\n printf(\"Then: year = %d, month = %d, day = %d, hour = %d, minute = %d\\n\",\n then.tm_year + 1900, then.tm_mon + 1, then.tm_mday, then.tm_hour, then.tm_min);\n printf(\"Reformatted (%lu): %s\\n\", (unsigned long)p_len, buffer2);\n\n return(0);\n}\n</code></pre>\n\n<p>On the basis of what I see, there is no bug in strptime() in the version I'm using. We can debate about the merits of the non-existent error checking, and of the casts versus C99 <code>&lt;inttypes.h&gt;</code> notations in the printing, but I think the code is accurate enough. I used <code>gmtime()</code> instead of <code>localtime()</code>; I doubt if that was a factor in not reproducing the problem.</p>\n\n<p>Maybe you should look at the PHP test suite?\nMaybe you should split your rather complex expression into pieces to detect where the error occurs in PHP?</p>\n" }, { "answer_id": 7093601, "author": "German", "author_id": 292609, "author_profile": "https://Stackoverflow.com/users/292609", "pm_score": 0, "selected": false, "text": "<p>I confirm:</p>\n\n<pre><code> $p = strptime(\"09.02.2002\", \"%d.%m.%Y\");\n var_dump($p);\n</code></pre>\n\n<p>Output:</p>\n\n<p>array(9) {\n [\"tm_sec\"]=>\n int(0)\n [\"tm_min\"]=>\n int(0)\n [\"tm_hour\"]=>\n int(0)\n [\"tm_mday\"]=>\n int(9)\n [\"tm_mon\"]=>\n int(1)\n [\"tm_year\"]=>\n int(102)\n [\"tm_wday\"]=>\n int(0)\n [\"tm_yday\"]=>\n int(0)\n [\"unparsed\"]=>\n string(0) \"\"\n}</p>\n\n<p>OS X Leopard, PHP 5.3.2</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33150/" ]
I am wrestling with a php 5.2.6 problem. An api we use returns dates in this format DDMMYYYYHHMM. Exactly that format, fixed length, no delimiters. However, in my experimentation, this format seems to break strptime, which returns a false (fail) when I feed it a date in this format. It can reproduced, at least on my system, with this example: ``` $format = "%d%m%Y%H%M"; echo print_r(strptime(strftime($format,1225405967),$format),true); ``` If I add any character between the date and the time, it works, even a space. So, this DOES work: ``` $format = "%d%m%Y %H%M"; echo print_r(strptime(strftime($format,1225405967),$format),true); ``` Am I missing something obvious? edit: further to this and owing to the results indicated by the comments, this seems to be platform specific. I can reproduce it on the Macs running OSX Leopard in the office but the Linux boxes parse it fine. I assume it is a bug or idiosyncrasy of the strptime in the underlying C library in the \*nix of OSX.
This function is locale-dependent. Have you tried setting different locale? (see `setlocale()`)
254,259
<p>I use vim (7.1) on OpenVMS V7.3-2.</p> <p>I connect to VMS trough a telnet session with SmartTerm, a terminal emulator.</p> <p>It works fine.</p> <p>But when I start a telnet session from a VMS session (connected via SmartTerm) to another VMS session, some keys doesn't work properly.</p> <pre><code>|--------------| telnet |-------------| telnet |-----------------| | Smartterm | ------&gt; | VMS, Vim OK | ------&gt; | VMS, Vim broken | |--------------| |-------------| |-----------------| </code></pre> <p>Insert, Delete, Home, End, PageUp and PageDown are like ~ in normal mode ( upcase to lowercase or vice-versa )</p> <p>Any idea ?</p> <p>=============================================</p> <p>Edit </p> <p>I just realized that I didn't mention that the second telneted session is on the same VMS box.</p> <p>I do that because I need to do something with rights from another user.</p>
[ { "answer_id": 254286, "author": "Nic Wise", "author_id": 2947, "author_profile": "https://Stackoverflow.com/users/2947", "pm_score": 0, "selected": false, "text": "<p>Usually this is because of the terminal emulation - so something isn't passing the right keys thru. It's been ages since I've done this, but look for stuff like VT-100 and the like. I doubt it's specific to vim, either :)</p>\n\n<p>Sorry I can't be more help.</p>\n" }, { "answer_id": 254303, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 2, "selected": true, "text": "<p>In addition to tweaking which terminal emulation is used, it's also a good idea to learn vim's keystrokes for the actions you're trying to perform. These are more reliable and don't depend on the terminal or the keyboard. For instance:</p>\n\n<ul>\n<li>Insert: i</li>\n<li>Home: ^ goes to first non-whitespace char, 0 goes to first column always</li>\n<li>End: $</li>\n<li>PageUp, PageDown: ctrl-u, ctrl-d move a half-page at a time</li>\n</ul>\n" }, { "answer_id": 254401, "author": "feoh", "author_id": 32514, "author_profile": "https://Stackoverflow.com/users/32514", "pm_score": 0, "selected": false, "text": "<p>The first question to ask is simply: What are you sitting in front of? Are you really on the console of a VAX or Alpha running OpenVMS? My guess is the answer is no.</p>\n\n<p>In the unlikely event that the answer is yes, simply enter:</p>\n\n<p>$ SHOW TERMINAL</p>\n\n<p>and make sure that the TERM variable on the remote UNIX host matches this exactly.</p>\n\n<p>If my guess is correct and you're sitting in front of a PC or a Mac running some sort of terminal emulator like PuTTY or Terminal, then you need to explore your software's options to ensure that the terminal it's emulating is correctly reflected in both the VMS system's world view and that of the remote UNIX host.</p>\n\n<p>Once you've figured out what kind of terminal you're emulating, use the VMS command above once again on the VMS system you're connected to to ensure that there is a match.</p>\n\n<p>If not, simply correct the situation by typing:</p>\n\n<p>$ SET TERMINAL/DEVICE=(your termainal name - e.g. vt100)</p>\n\n<p>and then make sure that TERM on the remote unix host matches what the VMS system is set to.</p>\n\n<p>Once you do all this, everything should work fine.</p>\n" }, { "answer_id": 257228, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 1, "selected": false, "text": "<p>I've experienced similar issues while resurrecting a dusty old Solaris box. I was too lazy to search for how I should set my <code>t_</code>... variables correctly, so I remapped the faulty terminal escape sequences instead:</p>\n\n<pre><code>:map xxx 0 (press &lt;C-v&gt;&lt;Home&gt; in place of xxx)\n:map xxx &lt;C-b&gt; (press &lt;C-v&gt;&lt;PgUp&gt; in place of xxx)\n... etc\n</code></pre>\n\n<p>If you want setup this damned thing right, RTFMing might eat quite some nerve and time:</p>\n\n<pre><code>:h terminal-options\n</code></pre>\n" }, { "answer_id": 10402314, "author": "Yauhen Yakimovich", "author_id": 544463, "author_profile": "https://Stackoverflow.com/users/544463", "pm_score": 0, "selected": false, "text": "<p>In addition to how to set <strong>env</strong> variables on terminal device compatibility, a tip on the telnet client itself might be useful:</p>\n\n<p>Before usual Esc combination use Ctrl+[, e.g. to quit vim</p>\n\n<pre><code>Ctrl+[ Esc :q!\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14673/" ]
I use vim (7.1) on OpenVMS V7.3-2. I connect to VMS trough a telnet session with SmartTerm, a terminal emulator. It works fine. But when I start a telnet session from a VMS session (connected via SmartTerm) to another VMS session, some keys doesn't work properly. ``` |--------------| telnet |-------------| telnet |-----------------| | Smartterm | ------> | VMS, Vim OK | ------> | VMS, Vim broken | |--------------| |-------------| |-----------------| ``` Insert, Delete, Home, End, PageUp and PageDown are like ~ in normal mode ( upcase to lowercase or vice-versa ) Any idea ? ============================================= Edit I just realized that I didn't mention that the second telneted session is on the same VMS box. I do that because I need to do something with rights from another user.
In addition to tweaking which terminal emulation is used, it's also a good idea to learn vim's keystrokes for the actions you're trying to perform. These are more reliable and don't depend on the terminal or the keyboard. For instance: * Insert: i * Home: ^ goes to first non-whitespace char, 0 goes to first column always * End: $ * PageUp, PageDown: ctrl-u, ctrl-d move a half-page at a time
254,260
<p>This question is a follow up to: <a href="https://stackoverflow.com/questions/252267/why-cant-i-call-a-method-outside-of-an-anonymous-class-of-the-same-name">Why can’t I call a method outside of an anonymous class of the same name</a></p> <p>This previous question answer <b>why</b>, but now I want to know if javac <b>should</b> find run(int bar)? (See previous question to see why run(42) fails)</p> <p>If it shouldn't, is it due to a spec? Does it produce ambiguous code? My point is, I think this is a bug. While the previous question explained why this code fails to compile, I feel it should compile if javac searched higher in the tree if it fails to find a match at the current level. IE. If this.run() does not match, it should automatically check NotApplicable.this for a run method.</p> <p>Also note that foo(int bar) is correctly found. If you give any reason why run(int bar) shouldn't be found, it must also explain why foo(int bar) is found.</p> <pre><code>public class NotApplicable { public NotApplicable() { new Runnable() { public void run() { // this works just fine, it automatically used NotApplicable.this when it couldn't find this.foo foo(42); // this fails to compile, javac find this.run(), and it does not match run(42); // to force javac to find run(int bar) you must use the following //NotApplicable.this.run(42); } }; } private void run(int bar) { } public void foo(int bar) { } } </code></pre>
[ { "answer_id": 254272, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Sounds like a recipe for ambiguity and fragility to me - as soon as a new method is added in your base class (okay, not so likely for an interface...) the meaning of your code changes completely.</p>\n\n<p>Anonymous classes are pretty ugly already - making this bit of explicit doesn't bother me at all. </p>\n" }, { "answer_id": 254314, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 3, "selected": true, "text": "<p>This behavior of javac conforms to the spec. See <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#20448\" rel=\"nofollow noreferrer\">§15.12 Method Invocation Expressions</a> in the Java Language Specification, specifically the paragraph under \"Compile Time Step 1\" explaining the meaning of an unqualified method invocation:</p>\n\n<blockquote>\n <p>If the Identifier appears within the scope (§6.3) of a visible method declaration with that name, then there must be an enclosing type declaration of which that method is a member. Let T be the innermost such type declaration. The class or interface to search is T. </p>\n</blockquote>\n\n<p>In other words, the unqualified method <em>name</em> is searched for in all enclosing scopes, and the innermost \"type declaration\" (which means either a class or an interface declaration) in which the name is found is the one that will be searched for the whole signature (in \"Compile Time Step 2\").</p>\n" }, { "answer_id": 254328, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 1, "selected": false, "text": "<p>Try</p>\n\n<pre><code>NotApplicable.this.run(42);\n</code></pre>\n\n<p>instead.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21838/" ]
This question is a follow up to: [Why can’t I call a method outside of an anonymous class of the same name](https://stackoverflow.com/questions/252267/why-cant-i-call-a-method-outside-of-an-anonymous-class-of-the-same-name) This previous question answer **why**, but now I want to know if javac **should** find run(int bar)? (See previous question to see why run(42) fails) If it shouldn't, is it due to a spec? Does it produce ambiguous code? My point is, I think this is a bug. While the previous question explained why this code fails to compile, I feel it should compile if javac searched higher in the tree if it fails to find a match at the current level. IE. If this.run() does not match, it should automatically check NotApplicable.this for a run method. Also note that foo(int bar) is correctly found. If you give any reason why run(int bar) shouldn't be found, it must also explain why foo(int bar) is found. ``` public class NotApplicable { public NotApplicable() { new Runnable() { public void run() { // this works just fine, it automatically used NotApplicable.this when it couldn't find this.foo foo(42); // this fails to compile, javac find this.run(), and it does not match run(42); // to force javac to find run(int bar) you must use the following //NotApplicable.this.run(42); } }; } private void run(int bar) { } public void foo(int bar) { } } ```
This behavior of javac conforms to the spec. See [§15.12 Method Invocation Expressions](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#20448) in the Java Language Specification, specifically the paragraph under "Compile Time Step 1" explaining the meaning of an unqualified method invocation: > > If the Identifier appears within the scope (§6.3) of a visible method declaration with that name, then there must be an enclosing type declaration of which that method is a member. Let T be the innermost such type declaration. The class or interface to search is T. > > > In other words, the unqualified method *name* is searched for in all enclosing scopes, and the innermost "type declaration" (which means either a class or an interface declaration) in which the name is found is the one that will be searched for the whole signature (in "Compile Time Step 2").
254,267
<p>I'm thinking about how to do this, but I have several different shapes of Data in my Database, Articles, NewsItems, etc. </p> <p>They All have something in common, they all have IDs (in the DB they're named ArticleID, NewsID etc. )</p> <p>They all have a <strong>Title</strong></p> <p>They all have <strong>BodyText</strong>.</p> <p>They all have a <strong>Status</strong></p> <p>They all have a <strong>DateAdded</strong></p> <p>What I'd like to do is standard class inheritance.</p> <p>I'd like a Master Class (I don't need to write this to the database) called <strong>Content</strong> with fields like:</p> <ul> <li>ID</li> <li>Title</li> <li>SubTitle</li> <li>BodyText</li> <li>Status</li> <li>AddedDate</li> </ul> <p>I'm not sure how I can do this with the ORM. Why I want this is because then I can pass a list of COntent to my UserControl which is responsible for Rendering it. It will only need the information that is common to all objects.</p> <p>Is this even possible?</p>
[ { "answer_id": 254359, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 1, "selected": false, "text": "<p>I'm not sure whether you're talking about LINQ to SQL, but there are a few resources online about how to create inheritance with it:</p>\n\n<ol>\n<li><a href=\"http://www.davidhayden.com/blog/dave/archive/2007/10/26/LINQToSQLInheritanceDiscriminatorColumnExampleInheritanceMappingTutorial.aspx\" rel=\"nofollow noreferrer\">LINQ To SQL Discriminator Column Example - Inheritance Mapping Tutorial</a></li>\n<li><a href=\"http://www.microsoft.com/uk/msdn/screencasts/screencast/207/Inheritance-in-LINQ-to-SQL.aspx\" rel=\"nofollow noreferrer\">Inheritance in LINQ to SQL Screencast</a></li>\n</ol>\n\n<p>...and more.</p>\n\n<p>HTH</p>\n" }, { "answer_id": 254433, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 0, "selected": false, "text": "<p>I found one page that looks like it has something along the lines of what I'm looking for (The last post)... but I'm not sure about using weakly typed objects:</p>\n\n<p><a href=\"http://www.eggheadcafe.com/software/aspnet/32149682/linq-inheritance-problem.aspx\" rel=\"nofollow noreferrer\">LINQ inheritance</a></p>\n" }, { "answer_id": 254452, "author": "Vyrotek", "author_id": 10941, "author_profile": "https://Stackoverflow.com/users/10941", "pm_score": 3, "selected": true, "text": "<p>This is what Interfaces are for. Have each class implement an IContent interface that contains your Title, BodyText, Status and DateAdded properties. Now you can pass around a collection ( <code>List&lt;IContent&gt;</code> ) around that could containt different types of content.</p>\n\n<p>If you're using LinqToSql you can create partial class files to have the autogenerated classes implement the interface you want.</p>\n\n<pre><code>public partial class SomeContent : IContent\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26931/" ]
I'm thinking about how to do this, but I have several different shapes of Data in my Database, Articles, NewsItems, etc. They All have something in common, they all have IDs (in the DB they're named ArticleID, NewsID etc. ) They all have a **Title** They all have **BodyText**. They all have a **Status** They all have a **DateAdded** What I'd like to do is standard class inheritance. I'd like a Master Class (I don't need to write this to the database) called **Content** with fields like: * ID * Title * SubTitle * BodyText * Status * AddedDate I'm not sure how I can do this with the ORM. Why I want this is because then I can pass a list of COntent to my UserControl which is responsible for Rendering it. It will only need the information that is common to all objects. Is this even possible?
This is what Interfaces are for. Have each class implement an IContent interface that contains your Title, BodyText, Status and DateAdded properties. Now you can pass around a collection ( `List<IContent>` ) around that could containt different types of content. If you're using LinqToSql you can create partial class files to have the autogenerated classes implement the interface you want. ``` public partial class SomeContent : IContent ```
254,271
<p>The WPF control WindowsFormsHost inherits from IDisposable.</p> <p>If I have a complex WPF visual tree containing some of the above controls what event or method can I use to call IDispose during shutdown?</p>
[ { "answer_id": 255334, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": -1, "selected": false, "text": "<p>You don't need to dispose controls when closing a form, the API will do it for you automatically if the control is in the visual tree of the form ( as a child of the form or other control in the form)</p>\n" }, { "answer_id": 257591, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 3, "selected": false, "text": "<p>In the case of application shutdown there is nothing you need to do to properly dispose of the WindowsFormsHost. Since it derives from HwndHost disposing is handled when the Dispatcher is shutdown. If you use Reflector you will see that when HwndHost is initialized it creates a WeakEventDispatcherShutdown.</p>\n\n<p>If you are using it in a dialog the best I can suggest is to override OnClosed and dispose of your Host then, otherwise the HwndHost will hang around until until the Dispatcher is shutdown.</p>\n\n<pre><code>public partial class Dialog : Window\n{\n public Dialog()\n {\n InitializeComponent();\n }\n\n protected override void OnClosed(EventArgs e)\n {\n if (host != null)\n host.Dispose();\n\n base.OnClosed(e);\n }\n}\n</code></pre>\n\n<p>A simple way to test when dispose gets called is to derive a custom class from WindowsFormsHost and play around with different situations. Put a break point in dispose and see when it gets called.</p>\n\n<pre><code>public class CustomWindowsFormsHost : WindowsFormsHost\n{\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n }\n}\n</code></pre>\n" }, { "answer_id": 258482, "author": "morechilli", "author_id": 5427, "author_profile": "https://Stackoverflow.com/users/5427", "pm_score": 3, "selected": true, "text": "<p>Building from Todd's answer I came up with this generic solution for any WPF control that is hosted by a Window and want's to guarantee disposal when that window is closed.</p>\n\n<p>(Obviously if you can avoid inheriting from IDisposable do, but sometimes you just can't)</p>\n\n<p>Dispose is called when the the first parent window in the hierarchy is closed.</p>\n\n<p>(Possible improvement - change the event handling to use the weak pattern)</p>\n\n<pre><code>public partial class MyCustomControl : IDisposable\n {\n\n public MyCustomControl() {\n InitializeComponent();\n\n Loaded += delegate(object sender, RoutedEventArgs e) {\n System.Windows.Window parent_window = Window.GetWindow(this);\n if (parent_window != null) {\n parent_window.Closed += delegate(object sender2, EventArgs e2) {\n Dispose();\n };\n }\n };\n\n ...\n\n }\n\n ...\n }\n</code></pre>\n" }, { "answer_id": 260330, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": -1, "selected": false, "text": "<p>WPF Controls don't implement the IDisposable interface, because <strong>they have nothing to dispose</strong> (No handles to clean up, no unmanaged memory to release). All you need to do is make sure that you don't have any references to the controls and the GC will clean them. </p>\n\n<p>Therefore WPF employs <strong><a href=\"http://msdn.microsoft.com/en-us/library/aa970850.aspx\" rel=\"nofollow noreferrer\">weak event patterns</a></strong> to ensure that controls can be garbage collected. This is the pattern you need to implement to ensure clean-up, not IDisposable.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5427/" ]
The WPF control WindowsFormsHost inherits from IDisposable. If I have a complex WPF visual tree containing some of the above controls what event or method can I use to call IDispose during shutdown?
Building from Todd's answer I came up with this generic solution for any WPF control that is hosted by a Window and want's to guarantee disposal when that window is closed. (Obviously if you can avoid inheriting from IDisposable do, but sometimes you just can't) Dispose is called when the the first parent window in the hierarchy is closed. (Possible improvement - change the event handling to use the weak pattern) ``` public partial class MyCustomControl : IDisposable { public MyCustomControl() { InitializeComponent(); Loaded += delegate(object sender, RoutedEventArgs e) { System.Windows.Window parent_window = Window.GetWindow(this); if (parent_window != null) { parent_window.Closed += delegate(object sender2, EventArgs e2) { Dispose(); }; } }; ... } ... } ```
254,273
<p>Why does this lambda expression not compile?</p> <pre><code>Action a = () =&gt; throw new InvalidOperationException(); </code></pre> <p>Conjecture is fine, but I would really appreciate references to the C# language specification or other documentation.</p> <p>And yes, I know that the following is valid and will compile:</p> <pre><code>Action a = () =&gt; { throw new InvalidOperationException(); }; </code></pre> <p>The context where I would use something like this is described on <a href="http://jacobcarpenter.wordpress.com/2008/10/06/c-compiler-eccentricity-of-the-day-throwing-lambda/" rel="noreferrer">this blog post</a>.</p>
[ { "answer_id": 254298, "author": "Nic Wise", "author_id": 2947, "author_profile": "https://Stackoverflow.com/users/2947", "pm_score": 1, "selected": false, "text": "<p>All the references I can find, from here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx#cs3spec_topic4\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx#cs3spec_topic4</a></p>\n\n<p>show that you have two options:</p>\n\n<pre><code>Action a = () =&gt; { throw new InvalidOperationException(); };\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Action a = () =&gt; throw new InvalidOperationException()\n</code></pre>\n\n<p>Note the missing ; on the end. Yes, it makes no sense to me either. The examples they give in the spec are:</p>\n\n<pre><code>x =&gt; x + 1 // Implicitly typed, expression body\nx =&gt; { return x + 1; } // Implicitly typed, statement body\n(int x) =&gt; x + 1 // Explicitly typed, expression body\n(int x) =&gt; { return x + 1; } // Explicitly typed, statement body\n(x, y) =&gt; x * y // Multiple parameters\n() =&gt; Console.WriteLine() // No parameters\n</code></pre>\n\n<p>Dunno how much help that is - I can't tell what context you are using it in, and not putting a ; on the end makes no sense in C#</p>\n\n<p>the difference may be that it's an expression body - not a statement - if it doesn't have the {}. Which means that your throw is not valid there, as it's a statement, not an expression!</p>\n" }, { "answer_id": 254319, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 4, "selected": false, "text": "<p>Here's my take:</p>\n\n<p><code>throw</code> is a statement, not an expression.</p>\n\n<p>And the reference:</p>\n\n<blockquote>\n <p>12.3.3.11 Throw statements </p>\n \n <p>For a statement stmt of the form </p>\n \n <p><code>throw expr;</code></p>\n \n <p>the definite assignment state of v\n at the beginning of expr is the same\n as the definite assignment state of v\n at the beginning of stmt.</p>\n</blockquote>\n\n<p>To explain the essence perhaps one should think about what an expression implies within the C# lambda construct. It is simply syntactic sugar for:</p>\n\n<pre><code>delegate () { return XXX; }\n</code></pre>\n\n<p>where <code>XXX</code> is an expression</p>\n" }, { "answer_id": 254322, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can't return or throw from an un-scoped lambda. </p>\n\n<p>Think of it this way... If you don't provide a {}, the compiler determines what your implicit return value is. When you <code>throw</code> from within the lambda, there is no return value. You're not even returning <code>void</code>. Why the compiler team didn't handle this situation, I don't know. </p>\n" }, { "answer_id": 254333, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>Hmm. I've got an answer, but it's not great.</p>\n\n<p>I don't believe that there's a \"throw\" <em>expression</em>. There's a throw <em>statement</em>, but not just an expression. Compare this with \"Console.WriteLine()\" which is a method invocation expression with a void type.</p>\n\n<p>As a parallel, you can't have a switch statement, or an if statement etc as the body of a lambda on its own. You can only have an expression or a block (section 7.14). </p>\n\n<p>Is that any help?</p>\n" }, { "answer_id": 254363, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>Not a big surprise. Lambda expressions are an aspect of <em>functional</em> programming. Exceptions are an aspect of <em>procedural</em> programming. The C# mesh between the two styles of programming isn't perfect.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26627/" ]
Why does this lambda expression not compile? ``` Action a = () => throw new InvalidOperationException(); ``` Conjecture is fine, but I would really appreciate references to the C# language specification or other documentation. And yes, I know that the following is valid and will compile: ``` Action a = () => { throw new InvalidOperationException(); }; ``` The context where I would use something like this is described on [this blog post](http://jacobcarpenter.wordpress.com/2008/10/06/c-compiler-eccentricity-of-the-day-throwing-lambda/).
Hmm. I've got an answer, but it's not great. I don't believe that there's a "throw" *expression*. There's a throw *statement*, but not just an expression. Compare this with "Console.WriteLine()" which is a method invocation expression with a void type. As a parallel, you can't have a switch statement, or an if statement etc as the body of a lambda on its own. You can only have an expression or a block (section 7.14). Is that any help?
254,276
<p>First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:<br> a: why it sucks<br> b: how language x has had that for years<br> c: how my mind sucks<br> d: all of the above</p> <p>The idea would give composition the same ease of code reuse that <code>extends</code> does. </p> <p>So if you had a class like this:</p> <pre> public interface A { public void methodInA(); } </pre> <p>And then you had a class like this:</p> <pre> public class B { private composed A; public B() { // construct A within constructor } } </pre> <p>You would then be able to do this:</p> <pre> B myB = new B(); myB.methodInA(); </pre> <p>Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie:</p> <pre> @Overrides public void methodInA(){ // B's own delegation method } </pre> <p>Disadvantages include:</p> <ul> <li>methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with <code>extends</code></li> <li>if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)</li> <li>if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to</li> <li>probably 100 other things I've not thought of</li> </ul> <p>Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.</p>
[ { "answer_id": 254317, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 0, "selected": false, "text": "<p>I'm not sure that I see a clear advantage to doing this though. I understand the point you are making. At the moment to call a method on A you have to myB.getAInstance().methodInA(), but you want to make that myB.methodInA(). </p>\n\n<p>But, what happens if you have multiple instances of A? How would the method call be resolved? Many times composition implies a one to many association so B has many A instances. What happens then?</p>\n\n<p>I agree with your disadvantages listed. It may simply cause too much confusion than it is worth.</p>\n" }, { "answer_id": 254346, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 1, "selected": false, "text": "<p>It sounds cool but I think it makes for some horrible language constructs. Obviously there is a problem if you declare more than one 'composition' of the same class, but even if you forbid that what about the case where a call matches a method in more than one of the (different) composed classes? You would have to specify which one was called in the main class, and you would need extra syntax for that. The situation becomes even worse if there are public members in the classes.</p>\n\n<p>Composition is used to prevent problems with multiple inheritance. Allowing composition like this is effectively permitting multiple inheritance, at least in terms of resolving which method to call. Since a key design decision with Java was to disallow multiple inheritance (for good reasons) I think it unlikely that this would ever be introduced to Java. </p>\n" }, { "answer_id": 254352, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": -1, "selected": false, "text": "<p>There's also the difference between <em>composition</em> and <em>aggregation</em> to consider. How does the compiler know whether you mean 'is-a' or 'has-a' relationships?</p>\n\n<ul>\n<li>Does the whole object graph become eligible for garbage collection or only the head of the graph?</li>\n</ul>\n\n<p>A couple of the ORM mapping tools and frameworks over/around them provide for <code>belongsTo</code> or <code>has-many</code> relationships between persistent objects and some also provide for the cascading delete (for composition). I don't know of one off hand that provides the simple syntactic sugar you're looking for.</p>\n\n<p>Actually, on second thought, Groovy's MetaClass and MetaProgramming idiom(s) may provide something very similar, with 'auto-magic' delegation.</p>\n" }, { "answer_id": 254365, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": -1, "selected": false, "text": "<p>Multiple inheritance is allowed in C++, I know that different but it is along the same thought process. Java was designed to not allow multiple inheritance so that there would be less confusion, therefore bugs and exploits. </p>\n\n<p>What you have suggested is in direct conflict with the principles of java. </p>\n\n<p>Having said that, it would be cool (not necessarily useful). I'm a java programmer who switched from C++. I like being able to make my own mistakes. </p>\n" }, { "answer_id": 254413, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 0, "selected": false, "text": "<p>Check out what is called \"Mixins\" in some languages, and \"Roles\" in the Perl 5 Moose OO system.</p>\n" }, { "answer_id": 254425, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 1, "selected": true, "text": "<p>I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed.</p>\n\n<p>Personally I hate inheritance of concrete classes. I'm a big proponent of Item 14 from Bloch's <em>Effective Java</em>, <a href=\"http://books.google.com/books?id=ZZOiqZQIbRMC&amp;pg=PA71&amp;lpg=PA71&amp;dq=effective+java+composition+over+inheritance&amp;source=bl&amp;ots=UZM06thG21&amp;sig=MQ4wfulnG28_z6TzvxL8uZaszn4&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result\" rel=\"nofollow noreferrer\">Favor composition over inheritence</a>. I think that something like this would make it a little easier to implement the idiom he recommends in that item.</p>\n\n<p>Honestly, if you really knew what you were doing I'll bet you could write a compiler annotation that would handle this. So assuming you had a class Bar that implemented the interface IBar, your class would look like this:</p>\n\n<pre><code>public class Foo {\n\n @Delegate(IBar.class)\n private Bar bar;\n\n // initialize bar via constructor or setter\n}\n</code></pre>\n\n<p>Then during compilation Foo could be made to implement IBar and any of the methods on that interface that weren't already implemented by Foo would end up being generated to look like this:</p>\n\n<pre><code>public Baz method1(Qux val) {\n return bar.method1(val);\n}\n</code></pre>\n\n<p>As mentioned above you would want to make the restriction that only one field per class could use this annotation. If multiple fields had this annotation you'd probably want to throw a compilation error. Alternatively you could figure out a way to encode some sort of precedence model into the parameters passed to it.</p>\n\n<p>Now that I've written this out that seems kinda cool. Maybe I'll play around with it next week. I'll update this if I manage to figure anything out.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ]
First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me: a: why it sucks b: how language x has had that for years c: how my mind sucks d: all of the above The idea would give composition the same ease of code reuse that `extends` does. So if you had a class like this: ``` public interface A { public void methodInA(); } ``` And then you had a class like this: ``` public class B { private composed A; public B() { // construct A within constructor } } ``` You would then be able to do this: ``` B myB = new B(); myB.methodInA(); ``` Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie: ``` @Overrides public void methodInA(){ // B's own delegation method } ``` Disadvantages include: * methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with `extends` * if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?) * if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to * probably 100 other things I've not thought of Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.
I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed. Personally I hate inheritance of concrete classes. I'm a big proponent of Item 14 from Bloch's *Effective Java*, [Favor composition over inheritence](http://books.google.com/books?id=ZZOiqZQIbRMC&pg=PA71&lpg=PA71&dq=effective+java+composition+over+inheritance&source=bl&ots=UZM06thG21&sig=MQ4wfulnG28_z6TzvxL8uZaszn4&hl=en&sa=X&oi=book_result&resnum=1&ct=result). I think that something like this would make it a little easier to implement the idiom he recommends in that item. Honestly, if you really knew what you were doing I'll bet you could write a compiler annotation that would handle this. So assuming you had a class Bar that implemented the interface IBar, your class would look like this: ``` public class Foo { @Delegate(IBar.class) private Bar bar; // initialize bar via constructor or setter } ``` Then during compilation Foo could be made to implement IBar and any of the methods on that interface that weren't already implemented by Foo would end up being generated to look like this: ``` public Baz method1(Qux val) { return bar.method1(val); } ``` As mentioned above you would want to make the restriction that only one field per class could use this annotation. If multiple fields had this annotation you'd probably want to throw a compilation error. Alternatively you could figure out a way to encode some sort of precedence model into the parameters passed to it. Now that I've written this out that seems kinda cool. Maybe I'll play around with it next week. I'll update this if I manage to figure anything out.
254,278
<p>I'm trying to define a table to store student grades for a online report card. I can't decide how to do it, though.</p> <p>The grades are given by subject, in a trimestral period. Every trimester has a average grade, the total missed classes and a "recovering grade" (I don't know the right term in English, but it's an extra test you take to try to raise your grade if you're below the average), I also gotta store the year average and final "recovering grade". Basically, it's like this:</p> <pre><code> |1st Trimester |2nd Trimester |3rd Trimester Subj. |Avg. |Mis. |Rec |Avg. |Mis. |Rec |Avg. |Mis. |Rec |Year Avg. |Final Rec. Math |5.33 |1 |4 |8.0 |0 |7.0 |2 |6.5 |7.0 Sci. |5.33 |1 |4 |8.0 |0 |7.0 |2 |6.5 |7.0 </code></pre> <p>I could store this information in a single DB row, with each row like this:</p> <pre><code>1tAverage | 1tMissedClasses | 1tRecoveringGrade | 2tAverage | 2tMissedClasses | 2tRecoveringGrade </code></pre> <p>And so on, but I figured this would be a pain to mantain, if the scholl ever decides to grade by bimester or some other period (like it used to be up until 3 years ago).<br /> I could also generalize the table fields, and use a tinyint for flagging for which trimester those grades are, or if they're the year finals. But this one would ask for a lot of subqueries to write the report card, also a pain to mantain.</p> <p>Which of the two is better, or is there some other way? Thanks</p>
[ { "answer_id": 254304, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 0, "selected": false, "text": "<p>I think the best solution is to store one row per period. So you'd have a table like:</p>\n\n<pre><code>grades\n------\nstudentID\nperiodNumber\naverageGrade\nmissedClasses\nrecoveringGrade\n</code></pre>\n\n<p>So if it's 2 semesters, you'd have periods 1 and 2. I'd suggest using period 0 to mean \"overall for the year\".</p>\n" }, { "answer_id": 254311, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 0, "selected": false, "text": "<p>It's better to have a second table representing trimester, and have a foreign key reference to the trimester from the grades table (and store individual grades in the grades table). Then do the averages, missed classes, etc using SQL functions SUM and AVG.</p>\n" }, { "answer_id": 254344, "author": "Handruin", "author_id": 26173, "author_profile": "https://Stackoverflow.com/users/26173", "pm_score": 4, "selected": true, "text": "<p>You could try structuring it like this with your tables. I didn't have all the information so I made some guesses at what you might need or do with it all.</p>\n\n<p>TimePeriods:</p>\n\n<ul>\n<li>ID(INT) </li>\n<li>PeriodTimeStart(DateTime)</li>\n<li>PeriodTimeEnd(DateTime)</li>\n<li>Name(VARCHAR(50)</li>\n</ul>\n\n<p>Students:</p>\n\n<ul>\n<li>ID(INT) </li>\n<li>FirstName(VARCHAR(60))</li>\n<li>LastName(VARCHAR(60))</li>\n<li>Birthday(DateTime) </li>\n<li>[any other relevant student field\ninformation added...like contact\ninfo, etc]</li>\n</ul>\n\n<p>Grading:</p>\n\n<ul>\n<li>ID(INT)</li>\n<li>StudentID(INT)</li>\n<li>GradeValue(float)</li>\n<li>TimePeriodID(INT)</li>\n<li>IsRecoveringGrade(boolean)</li>\n</ul>\n\n<p>MissedClasses:</p>\n\n<ul>\n<li>ID(INT)</li>\n<li>StudentID(INT)</li>\n<li>ClassID(INT)</li>\n<li>TimePeriodID(INT)</li>\n<li>DateMissed(DateTime)</li>\n</ul>\n\n<p>Classes:</p>\n\n<ul>\n<li>ID(INT)</li>\n<li>ClassName (VARCHAR(50))</li>\n<li>ClassDescription (TEXT)</li>\n</ul>\n" }, { "answer_id": 254348, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://xkcd.com/327/\" rel=\"nofollow noreferrer\">This comes to mind.</a></p>\n\n<p>(But seriously, err on the side of too many tables, not too few. Handruin has the best solution I see so far).</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9835/" ]
I'm trying to define a table to store student grades for a online report card. I can't decide how to do it, though. The grades are given by subject, in a trimestral period. Every trimester has a average grade, the total missed classes and a "recovering grade" (I don't know the right term in English, but it's an extra test you take to try to raise your grade if you're below the average), I also gotta store the year average and final "recovering grade". Basically, it's like this: ``` |1st Trimester |2nd Trimester |3rd Trimester Subj. |Avg. |Mis. |Rec |Avg. |Mis. |Rec |Avg. |Mis. |Rec |Year Avg. |Final Rec. Math |5.33 |1 |4 |8.0 |0 |7.0 |2 |6.5 |7.0 Sci. |5.33 |1 |4 |8.0 |0 |7.0 |2 |6.5 |7.0 ``` I could store this information in a single DB row, with each row like this: ``` 1tAverage | 1tMissedClasses | 1tRecoveringGrade | 2tAverage | 2tMissedClasses | 2tRecoveringGrade ``` And so on, but I figured this would be a pain to mantain, if the scholl ever decides to grade by bimester or some other period (like it used to be up until 3 years ago). I could also generalize the table fields, and use a tinyint for flagging for which trimester those grades are, or if they're the year finals. But this one would ask for a lot of subqueries to write the report card, also a pain to mantain. Which of the two is better, or is there some other way? Thanks
You could try structuring it like this with your tables. I didn't have all the information so I made some guesses at what you might need or do with it all. TimePeriods: * ID(INT) * PeriodTimeStart(DateTime) * PeriodTimeEnd(DateTime) * Name(VARCHAR(50) Students: * ID(INT) * FirstName(VARCHAR(60)) * LastName(VARCHAR(60)) * Birthday(DateTime) * [any other relevant student field information added...like contact info, etc] Grading: * ID(INT) * StudentID(INT) * GradeValue(float) * TimePeriodID(INT) * IsRecoveringGrade(boolean) MissedClasses: * ID(INT) * StudentID(INT) * ClassID(INT) * TimePeriodID(INT) * DateMissed(DateTime) Classes: * ID(INT) * ClassName (VARCHAR(50)) * ClassDescription (TEXT)
254,281
<p>How do you properly override <code>isEqual:</code> in Objective-C? The "catch" seems to be that if two objects are equal (as determined by the <code>isEqual:</code> method), they must have the same hash value.</p> <p>The <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW25" rel="noreferrer">Introspection</a> section of the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/" rel="noreferrer">Cocoa Fundamentals Guide</a> does have an example on how to override <code>isEqual:</code>, copied as follows, for a class named <code>MyWidget</code>:</p> <pre><code>- (BOOL)isEqual:(id)other { if (other == self) return YES; if (!other || ![other isKindOfClass:[self class]]) return NO; return [self isEqualToWidget:other]; } - (BOOL)isEqualToWidget:(MyWidget *)aWidget { if (self == aWidget) return YES; if (![(id)[self name] isEqual:[aWidget name]]) return NO; if (![[self data] isEqualToData:[aWidget data]]) return NO; return YES; } </code></pre> <p>It checks pointer equality, then class equality, and finally compares the objects using <code>isEqualToWidget:</code>, which only checks the <code>name</code> and <code>data</code> properties. What the example <em>doesn't</em> show is how to override <code>hash</code>.</p> <p>Let's assume there are other properties that do not affect equality, say <code>age</code>. Shouldn't the <code>hash</code> method be overridden such that only <code>name</code> and <code>data</code> affect the hash? And if so, how would you do that? Just add the hashes of <code>name</code> and <code>data</code>? For example:</p> <pre><code>- (NSUInteger)hash { NSUInteger hash = 0; hash += [[self name] hash]; hash += [[self data] hash]; return hash; } </code></pre> <p>Is that sufficient? Is there a better technique? What if you have primitives, like <code>int</code>? Convert them to <code>NSNumber</code> to get their hash? Or structs like <code>NSRect</code>?</p> <p>(<strong>Brain fart</strong>: Originally wrote "bitwise OR" them together with <code>|=</code>. Meant add.)</p>
[ { "answer_id": 254315, "author": "Jens Ayton", "author_id": 6443, "author_profile": "https://Stackoverflow.com/users/6443", "pm_score": 4, "selected": false, "text": "<p>The easy but inefficient way is to return the same <code>-hash</code> value for every instance. Otherwise, yes, you must implement hash based only on objects which affect equality. This is tricky if you use lax comparisons in <code>-isEqual:</code> (e.g. case-insensitive string comparisons). For ints, you can generally use the int itself, unless you’ll be comparing with NSNumbers.</p>\n\n<p>Don’t use |=, though, it will saturate. Use ^= instead.</p>\n\n<p>Random fun fact: <code>[[NSNumber numberWithInt:0] isEqual:[NSNumber numberWithBool:NO]]</code>, but <code>[[NSNumber numberWithInt:0] hash] != [[NSNumber numberWithBool:NO] hash]</code>. (rdar://4538282, open since 05-May-2006)</p>\n" }, { "answer_id": 254326, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 3, "selected": false, "text": "<p>I've found <a href=\"http://web.archive.org/web/20071013053633/http://www.geocities.com/technofundo/tech/java/equalhash.html\" rel=\"nofollow noreferrer\">this page</a> to be a helpful guide in override equals- and hash-type methods. It includes a decent algorithm for calculating hash codes. The page is geared towards Java, but it's pretty easy to adapt it to Objective-C/Cocoa.</p>\n" }, { "answer_id": 254337, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 3, "selected": false, "text": "<p>This doesn't directly answer your question (at all) but I've used MurmurHash before to generate hashes: <a href=\"http://murmurhash.googlepages.com\" rel=\"nofollow noreferrer\">murmurhash</a></p>\n\n<p>Guess I should explain why: murmurhash is bloody fast...</p>\n" }, { "answer_id": 254380, "author": "tcurdt", "author_id": 33165, "author_profile": "https://Stackoverflow.com/users/33165", "pm_score": 8, "selected": true, "text": "<p>Start with</p>\n\n<pre><code> NSUInteger prime = 31;\n NSUInteger result = 1;\n</code></pre>\n\n<p>Then for every primitive you do</p>\n\n<pre><code> result = prime * result + var\n</code></pre>\n\n<p>For objects you use 0 for nil and otherwise their hashcode.</p>\n\n<pre><code> result = prime * result + [var hash];\n</code></pre>\n\n<p>For booleans you use two different values</p>\n\n<pre><code> result = prime * result + ((var)?1231:1237);\n</code></pre>\n\n<hr>\n\n<h2>Explanation and Attribution</h2>\n\n<p>This is not tcurdt's work, and comments were asking for more explanation, so I believe an edit for attribution is fair.</p>\n\n<p>This algorithm was popularized in the book \"Effective Java\", and <a href=\"http://www.scribd.com/doc/36454091/Effective-Java-Chapter3\" rel=\"nofollow noreferrer\">the relevant chapter can currently be found online here</a>. That book popularized the algorithm, which is now a default in a number of Java applications (including Eclipse). It derived, however, from an even older implementation which is variously attributed to Dan Bernstein or Chris Torek. That older algorithm originally floated around on Usenet, and certain attribution is difficult. For example, there is some <a href=\"http://svn.apache.org/repos/asf/apr/apr/trunk/tables/apr_hash.c\" rel=\"nofollow noreferrer\">interesting commentary in this Apache code</a> (search for their names) that references the original source.</p>\n\n<p>Bottom line is, this is a very old, simple hashing algorithm. It is not the most performant, and it is not even proven mathematically to be a \"good\" algorithm. But it is simple, and a lot of people have used it for a long time with good results, so it has a lot of historical support.</p>\n" }, { "answer_id": 254446, "author": "Brian B.", "author_id": 21817, "author_profile": "https://Stackoverflow.com/users/21817", "pm_score": 6, "selected": false, "text": "<p>I'm just picking up Objective-C myself, so I can't speak for that language specifically, but in the other languages I use if two instances are \"Equal\" they must return the same hash - otherwise you are going to have all sorts of problems when trying to use them as keys in a hashtable (or any dictionary-type collections). </p>\n\n<p>On the other hand, if 2 instances are not equal, they may or may not have the same hash - it is best if they don't. This is the difference between an O(1) search on a hash table and an O(N) search - if all your hashes collide you may find that searching your table is no better than searching a list.</p>\n\n<p>In terms of best practices your hash should return a random distribution of values for its input. This means that, for example, if you have a double, but the majority of your values tend to cluster between 0 and 100, you need to make sure that the hashes returned by those values are evenly distributed across the entire range of possible hash values. This will significantly improve your performance.</p>\n\n<p>There are a number of hashing algorithms out there, including several listed here. I try to avoid creating new hash algorithms as it can have large performance implications, so using the existing hash methods and doing a bitwise combination of some sort as you do in your example is a good way to avoid it.</p>\n" }, { "answer_id": 257689, "author": "user10345", "author_id": 10345, "author_profile": "https://Stackoverflow.com/users/10345", "pm_score": 2, "selected": false, "text": "<p>Note that if you're creating a object that can be mutated after creation, the hash value must <em>not change</em> if the object is inserted into a collection. Practically speaking, this means that the hash value must be fixed from the point of the initial object creation. See <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/doc/uid/20000052-BBCGFFCH\" rel=\"nofollow noreferrer\">Apple's documentation on the NSObject protocol's -hash method</a> for more information:</p>\n\n<blockquote>\n <p>If a mutable object is added to a collection that uses hash values to determine the object’s position in the collection, the value returned by the hash method of the object must not change while the object is in the collection. Therefore, either the hash method must not rely on any of the object’s internal state information or you must make sure the object’s internal state information does not change while the object is in the collection. Thus, for example, a mutable dictionary can be put in a hash table but you must not change it while it is in there. (Note that it can be difficult to know whether or not a given object is in a collection.)</p>\n</blockquote>\n\n<p>This sounds like complete whackery to me since it potentially effectively renders hash lookups far less efficient, but I suppose it's better to err on the side of caution and follow what the documentation says.</p>\n" }, { "answer_id": 582100, "author": "ceperry", "author_id": 70410, "author_profile": "https://Stackoverflow.com/users/70410", "pm_score": 2, "selected": false, "text": "<p>I'm an Objective C newbie too, but I found an excellent article about identity vs. equality in Objective C <a href=\"http://www.karlkraft.com/index.php/2008/01/07/equality-vs-identity/\" rel=\"nofollow noreferrer\">here</a>. From my reading it looks like you might be able to just keep the default hash function (which should provide a unique identity) and implement the isEqual method so that it compares data values.</p>\n" }, { "answer_id": 1358903, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Quinn is just wrong that the reference to the murmur hash is useless here. Quinn is right that you want to understand the theory behind hashing. The murmur distills a lot of that theory into an implementation. Figuring out how to apply that implementation to this particular application is worth exploring.</p>\n\n<p>Some of the key points here:</p>\n\n<p>The example function from tcurdt suggests that '31' is a good multiplier because it is prime. One needs to show that being prime is a necessary and sufficient condition. In fact 31 (and 7) are probably not particularly good primes because 31 == -1 % 32. An odd multiplier with about half the bits set and half the bits clear is likely to be better. (The murmur hash multiplication constant has that property.)</p>\n\n<p>This type of hash function would likely be stronger if, after multiplying, the result value were adjusted via a shift and xor. The multiplication tends to produce the results of lots of bit interactions at the high end of the register and low interaction results at the bottom end of the register. The shift and xor increases the interactions at the bottom end of the register.</p>\n\n<p>Setting the initial result to a value where about half the bits are zero and about half the bits are one would also tend to be useful.</p>\n\n<p>It may be useful to be careful about the order in which elements are combined. One should probably first process booleans and other elements where the values are not strongly distributed.</p>\n\n<p>It may be useful to add a couple of extra bit scrambling stages at the end of the computation.</p>\n\n<p>Whether or not the murmur hash is actually fast for this application is an open question. The murmur hash premixes the bits of each input word. Multiple input words can be processed in parallel which helps multiple-issue pipelined cpus.</p>\n" }, { "answer_id": 1681881, "author": "Thibaud de Souza", "author_id": 194422, "author_profile": "https://Stackoverflow.com/users/194422", "pm_score": 1, "selected": false, "text": "<p>Sorry if I risk sounding a complete boffin here but...\n...nobody bothered mentioning that to follow 'best practices' you should definitely not specify an equals method that would NOT take into account all data owned by your target object, e.g whatever data is aggregated to your object, versus an associate of it, should be taken into account when implementing equals.\nIf you don't want to take, say 'age' into account in a comparison, then you should write a comparator and use that to perform your comparisons instead of isEqual:.</p>\n\n<p>If you define an isEqual: method that performs equality comparison arbitrarily, you incur the risk that this method is misused by another developer, or even yourself, once you've forgotten the 'twist' in your equals interpretation.</p>\n\n<p>Ergo, although this is a great q&amp;a about hashing, you don't normally need to redefine the hashing method, you should probably define an ad-hoc comparator instead.</p>\n" }, { "answer_id": 4288017, "author": "LavaSlider", "author_id": 313757, "author_profile": "https://Stackoverflow.com/users/313757", "pm_score": 5, "selected": false, "text": "<p>I found this thread extremely helpful supplying everything I needed to get my <code>isEqual:</code> and <code>hash</code> methods implemented with one catch. When testing object instance variables in <code>isEqual:</code> the example code uses:</p>\n\n<pre><code>if (![(id)[self name] isEqual:[aWidget name]])\n return NO;\n</code></pre>\n\n<p>This repeatedly failed (<i>i.e.</i>, returned <b>NO</b>) without and error, when I <b><i>knew</i></b> the objects were identical in my unit testing. The reason was, one of the <code>NSString</code> instance variables was <i>nil</i> so the above statement was:</p>\n\n<pre><code>if (![nil isEqual: nil])\n return NO;\n</code></pre>\n\n<p>and since <i>nil</i> will respond to any method, this is perfectly legal but </p>\n\n<pre><code>[nil isEqual: nil]\n</code></pre>\n\n<p>returns <i>nil</i>, which is <b>NO</b>, so when both the object and the one being tested had a <i>nil</i> object they would be considered not equal (<i>i.e.</i>, <code>isEqual:</code> would return <b>NO</b>).</p>\n\n<p>This simple fix was to change the if statement to:</p>\n\n<pre><code>if ([self name] != [aWidget name] &amp;&amp; ![(id)[self name] isEqual:[aWidget name]])\n return NO;\n</code></pre>\n\n<p>This way, if their addresses are the same it skips the method call no matter if they are both <i>nil</i> or both pointing to the same object but if either is not <i>nil</i> or they point to different objects then the comparator is appropriately called.</p>\n\n<p>I hope this saves someone a few minutes of head scratching.</p>\n" }, { "answer_id": 4393493, "author": "Paul Solt", "author_id": 276626, "author_profile": "https://Stackoverflow.com/users/276626", "pm_score": 5, "selected": false, "text": "<p>The hash function should create a semi-unique value that is not likely to collide or match another object's hash value.</p>\n<p>Here is the full hash function, which can be adapted to your classes instance variables. It uses NSUInteger's rather than int for compatibility on 64/32bit applications.</p>\n<p>If the result becomes 0 for different objects, you run the risk of colliding hashes. Colliding hashes can result in unexpected program behavior when working with some of the collection classes that depend on the hash function. Make sure to test your hash function prior to use.</p>\n<pre><code>-(NSUInteger)hash {\n NSUInteger result = 1;\n NSUInteger prime = 31;\n NSUInteger yesPrime = 1231;\n NSUInteger noPrime = 1237;\n \n // Add any object that already has a hash function (NSString)\n result = prime * result + [self.myObject hash];\n \n // Add primitive variables (int)\n result = prime * result + self.primitiveVariable; \n\n // Boolean values (BOOL)\n result = prime * result + (self.isSelected ? yesPrime : noPrime);\n \n return result;\n}\n</code></pre>\n" }, { "answer_id": 8902201, "author": "Jonathan Ellis", "author_id": 555485, "author_profile": "https://Stackoverflow.com/users/555485", "pm_score": 3, "selected": false, "text": "<p>Hold on, surely a far easier way to do this is to first override <code>- (NSString )description</code> and provide a string representation of your object state (you must represent the entire state of your object in this string).</p>\n\n<p>Then, just provide the following implementation of <code>hash</code>:</p>\n\n<pre><code>- (NSUInteger)hash {\n return [[self description] hash];\n}\n</code></pre>\n\n<p>This is based on the principle that \"if two string objects are equal (as determined by the isEqualToString: method), they must have the same hash value.\"</p>\n\n<p>Source: <a href=\"http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html\">NSString Class Reference</a></p>\n" }, { "answer_id": 12557880, "author": "user4951", "author_id": 700663, "author_profile": "https://Stackoverflow.com/users/700663", "pm_score": 3, "selected": false, "text": "<p>Remember that you only need to provide hash that's equal when <code>isEqual</code> is true. When <code>isEqual</code> is false, the hash doesn't have to be unequal though presumably it is. Hence:</p>\n\n<p><strong>Keep hash simple. Pick a member (or few members) variable that is the most distinctive.</strong></p>\n\n<p>For example, for CLPlacemark, the name only is enough. Yes there are 2 or 3 distincts CLPlacemark with the exact same name but those are rare. Use that hash.</p>\n\n<pre><code>@interface CLPlacemark (equal)\n- (BOOL)isEqual:(CLPlacemark*)other;\n@end\n\n@implementation CLPlacemark (equal)\n</code></pre>\n\n<p>...</p>\n\n<pre><code>-(NSUInteger) hash\n{\n return self.name.hash;\n}\n\n\n@end\n</code></pre>\n\n<p>Notice I do not bother specifying the city, the country, etc. The name is enough. Perhaps the name and CLLocation.</p>\n\n<p><strong>Hash should be evenly distributed. So you can combine several members variable using the caret ^ (xor sign)</strong></p>\n\n<p>So it's something like</p>\n\n<pre><code>hash = self.member1.hash ^ self.member2.hash ^ self.member3.hash\n</code></pre>\n\n<p>That way the hash will be evenly distributed.</p>\n\n<pre><code>Hash must be O(1), and not O(n)\n</code></pre>\n\n<p>So what to do in array?</p>\n\n<p>Again, simple. You do not have to hash all members of the array. Enough to hash the first element, last element, the count, maybe some middle elements, and that's it.</p>\n" }, { "answer_id": 16633700, "author": "jedwidz", "author_id": 2396171, "author_profile": "https://Stackoverflow.com/users/2396171", "pm_score": 3, "selected": false, "text": "<p>The equals and hash contracts are well specified and thoroughly researched in the Java world (see @mipardi's answer), but all the same considerations should apply to Objective-C.</p>\n\n<p>Eclipse does a reliable job of generating these methods in Java, so here's an Eclipse example ported by hand to Objective-C:</p>\n\n<pre><code>- (BOOL)isEqual:(id)object {\n if (self == object)\n return true;\n if ([self class] != [object class])\n return false;\n MyWidget *other = (MyWidget *)object;\n if (_name == nil) {\n if (other-&gt;_name != nil)\n return false;\n }\n else if (![_name isEqual:other-&gt;_name])\n return false;\n if (_data == nil) {\n if (other-&gt;_data != nil)\n return false;\n }\n else if (![_data isEqual:other-&gt;_data])\n return false;\n return true;\n}\n\n- (NSUInteger)hash {\n const NSUInteger prime = 31;\n NSUInteger result = 1;\n result = prime * result + [_name hash];\n result = prime * result + [_data hash];\n return result;\n}\n</code></pre>\n\n<p>And for a subclass <code>YourWidget</code> which adds a property <code>serialNo</code>:</p>\n\n<pre><code>- (BOOL)isEqual:(id)object {\n if (self == object)\n return true;\n if (![super isEqual:object])\n return false;\n if ([self class] != [object class])\n return false;\n YourWidget *other = (YourWidget *)object;\n if (_serialNo == nil) {\n if (other-&gt;_serialNo != nil)\n return false;\n }\n else if (![_serialNo isEqual:other-&gt;_serialNo])\n return false;\n return true;\n}\n\n- (NSUInteger)hash {\n const NSUInteger prime = 31;\n NSUInteger result = [super hash];\n result = prime * result + [_serialNo hash];\n return result;\n}\n</code></pre>\n\n<p>This implementation avoids some subclassing pitfalls in the sample <code>isEqual:</code> from Apple:</p>\n\n<ul>\n<li>Apple's class test <code>other isKindOfClass:[self class]</code> is asymmetric for two different subclasses of <code>MyWidget</code>. Equality needs to be symmetric: a=b if and only if b=a. This could easily be fixed by changing the test to <code>other isKindOfClass:[MyWidget class]</code>, then all <code>MyWidget</code> subclasses would be mutually comparable.</li>\n<li>Using an <code>isKindOfClass:</code> subclass test prevents subclasses from overriding <code>isEqual:</code> with a refined equality test. This is because equality needs to be transitive: if a=b and a=c then b=c. If a <code>MyWidget</code> instance compares equal to two <code>YourWidget</code> instances, then those <code>YourWidget</code> instances must compare equal to each other, even if their <code>serialNo</code> differs. </li>\n</ul>\n\n<p>The second issue can be fixed by only considering objects to be equal if they belong to the exact same class, hence the <code>[self class] != [object class]</code> test here. For typical <strong>application classes</strong>, this seems to be the best approach.</p>\n\n<p>However, there certainly are cases where the <code>isKindOfClass:</code> test is preferable. This is more typical of <strong>framework classes</strong> than application classes. For example, any <code>NSString</code> should compare equal to any other other <code>NSString</code> with the same underlying character sequence, regardless of the <code>NSString</code>/<code>NSMutableString</code> distinction, and also regardless of what private classes in the <code>NSString</code> class cluster are involved.</p>\n\n<p>In such cases, <code>isEqual:</code> should have well-defined, well-documented behaviour, and it should be made clear that subclasses can't override this. In Java, the 'no override' restriction can be enforced by flagging the equals and hashcode methods as <code>final</code>, but Objective-C has no equivalent.</p>\n" }, { "answer_id": 19667370, "author": "johnboiles", "author_id": 163827, "author_profile": "https://Stackoverflow.com/users/163827", "pm_score": 2, "selected": false, "text": "<p>Combining @tcurdt's answer with @oscar-gomez's answer for <a href=\"https://stackoverflow.com/a/6615878/163827\">getting property names</a>, we can create an easy drop-in solution for both isEqual and hash:</p>\n\n<pre><code>NSArray *PropertyNamesFromObject(id object)\n{\n unsigned int propertyCount = 0;\n objc_property_t * properties = class_copyPropertyList([object class], &amp;propertyCount);\n NSMutableArray *propertyNames = [NSMutableArray arrayWithCapacity:propertyCount];\n\n for (unsigned int i = 0; i &lt; propertyCount; ++i) {\n objc_property_t property = properties[i];\n const char * name = property_getName(property);\n NSString *propertyName = [NSString stringWithUTF8String:name];\n [propertyNames addObject:propertyName];\n }\n free(properties);\n return propertyNames;\n}\n\nBOOL IsEqualObjects(id object1, id object2)\n{\n if (object1 == object2)\n return YES;\n if (!object1 || ![object2 isKindOfClass:[object1 class]])\n return NO;\n\n NSArray *propertyNames = PropertyNamesFromObject(object1);\n for (NSString *propertyName in propertyNames) {\n if (([object1 valueForKey:propertyName] != [object2 valueForKey:propertyName])\n &amp;&amp; (![[object1 valueForKey:propertyName] isEqual:[object2 valueForKey:propertyName]])) return NO;\n }\n\n return YES;\n}\n\nNSUInteger MagicHash(id object)\n{\n NSUInteger prime = 31;\n NSUInteger result = 1;\n\n NSArray *propertyNames = PropertyNamesFromObject(object);\n\n for (NSString *propertyName in propertyNames) {\n id value = [object valueForKey:propertyName];\n result = prime * result + [value hash];\n }\n\n return result;\n}\n</code></pre>\n\n<p>Now, in your custom class you can easily implement <code>isEqual:</code> and <code>hash</code>:</p>\n\n<pre><code>- (NSUInteger)hash\n{\n return MagicHash(self);\n}\n\n- (BOOL)isEqual:(id)other\n{\n return IsEqualObjects(self, other);\n}\n</code></pre>\n" }, { "answer_id": 20014074, "author": "Yariv Nissim", "author_id": 1220642, "author_profile": "https://Stackoverflow.com/users/1220642", "pm_score": 5, "selected": false, "text": "<blockquote>\n<p>A simple XOR over the hash values of critical properties is sufficient\n99% of the time.</p>\n</blockquote>\n<p>For example:</p>\n<pre><code>- (NSUInteger)hash\n{\n return [self.name hash] ^ [self.data hash];\n}\n</code></pre>\n<p>Solution found at <a href=\"http://nshipster.com/equality/\" rel=\"nofollow noreferrer\">http://nshipster.com/equality/</a> by Mattt Thompson (which also referred to this question in his post :~)</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26825/" ]
How do you properly override `isEqual:` in Objective-C? The "catch" seems to be that if two objects are equal (as determined by the `isEqual:` method), they must have the same hash value. The [Introspection](http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW25) section of the [Cocoa Fundamentals Guide](http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/) does have an example on how to override `isEqual:`, copied as follows, for a class named `MyWidget`: ``` - (BOOL)isEqual:(id)other { if (other == self) return YES; if (!other || ![other isKindOfClass:[self class]]) return NO; return [self isEqualToWidget:other]; } - (BOOL)isEqualToWidget:(MyWidget *)aWidget { if (self == aWidget) return YES; if (![(id)[self name] isEqual:[aWidget name]]) return NO; if (![[self data] isEqualToData:[aWidget data]]) return NO; return YES; } ``` It checks pointer equality, then class equality, and finally compares the objects using `isEqualToWidget:`, which only checks the `name` and `data` properties. What the example *doesn't* show is how to override `hash`. Let's assume there are other properties that do not affect equality, say `age`. Shouldn't the `hash` method be overridden such that only `name` and `data` affect the hash? And if so, how would you do that? Just add the hashes of `name` and `data`? For example: ``` - (NSUInteger)hash { NSUInteger hash = 0; hash += [[self name] hash]; hash += [[self data] hash]; return hash; } ``` Is that sufficient? Is there a better technique? What if you have primitives, like `int`? Convert them to `NSNumber` to get their hash? Or structs like `NSRect`? (**Brain fart**: Originally wrote "bitwise OR" them together with `|=`. Meant add.)
Start with ``` NSUInteger prime = 31; NSUInteger result = 1; ``` Then for every primitive you do ``` result = prime * result + var ``` For objects you use 0 for nil and otherwise their hashcode. ``` result = prime * result + [var hash]; ``` For booleans you use two different values ``` result = prime * result + ((var)?1231:1237); ``` --- Explanation and Attribution --------------------------- This is not tcurdt's work, and comments were asking for more explanation, so I believe an edit for attribution is fair. This algorithm was popularized in the book "Effective Java", and [the relevant chapter can currently be found online here](http://www.scribd.com/doc/36454091/Effective-Java-Chapter3). That book popularized the algorithm, which is now a default in a number of Java applications (including Eclipse). It derived, however, from an even older implementation which is variously attributed to Dan Bernstein or Chris Torek. That older algorithm originally floated around on Usenet, and certain attribution is difficult. For example, there is some [interesting commentary in this Apache code](http://svn.apache.org/repos/asf/apr/apr/trunk/tables/apr_hash.c) (search for their names) that references the original source. Bottom line is, this is a very old, simple hashing algorithm. It is not the most performant, and it is not even proven mathematically to be a "good" algorithm. But it is simple, and a lot of people have used it for a long time with good results, so it has a lot of historical support.
254,291
<p>I'm working through <a href="https://rads.stackoverflow.com/amzn/click/com/1590599063" rel="nofollow noreferrer" rel="nofollow noreferrer">Practical Web 2.0 Appications</a> currently and have hit a bit of a roadblock. I'm trying to get PHP, MySQL, Apache, Smarty and the Zend Framework all working correctly so I can begin to build the application. I have gotten the bootstrap file for Zend working, shown here:</p> <pre><code>&lt;?php require_once('Zend/Loader.php'); Zend_Loader::registerAutoload(); // load the application configuration $config = new Zend_Config_Ini('../settings.ini', 'development'); Zend_Registry::set('config', $config); // create the application logger $logger = new Zend_Log(new Zend_Log_Writer_Stream($config-&gt;logging-&gt;file)); Zend_Registry::set('logger', $logger); // connect to the database $params = array('host' =&gt; $config-&gt;database-&gt;hostname, 'username' =&gt; $config-&gt;database-&gt;username, 'password' =&gt; $config-&gt;database-&gt;password, 'dbname' =&gt; $config-&gt;database-&gt;database); $db = Zend_Db::factory($config-&gt;database-&gt;type, $params); Zend_Registry::set('db', $db); // handle the user request $controller = Zend_Controller_Front::getInstance(); $controller-&gt;setControllerDirectory($config-&gt;paths-&gt;base . '/include/Controllers'); // setup the view renderer $vr = new Zend_Controller_Action_Helper_ViewRenderer(); $vr-&gt;setView(new Templater()); $vr-&gt;setViewSuffix('tpl'); Zend_Controller_Action_HelperBroker::addHelper($vr); $controller-&gt;dispatch(); ?&gt; </code></pre> <p>This calls the IndexController. The error comes with the use of this Templater.php to implement Smarty with Zend:</p> <pre><code>&lt;?php class Templater extends Zend_View_Abstract { protected $_path; protected $_engine; public function __construct() { $config = Zend_Registry::get('config'); require_once('Smarty/Smarty.class.php'); $this-&gt;_engine = new Smarty(); $this-&gt;_engine-&gt;template_dir = $config-&gt;paths-&gt;templates; $this-&gt;_engine-&gt;compile_dir = sprintf('%s/tmp/templates_c', $config-&gt;paths-&gt;data); $this-&gt;_engine-&gt;plugins_dir = array($config-&gt;paths-&gt;base . '/include/Templater/plugins', 'plugins'); } public function getEngine() { return $this-&gt;_engine; } public function __set($key, $val) { $this-&gt;_engine-&gt;assign($key, $val); } public function __get($key) { return $this-&gt;_engine-&gt;get_template_vars($key); } public function __isset($key) { return $this-&gt;_engine-&gt;get_template_vars($key) !== null; } public function __unset($key) { $this-&gt;_engine-&gt;clear_assign($key); } public function assign($spec, $value = null) { if (is_array($spec)) { $this-&gt;_engine-&gt;assign($spec); return; } $this-&gt;_engine-&gt;assign($spec, $value); } public function clearVars() { $this-&gt;_engine-&gt;clear_all_assign(); } public function render($name) { return $this-&gt;_engine-&gt;fetch(strtolower($name)); } public function _run() { } } ?&gt; </code></pre> <p>The error I am getting when I load the page is this:</p> <p><code>Fatal error: Call to a member function fetch() on a non-object in /var/www/phpweb20/include/Templater.php on line 60</code></p> <p>I understand it doesn't see $name as an object, but I don't know how to go about fixing this. Isn't the controller supposed to refer to the index.tpl? I haven't been able to discover what the $name variable represents and how to fix this to get the foundation working.</p> <p>Any help you have is much appreciated!</p>
[ { "answer_id": 254358, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 4, "selected": true, "text": "<p>The problem isn't with the $name variable but rather with the $_engine variable. It's currently empty. You need to verify that the path specification to Smarty.class.php is correct. </p>\n\n<p>You might try this to begin your debugging:</p>\n\n<pre><code>$this-&gt;_engine = new Smarty();\nprint_r($this-&gt;_engine);\n</code></pre>\n\n<p>If it turns out that $_engine is correct at that stage then verify that it is still correctly populated within the render() function.</p>\n" }, { "answer_id": 276805, "author": "ironkeith", "author_id": 4106, "author_profile": "https://Stackoverflow.com/users/4106", "pm_score": 0, "selected": false, "text": "<p>Zend has an example of creating a templating system which implements the Zend_View_Interface here: <a href=\"http://framework.zend.com/manual/en/zend.view.scripts.html#zend.view.scripts.templates.interface\" rel=\"nofollow noreferrer\">http://framework.zend.com/manual/en/zend.view.scripts.html#zend.view.scripts.templates.interface</a></p>\n\n<p>That might save you some time from trying to debug a custom solution. </p>\n" }, { "answer_id": 4920299, "author": "ManjuB", "author_id": 606241, "author_profile": "https://Stackoverflow.com/users/606241", "pm_score": 0, "selected": false, "text": "<p>removing the __construct method, from the class, solved the similar issue I was facing.</p>\n" }, { "answer_id": 8919639, "author": "nufnuf", "author_id": 1157450, "author_profile": "https://Stackoverflow.com/users/1157450", "pm_score": 0, "selected": false, "text": "<p>Renaming <code>__construct()</code> to <code>Tempater()</code> worked for me.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27673/" ]
I'm working through [Practical Web 2.0 Appications](https://rads.stackoverflow.com/amzn/click/com/1590599063) currently and have hit a bit of a roadblock. I'm trying to get PHP, MySQL, Apache, Smarty and the Zend Framework all working correctly so I can begin to build the application. I have gotten the bootstrap file for Zend working, shown here: ``` <?php require_once('Zend/Loader.php'); Zend_Loader::registerAutoload(); // load the application configuration $config = new Zend_Config_Ini('../settings.ini', 'development'); Zend_Registry::set('config', $config); // create the application logger $logger = new Zend_Log(new Zend_Log_Writer_Stream($config->logging->file)); Zend_Registry::set('logger', $logger); // connect to the database $params = array('host' => $config->database->hostname, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->database); $db = Zend_Db::factory($config->database->type, $params); Zend_Registry::set('db', $db); // handle the user request $controller = Zend_Controller_Front::getInstance(); $controller->setControllerDirectory($config->paths->base . '/include/Controllers'); // setup the view renderer $vr = new Zend_Controller_Action_Helper_ViewRenderer(); $vr->setView(new Templater()); $vr->setViewSuffix('tpl'); Zend_Controller_Action_HelperBroker::addHelper($vr); $controller->dispatch(); ?> ``` This calls the IndexController. The error comes with the use of this Templater.php to implement Smarty with Zend: ``` <?php class Templater extends Zend_View_Abstract { protected $_path; protected $_engine; public function __construct() { $config = Zend_Registry::get('config'); require_once('Smarty/Smarty.class.php'); $this->_engine = new Smarty(); $this->_engine->template_dir = $config->paths->templates; $this->_engine->compile_dir = sprintf('%s/tmp/templates_c', $config->paths->data); $this->_engine->plugins_dir = array($config->paths->base . '/include/Templater/plugins', 'plugins'); } public function getEngine() { return $this->_engine; } public function __set($key, $val) { $this->_engine->assign($key, $val); } public function __get($key) { return $this->_engine->get_template_vars($key); } public function __isset($key) { return $this->_engine->get_template_vars($key) !== null; } public function __unset($key) { $this->_engine->clear_assign($key); } public function assign($spec, $value = null) { if (is_array($spec)) { $this->_engine->assign($spec); return; } $this->_engine->assign($spec, $value); } public function clearVars() { $this->_engine->clear_all_assign(); } public function render($name) { return $this->_engine->fetch(strtolower($name)); } public function _run() { } } ?> ``` The error I am getting when I load the page is this: `Fatal error: Call to a member function fetch() on a non-object in /var/www/phpweb20/include/Templater.php on line 60` I understand it doesn't see $name as an object, but I don't know how to go about fixing this. Isn't the controller supposed to refer to the index.tpl? I haven't been able to discover what the $name variable represents and how to fix this to get the foundation working. Any help you have is much appreciated!
The problem isn't with the $name variable but rather with the $\_engine variable. It's currently empty. You need to verify that the path specification to Smarty.class.php is correct. You might try this to begin your debugging: ``` $this->_engine = new Smarty(); print_r($this->_engine); ``` If it turns out that $\_engine is correct at that stage then verify that it is still correctly populated within the render() function.
254,295
<p>In a table, I have three columns - id, name, and count. A good number of name columns are identical (due to the lack of a UNIQUE early on) and I want to fix this. However, the id column is used by other (4 or 5, I think - I would have to check the docs) tables to look up the name and just removing them would break things. So is there a good, clean way of saying "find all identical records and merge them together"?</p>
[ { "answer_id": 254353, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "<p>Why can't you do something like</p>\n\n<pre><code>update dependent_table set name_id = &lt;id you want to keep&gt; where name_id in (\n select id from names where name = 'foo' and id != &lt;id you want to keep&gt;)\n</code></pre>\n" }, { "answer_id": 254392, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "<p>This kind of question comes up from time to time. No, there's not a really clean way to do it. You have to change all the rows in the child table that depend on unwanted values in the parent table before you can eliminate the unwanted rows in the parent table.</p>\n\n<p>MySQL supports multi-table <code>UPDATE</code> and <code>DELETE</code> statements (unlike other brands of database) and so you can do some pretty neat tricks like the following:</p>\n\n<pre><code>UPDATE names n1\n JOIN names n2 ON (n1.id &lt; n2.id AND n1.name = n2.name)\n JOIN child_table c ON (n2.id = c.id)\nSET c.name_id = n1.id\nORDER BY n1.id DESC;\n</code></pre>\n\n<p>Once you have done this on all the child table(s), you can use MySQL's multi-table <code>DELETE</code> syntax to remove unwanted rows in the parent table:</p>\n\n<pre><code>DELETE FROM n2\n USING names n1 JOIN names n2 ON (n1.id &lt; n2.id AND n1.name = n2.name);\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
In a table, I have three columns - id, name, and count. A good number of name columns are identical (due to the lack of a UNIQUE early on) and I want to fix this. However, the id column is used by other (4 or 5, I think - I would have to check the docs) tables to look up the name and just removing them would break things. So is there a good, clean way of saying "find all identical records and merge them together"?
This kind of question comes up from time to time. No, there's not a really clean way to do it. You have to change all the rows in the child table that depend on unwanted values in the parent table before you can eliminate the unwanted rows in the parent table. MySQL supports multi-table `UPDATE` and `DELETE` statements (unlike other brands of database) and so you can do some pretty neat tricks like the following: ``` UPDATE names n1 JOIN names n2 ON (n1.id < n2.id AND n1.name = n2.name) JOIN child_table c ON (n2.id = c.id) SET c.name_id = n1.id ORDER BY n1.id DESC; ``` Once you have done this on all the child table(s), you can use MySQL's multi-table `DELETE` syntax to remove unwanted rows in the parent table: ``` DELETE FROM n2 USING names n1 JOIN names n2 ON (n1.id < n2.id AND n1.name = n2.name); ```
254,302
<p>I need a way to determine the type of an HTML element in JavaScript. It has the ID, but the element itself could be a <code>&lt;div&gt;</code>, a <code>&lt;form&gt;</code> field, a <code>&lt;fieldset&gt;</code>, etc. How can I achieve this?</p>
[ { "answer_id": 254308, "author": "Brian Cline", "author_id": 32536, "author_profile": "https://Stackoverflow.com/users/32536", "pm_score": 6, "selected": false, "text": "<p>What about <a href=\"http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-104682815\" rel=\"noreferrer\"><code>element.tagName</code></a>?</p>\n\n<p>See also <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName\" rel=\"noreferrer\"><code>tagName</code> docs on MDN</a>.</p>\n" }, { "answer_id": 254313, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 10, "selected": true, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName\" rel=\"noreferrer\"><code>nodeName</code></a> is the attribute you are looking for. For example:</p>\n\n<pre><code>var elt = document.getElementById('foo');\nconsole.log(elt.nodeName);\n</code></pre>\n\n<p>Note that <code>nodeName</code> returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <code>&lt;div&gt;</code> element you could do it as follows:</p>\n\n<pre><code>elt.nodeName == \"DIV\"\n</code></pre>\n\n<p>While this would not give you the expected results:</p>\n\n<pre><code>elt.nodeName == \"&lt;div&gt;\"\n</code></pre>\n" }, { "answer_id": 55273598, "author": "golopot", "author_id": 3290397, "author_profile": "https://Stackoverflow.com/users/3290397", "pm_score": 4, "selected": false, "text": "<p>Sometimes you want <code>element.constructor.name</code></p>\n\n<pre><code>document.createElement('div').constructor.name\n// HTMLDivElement\n\ndocument.createElement('a').constructor.name\n// HTMLAnchorElement\n\ndocument.createElement('foo').constructor.name\n// HTMLUnknownElement\n</code></pre>\n" }, { "answer_id": 60020069, "author": "Code4R7", "author_id": 7740888, "author_profile": "https://Stackoverflow.com/users/7740888", "pm_score": 5, "selected": false, "text": "<p>You can use generic code inspection via <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof\" rel=\"noreferrer\"><code>instanceof</code></a>:</p>\n\n<pre><code>var e = document.getElementById('#my-element');\nif (e instanceof HTMLInputElement) {} // &lt;input&gt;\nelseif (e instanceof HTMLSelectElement) {} // &lt;select&gt;\nelseif (e instanceof HTMLTextAreaElement) {} // &lt;textarea&gt;\nelseif ( ... ) {} // any interface\n</code></pre>\n\n<p>Look <a href=\"https://developer.mozilla.org/en-US/docs/Web/API\" rel=\"noreferrer\">here</a> for a complete list of interfaces.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103/" ]
I need a way to determine the type of an HTML element in JavaScript. It has the ID, but the element itself could be a `<div>`, a `<form>` field, a `<fieldset>`, etc. How can I achieve this?
[`nodeName`](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName) is the attribute you are looking for. For example: ``` var elt = document.getElementById('foo'); console.log(elt.nodeName); ``` Note that `nodeName` returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an `<div>` element you could do it as follows: ``` elt.nodeName == "DIV" ``` While this would not give you the expected results: ``` elt.nodeName == "<div>" ```
254,340
<p>I've tried variations of this, but had no luck other than the ability to start a cygwin window. (wrapped on <strong>;</strong> for clarity)</p> <pre><code>Filename: "c:\cygwin\bin\bash.exe"; Parameters: "-c c:/scripts/step1.sh paramX"; Flags: shellexec waituntilterminated; StatusMsg: "Running the script..." </code></pre> <p>(this is for an internal install, thus cywin is installed, and all paths, scripts are known)</p>
[ { "answer_id": 254370, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "<p>I think you're going to need to make the whole thing part of a <code>cmd.exe</code> invocation, and then I'm not sure it will do exactly what you want/need.</p>\n\n<p>I'm looking at Inno-Setup 5 documentation (may be out-of-date), but I don't think you need the <code>shellexec</code> or <code>waituntilterminated</code> flags.</p>\n\n<p>Try something like</p>\n\n<pre><code>Filename: \"cmd.exe\"; Parameters: \"/c c:\\cygwin\\bin\\bash -c 'c:/scripts/step1.sh paramx'\"\n</code></pre>\n\n<p>Untested, caveat emptor.</p>\n" }, { "answer_id": 14785573, "author": "Joshua Clayton", "author_id": 1419731, "author_profile": "https://Stackoverflow.com/users/1419731", "pm_score": 3, "selected": false, "text": "<p>Your problem is that <code>-c</code> tells bash to read instructions from the next parameter:\ne.g.</p>\n\n<pre><code>c:\\cygwin\\bin\\bash.exe -c 'for NUM in 1 2 3 4 5 6 7 8 9 10; do echo $NUM; done'\n</code></pre>\n\n<p>you just need:</p>\n\n<pre><code>c:\\cygwin\\bin\\bash.exe \"/scripts/step1.sh paramX\"\n</code></pre>\n\n<p>So your code would look like:</p>\n\n<pre><code>Filename: \"c:\\cygwin\\bin\\bash.exe\";\n Parameters: \"c:/scripts/step1.sh paramX\";\n Flags: shellexec waituntilterminated;\n StatusMsg: \"Running the script...\"\n</code></pre>\n\n<p>Maybe this will be helpful for somebody else :)</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6144/" ]
I've tried variations of this, but had no luck other than the ability to start a cygwin window. (wrapped on **;** for clarity) ``` Filename: "c:\cygwin\bin\bash.exe"; Parameters: "-c c:/scripts/step1.sh paramX"; Flags: shellexec waituntilterminated; StatusMsg: "Running the script..." ``` (this is for an internal install, thus cywin is installed, and all paths, scripts are known)
Your problem is that `-c` tells bash to read instructions from the next parameter: e.g. ``` c:\cygwin\bin\bash.exe -c 'for NUM in 1 2 3 4 5 6 7 8 9 10; do echo $NUM; done' ``` you just need: ``` c:\cygwin\bin\bash.exe "/scripts/step1.sh paramX" ``` So your code would look like: ``` Filename: "c:\cygwin\bin\bash.exe"; Parameters: "c:/scripts/step1.sh paramX"; Flags: shellexec waituntilterminated; StatusMsg: "Running the script..." ``` Maybe this will be helpful for somebody else :)
254,345
<p>I previously asked how to do this in Groovy. However, now I'm rewriting my app in Perl because of all the CPAN libraries.</p> <p>If the page contained these links:</p> <pre> &lt;a href="http://www.google.com"&gt;Google&lt;/a&gt; &lt;a href="http://www.apple.com"&gt;Apple&lt;/a&gt; </pre> <p>The output would be:</p> <pre> Google, http://www.google.com Apple, http://www.apple.com </pre> <p>What is the best way to do this in Perl?</p>
[ { "answer_id": 254381, "author": "Sherm Pendley", "author_id": 27631, "author_profile": "https://Stackoverflow.com/users/27631", "pm_score": 4, "selected": false, "text": "<p>Have a look at <a href=\"http://search.cpan.org/perldoc?HTML::LinkExtractor\" rel=\"nofollow noreferrer\">HTML::LinkExtractor</a> and <a href=\"http://search.cpan.org/perldoc?HTML::LinkExtor\" rel=\"nofollow noreferrer\">HTML::LinkExtor</a>, part of the <a href=\"http://search.cpan.org/dist/HTML-Parser/\" rel=\"nofollow noreferrer\">HTML::Parser</a> package.</p>\n\n<p>HTML::LinkExtractor is similar to HTML::LinkExtor, except that besides getting the URL, you also get the link-text.</p>\n" }, { "answer_id": 254505, "author": "converter42", "author_id": 28974, "author_profile": "https://Stackoverflow.com/users/28974", "pm_score": 2, "selected": false, "text": "<p>HTML is a structured markup language that has to be parsed to extract its meaning without errors. The module Sherm listed will parse the HTML and extract the links for you. Ad hoc regular expression-based solutions might be acceptable if you know that your inputs will always be formed the same way (don't forget attributes), but a parser is almost always the right answer for processing structured text.</p>\n" }, { "answer_id": 254506, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 3, "selected": false, "text": "<p>I like using <a href=\"http://search.cpan.org/dist/pQuery/lib/pQuery.pm\" rel=\"nofollow noreferrer\">pQuery</a> for things like this...</p>\n\n<pre><code>use pQuery;\n\npQuery( 'http://www.perlbuzz.com' )-&gt;find( 'a' )-&gt;each(\n sub {\n say $_-&gt;innerHTML . q{, } . $_-&gt;getAttribute( 'href' );\n }\n);\n</code></pre>\n\n<p>Also checkout this previous stackoverflow.com question <a href=\"https://stackoverflow.com/questions/160889/emulation-of-lex-like-functionality-in-perl-or-python#161977\">Emulation of lex like functionality in Perl or Python</a> for similar answers.</p>\n" }, { "answer_id": 254687, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 6, "selected": true, "text": "<p>Please look at using the <a href=\"http://search.cpan.org/dist/WWW-Mechanize/\" rel=\"noreferrer\">WWW::Mechanize</a> module for this. It will fetch your web pages for you, and then give you easy-to-work with lists of URLs.</p>\n\n<pre><code>my $mech = WWW::Mechanize-&gt;new();\n$mech-&gt;get( $some_url );\nmy @links = $mech-&gt;links();\nfor my $link ( @links ) {\n printf \"%s, %s\\n\", $link-&gt;text, $link-&gt;url;\n}\n</code></pre>\n\n<p>Pretty simple, and if you're looking to navigate to other URLs on that page, it's even simpler.</p>\n\n<p>Mech is basically a browser in an object.</p>\n" }, { "answer_id": 254708, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/254345/how-can-i-extract-urls-from-a-web-page-in-perl#254381\">Sherm</a> recommended <a href=\"http://search.cpan.org/perldoc?HTML::LinkExtor\" rel=\"nofollow noreferrer\">HTML::LinkExtor</a>, which is almost what you want. Unfortunately, it can't return the text inside the &lt;a> tag.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/254345/how-can-i-extract-urls-from-a-web-page-in-perl#254687\">Andy</a> recommended <a href=\"http://search.cpan.org/perldoc?WWW::Mechanize\" rel=\"nofollow noreferrer\">WWW::Mechanize</a>. That's probably the best solution.</p>\n\n<p>If you find that WWW::Mechanize isn't to your liking, try <a href=\"http://search.cpan.org/dist/HTML-Tree/\" rel=\"nofollow noreferrer\">HTML::TreeBuilder</a>. It will build a DOM-like tree out of the HTML, which you can then search for the links you want and extract any nearby content you want.</p>\n" }, { "answer_id": 256433, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "<p>Or consider enhancing HTML::LinkExtor to do what you want, and submitting the changes to the author.</p>\n" }, { "answer_id": 266022, "author": "Alexandr Ciornii", "author_id": 13467, "author_profile": "https://Stackoverflow.com/users/13467", "pm_score": 3, "selected": false, "text": "<p>Another way to do this is to use XPath to query parsed HTML. It is needed in complex cases, like extract all links in div with specific class. Use HTML::TreeBuilder::XPath for this.</p>\n\n<pre><code> my $tree=HTML::TreeBuilder::XPath-&gt;new_from_content($c);\n my $nodes=$tree-&gt;findnodes(q{//map[@name='map1']/area});\n while (my $node=$nodes-&gt;shift) {\n my $t=$node-&gt;attr('title');\n }\n</code></pre>\n" }, { "answer_id": 5398997, "author": "Ashley", "author_id": 109483, "author_profile": "https://Stackoverflow.com/users/109483", "pm_score": 2, "selected": false, "text": "<p>Previous answers were perfectly good and I know I’m late to the party but this got bumped in the [perl] feed so…</p>\n\n<p><a href=\"http://search.cpan.org/perldoc?XML%3a%3aLibXML\" rel=\"nofollow\">XML::LibXML</a> is excellent for HTML parsing and unbeatable for speed. Set <code>recover</code> option when parsing badly formed HTML.</p>\n\n<pre><code>use XML::LibXML;\n\nmy $doc = XML::LibXML-&gt;load_html(IO =&gt; \\*DATA);\nfor my $anchor ( $doc-&gt;findnodes(\"//a[\\@href]\") )\n{\n printf \"%15s -&gt; %s\\n\",\n $anchor-&gt;textContent,\n $anchor-&gt;getAttribute(\"href\");\n}\n\n__DATA__\n&lt;html&gt;&lt;head&gt;&lt;title/&gt;&lt;/head&gt;&lt;body&gt;\n&lt;a href=\"http://www.google.com\"&gt;Google&lt;/a&gt;\n&lt;a href=\"http://www.apple.com\"&gt;Apple&lt;/a&gt;\n&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n\n<p>–yields–</p>\n\n<pre><code> Google -&gt; http://www.google.com\n Apple -&gt; http://www.apple.com\n</code></pre>\n" }, { "answer_id": 10888037, "author": "Aaron Graves", "author_id": 1435982, "author_profile": "https://Stackoverflow.com/users/1435982", "pm_score": 3, "selected": false, "text": "<p>If you're adventurous and want to try without modules, something like this should work (adapt it to your needs):</p>\n\n<pre><code>#!/usr/bin/perl\n\nif($#ARGV &lt; 0) {\n print \"$0: Need URL argument.\\n\";\n exit 1;\n}\n\nmy @content = split(/\\n/,`wget -qO- $ARGV[0]`);\nmy @links = grep(/&lt;a.*href=.*&gt;/,@content);\n\nforeach my $c (@links){\n $c =~ /&lt;a.*href=\"([\\s\\S]+?)\".*&gt;/;\n $link = $1;\n $c =~ /&lt;a.*href.*&gt;([\\s\\S]+?)&lt;\\/a&gt;/;\n $title = $1;\n print \"$title, $link\\n\";\n}\n</code></pre>\n\n<p>There's likely a few things I did wrong here, but it works in a handful of test cases I tried after writing it (it doesn't account for things like &lt;img&gt; tags, etc).</p>\n" }, { "answer_id": 14579702, "author": "Deiveegaraja Andaver", "author_id": 944073, "author_profile": "https://Stackoverflow.com/users/944073", "pm_score": -1, "selected": false, "text": "<p>We can use regular expression to extract the link with its link text. This is also the one way.</p>\n\n<pre><code>local $/ = '';\nmy $a = &lt;DATA&gt;;\n\nwhile( $a =~ m/&lt;a[^&gt;]*?href=\\\"([^&gt;]*?)\\\"[^&gt;]*?&gt;\\s*([\\w\\W]*?)\\s*&lt;\\/a&gt;/igs )\n{ \n print \"Link:$1 \\t Text: $2\\n\";\n}\n\n\n__DATA__\n\n&lt;a href=\"http://www.google.com\"&gt;Google&lt;/a&gt;\n\n&lt;a href=\"http://www.apple.com\"&gt;Apple&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 18786147, "author": "user13107", "author_id": 1729501, "author_profile": "https://Stackoverflow.com/users/1729501", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://search.cpan.org/~podmaster/HTML-LinkExtractor-0.13/LinkExtractor.pm\" rel=\"nofollow\">HTML::LinkExtractor</a> is better than HTML::LinkExtor</p>\n\n<p>It can give both link text and URL.</p>\n\n<p>Usage:</p>\n\n<pre><code> use HTML::LinkExtractor;\n my $input = q{If &lt;a href=\"http://apple.com/\"&gt; Apple &lt;/a&gt;}; #HTML string\n my $LX = new HTML::LinkExtractor(undef,undef,1);\n $LX-&gt;parse(\\$input);\n for my $Link( @{ $LX-&gt;links } ) {\n if( $$Link{_TEXT}=~ m/Apple/ ) {\n print \"\\n LinkText $$Link{_TEXT} URL $$Link{href}\\n\";\n }\n }\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I previously asked how to do this in Groovy. However, now I'm rewriting my app in Perl because of all the CPAN libraries. If the page contained these links: ``` <a href="http://www.google.com">Google</a> <a href="http://www.apple.com">Apple</a> ``` The output would be: ``` Google, http://www.google.com Apple, http://www.apple.com ``` What is the best way to do this in Perl?
Please look at using the [WWW::Mechanize](http://search.cpan.org/dist/WWW-Mechanize/) module for this. It will fetch your web pages for you, and then give you easy-to-work with lists of URLs. ``` my $mech = WWW::Mechanize->new(); $mech->get( $some_url ); my @links = $mech->links(); for my $link ( @links ) { printf "%s, %s\n", $link->text, $link->url; } ``` Pretty simple, and if you're looking to navigate to other URLs on that page, it's even simpler. Mech is basically a browser in an object.
254,347
<p>We currently have developed an application using WCF. Our clients make connections to different WCF servicehosts located on the server, and the servicehosts return the data from the DB that the clients need. Standard model. However, this current design has all of our WCF data in app.config files both on the client side as well as the servicehost side. We want to make this more dynamic, and have moved all of the data, including the endpoints, the contracts, and the bindings, into the DB.</p> <p>Now the question is how do we retrieve this data, and access it properly. We've got the design working where we have one defined endpoint in a config file, and using that endpoint, we can make a call to it to get the rest of the endpoint information that we need (i.e. all of the bindings, contracts and different endpoints that it used to have defined in its app.config). This is the case on both the client side as well as the servicehost side.</p> <p>The issue that I'm now struggling with is how do I code against these dynamic endpoints? When the client makes a call to the servicehost, it not only is making simple calls to the servicehost, but retrieving and passing back objects for the servicehost to process as needed. For example, on form load we may retrieve the object with all of the currently defined settings from the DB, and then the user does whatever on the fornm, and we then pass back the updated object to the servicehost. We can do that now because in Visual Studio 2008 we've added all of the service references, which has auto-generated the methods and objects that can be called and retrieved from the servicehosts. If we go to a dynamic endpoint connection, how do we get this data during the development phase?</p> <p>I've developed a similar application in the past in .NET 2.0 using .NET remoting, where we were passing the object back and forth, and the client and server both used the same object definition class to know about the object. I'm not sure how we would go about doing this with WCF.</p>
[ { "answer_id": 254381, "author": "Sherm Pendley", "author_id": 27631, "author_profile": "https://Stackoverflow.com/users/27631", "pm_score": 4, "selected": false, "text": "<p>Have a look at <a href=\"http://search.cpan.org/perldoc?HTML::LinkExtractor\" rel=\"nofollow noreferrer\">HTML::LinkExtractor</a> and <a href=\"http://search.cpan.org/perldoc?HTML::LinkExtor\" rel=\"nofollow noreferrer\">HTML::LinkExtor</a>, part of the <a href=\"http://search.cpan.org/dist/HTML-Parser/\" rel=\"nofollow noreferrer\">HTML::Parser</a> package.</p>\n\n<p>HTML::LinkExtractor is similar to HTML::LinkExtor, except that besides getting the URL, you also get the link-text.</p>\n" }, { "answer_id": 254505, "author": "converter42", "author_id": 28974, "author_profile": "https://Stackoverflow.com/users/28974", "pm_score": 2, "selected": false, "text": "<p>HTML is a structured markup language that has to be parsed to extract its meaning without errors. The module Sherm listed will parse the HTML and extract the links for you. Ad hoc regular expression-based solutions might be acceptable if you know that your inputs will always be formed the same way (don't forget attributes), but a parser is almost always the right answer for processing structured text.</p>\n" }, { "answer_id": 254506, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 3, "selected": false, "text": "<p>I like using <a href=\"http://search.cpan.org/dist/pQuery/lib/pQuery.pm\" rel=\"nofollow noreferrer\">pQuery</a> for things like this...</p>\n\n<pre><code>use pQuery;\n\npQuery( 'http://www.perlbuzz.com' )-&gt;find( 'a' )-&gt;each(\n sub {\n say $_-&gt;innerHTML . q{, } . $_-&gt;getAttribute( 'href' );\n }\n);\n</code></pre>\n\n<p>Also checkout this previous stackoverflow.com question <a href=\"https://stackoverflow.com/questions/160889/emulation-of-lex-like-functionality-in-perl-or-python#161977\">Emulation of lex like functionality in Perl or Python</a> for similar answers.</p>\n" }, { "answer_id": 254687, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 6, "selected": true, "text": "<p>Please look at using the <a href=\"http://search.cpan.org/dist/WWW-Mechanize/\" rel=\"noreferrer\">WWW::Mechanize</a> module for this. It will fetch your web pages for you, and then give you easy-to-work with lists of URLs.</p>\n\n<pre><code>my $mech = WWW::Mechanize-&gt;new();\n$mech-&gt;get( $some_url );\nmy @links = $mech-&gt;links();\nfor my $link ( @links ) {\n printf \"%s, %s\\n\", $link-&gt;text, $link-&gt;url;\n}\n</code></pre>\n\n<p>Pretty simple, and if you're looking to navigate to other URLs on that page, it's even simpler.</p>\n\n<p>Mech is basically a browser in an object.</p>\n" }, { "answer_id": 254708, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/254345/how-can-i-extract-urls-from-a-web-page-in-perl#254381\">Sherm</a> recommended <a href=\"http://search.cpan.org/perldoc?HTML::LinkExtor\" rel=\"nofollow noreferrer\">HTML::LinkExtor</a>, which is almost what you want. Unfortunately, it can't return the text inside the &lt;a> tag.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/254345/how-can-i-extract-urls-from-a-web-page-in-perl#254687\">Andy</a> recommended <a href=\"http://search.cpan.org/perldoc?WWW::Mechanize\" rel=\"nofollow noreferrer\">WWW::Mechanize</a>. That's probably the best solution.</p>\n\n<p>If you find that WWW::Mechanize isn't to your liking, try <a href=\"http://search.cpan.org/dist/HTML-Tree/\" rel=\"nofollow noreferrer\">HTML::TreeBuilder</a>. It will build a DOM-like tree out of the HTML, which you can then search for the links you want and extract any nearby content you want.</p>\n" }, { "answer_id": 256433, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "<p>Or consider enhancing HTML::LinkExtor to do what you want, and submitting the changes to the author.</p>\n" }, { "answer_id": 266022, "author": "Alexandr Ciornii", "author_id": 13467, "author_profile": "https://Stackoverflow.com/users/13467", "pm_score": 3, "selected": false, "text": "<p>Another way to do this is to use XPath to query parsed HTML. It is needed in complex cases, like extract all links in div with specific class. Use HTML::TreeBuilder::XPath for this.</p>\n\n<pre><code> my $tree=HTML::TreeBuilder::XPath-&gt;new_from_content($c);\n my $nodes=$tree-&gt;findnodes(q{//map[@name='map1']/area});\n while (my $node=$nodes-&gt;shift) {\n my $t=$node-&gt;attr('title');\n }\n</code></pre>\n" }, { "answer_id": 5398997, "author": "Ashley", "author_id": 109483, "author_profile": "https://Stackoverflow.com/users/109483", "pm_score": 2, "selected": false, "text": "<p>Previous answers were perfectly good and I know I’m late to the party but this got bumped in the [perl] feed so…</p>\n\n<p><a href=\"http://search.cpan.org/perldoc?XML%3a%3aLibXML\" rel=\"nofollow\">XML::LibXML</a> is excellent for HTML parsing and unbeatable for speed. Set <code>recover</code> option when parsing badly formed HTML.</p>\n\n<pre><code>use XML::LibXML;\n\nmy $doc = XML::LibXML-&gt;load_html(IO =&gt; \\*DATA);\nfor my $anchor ( $doc-&gt;findnodes(\"//a[\\@href]\") )\n{\n printf \"%15s -&gt; %s\\n\",\n $anchor-&gt;textContent,\n $anchor-&gt;getAttribute(\"href\");\n}\n\n__DATA__\n&lt;html&gt;&lt;head&gt;&lt;title/&gt;&lt;/head&gt;&lt;body&gt;\n&lt;a href=\"http://www.google.com\"&gt;Google&lt;/a&gt;\n&lt;a href=\"http://www.apple.com\"&gt;Apple&lt;/a&gt;\n&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n\n<p>–yields–</p>\n\n<pre><code> Google -&gt; http://www.google.com\n Apple -&gt; http://www.apple.com\n</code></pre>\n" }, { "answer_id": 10888037, "author": "Aaron Graves", "author_id": 1435982, "author_profile": "https://Stackoverflow.com/users/1435982", "pm_score": 3, "selected": false, "text": "<p>If you're adventurous and want to try without modules, something like this should work (adapt it to your needs):</p>\n\n<pre><code>#!/usr/bin/perl\n\nif($#ARGV &lt; 0) {\n print \"$0: Need URL argument.\\n\";\n exit 1;\n}\n\nmy @content = split(/\\n/,`wget -qO- $ARGV[0]`);\nmy @links = grep(/&lt;a.*href=.*&gt;/,@content);\n\nforeach my $c (@links){\n $c =~ /&lt;a.*href=\"([\\s\\S]+?)\".*&gt;/;\n $link = $1;\n $c =~ /&lt;a.*href.*&gt;([\\s\\S]+?)&lt;\\/a&gt;/;\n $title = $1;\n print \"$title, $link\\n\";\n}\n</code></pre>\n\n<p>There's likely a few things I did wrong here, but it works in a handful of test cases I tried after writing it (it doesn't account for things like &lt;img&gt; tags, etc).</p>\n" }, { "answer_id": 14579702, "author": "Deiveegaraja Andaver", "author_id": 944073, "author_profile": "https://Stackoverflow.com/users/944073", "pm_score": -1, "selected": false, "text": "<p>We can use regular expression to extract the link with its link text. This is also the one way.</p>\n\n<pre><code>local $/ = '';\nmy $a = &lt;DATA&gt;;\n\nwhile( $a =~ m/&lt;a[^&gt;]*?href=\\\"([^&gt;]*?)\\\"[^&gt;]*?&gt;\\s*([\\w\\W]*?)\\s*&lt;\\/a&gt;/igs )\n{ \n print \"Link:$1 \\t Text: $2\\n\";\n}\n\n\n__DATA__\n\n&lt;a href=\"http://www.google.com\"&gt;Google&lt;/a&gt;\n\n&lt;a href=\"http://www.apple.com\"&gt;Apple&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 18786147, "author": "user13107", "author_id": 1729501, "author_profile": "https://Stackoverflow.com/users/1729501", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://search.cpan.org/~podmaster/HTML-LinkExtractor-0.13/LinkExtractor.pm\" rel=\"nofollow\">HTML::LinkExtractor</a> is better than HTML::LinkExtor</p>\n\n<p>It can give both link text and URL.</p>\n\n<p>Usage:</p>\n\n<pre><code> use HTML::LinkExtractor;\n my $input = q{If &lt;a href=\"http://apple.com/\"&gt; Apple &lt;/a&gt;}; #HTML string\n my $LX = new HTML::LinkExtractor(undef,undef,1);\n $LX-&gt;parse(\\$input);\n for my $Link( @{ $LX-&gt;links } ) {\n if( $$Link{_TEXT}=~ m/Apple/ ) {\n print \"\\n LinkText $$Link{_TEXT} URL $$Link{href}\\n\";\n }\n }\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539/" ]
We currently have developed an application using WCF. Our clients make connections to different WCF servicehosts located on the server, and the servicehosts return the data from the DB that the clients need. Standard model. However, this current design has all of our WCF data in app.config files both on the client side as well as the servicehost side. We want to make this more dynamic, and have moved all of the data, including the endpoints, the contracts, and the bindings, into the DB. Now the question is how do we retrieve this data, and access it properly. We've got the design working where we have one defined endpoint in a config file, and using that endpoint, we can make a call to it to get the rest of the endpoint information that we need (i.e. all of the bindings, contracts and different endpoints that it used to have defined in its app.config). This is the case on both the client side as well as the servicehost side. The issue that I'm now struggling with is how do I code against these dynamic endpoints? When the client makes a call to the servicehost, it not only is making simple calls to the servicehost, but retrieving and passing back objects for the servicehost to process as needed. For example, on form load we may retrieve the object with all of the currently defined settings from the DB, and then the user does whatever on the fornm, and we then pass back the updated object to the servicehost. We can do that now because in Visual Studio 2008 we've added all of the service references, which has auto-generated the methods and objects that can be called and retrieved from the servicehosts. If we go to a dynamic endpoint connection, how do we get this data during the development phase? I've developed a similar application in the past in .NET 2.0 using .NET remoting, where we were passing the object back and forth, and the client and server both used the same object definition class to know about the object. I'm not sure how we would go about doing this with WCF.
Please look at using the [WWW::Mechanize](http://search.cpan.org/dist/WWW-Mechanize/) module for this. It will fetch your web pages for you, and then give you easy-to-work with lists of URLs. ``` my $mech = WWW::Mechanize->new(); $mech->get( $some_url ); my @links = $mech->links(); for my $link ( @links ) { printf "%s, %s\n", $link->text, $link->url; } ``` Pretty simple, and if you're looking to navigate to other URLs on that page, it's even simpler. Mech is basically a browser in an object.
254,349
<p>I have a page with some dynamically added buttons. If you click a button before the page has fully loaded, it throws the classic exception:</p> <blockquote> <pre><code>Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For </code></pre> <p>security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.</p> </blockquote> <p>I am guessing the Viewstate field hasn't loaded on the form yet, the the other bits are being submitted. What's the best way to prevent this error, while maintaining Event Validation?</p>
[ { "answer_id": 254387, "author": "Handruin", "author_id": 26173, "author_profile": "https://Stackoverflow.com/users/26173", "pm_score": 0, "selected": false, "text": "<p>What if you set those button's visible property to false by default and at the end of the page load or event validation you set their visible property to true? This way restricting them from clicking the button until the page has fully loaded.</p>\n" }, { "answer_id": 254561, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>From what I can tell the ViewState is loaded right after the form tag on the page.</p>\n\n<p>Have you tried using <code>ClientScriptManager.RegisterForEventValidation( button.UniqueID )</code> for each button after you add the button to the page? Depending on where you add the button, the event hookup for the page may have already happened and thus the events generated by the button may not be registered with the page.</p>\n" }, { "answer_id": 254677, "author": "Jeffrey Harrington", "author_id": 4307, "author_profile": "https://Stackoverflow.com/users/4307", "pm_score": 3, "selected": true, "text": "<p>I answered a similar question <a href=\"https://stackoverflow.com/questions/140303/aspnet-unable-to-validate-data#254581\">here</a>. To quote:</p>\n\n<p>Essentially, you'll want to get the ViewState to load at the top of the page. In .NET 3.5 SP1 the <em>RenderAllHiddenFieldsAtTopOfForm</em> property was added to the PagesSection configuration. </p>\n\n<p><strong>Web.config</strong></p>\n\n<pre><code>&lt;configuration&gt;\n\n &lt;system.web&gt;\n\n &lt;pages renderAllHiddenFieldsAtTopOfForm=\"true\"&gt;&lt;/pages&gt;\n\n &lt;/system.web&gt;\n\n&lt;/configuration&gt;\n</code></pre>\n\n<p>Interestingly, the default value of this is true. So, in essence, if you are using .NET 3.5 SP1 then the ViewState is automatically being rendered at the top of the form (before the rest of the page is loaded) thus eliminating the ViewState error you are getting.</p>\n" }, { "answer_id": 260772, "author": "Andy C.", "author_id": 28541, "author_profile": "https://Stackoverflow.com/users/28541", "pm_score": 2, "selected": false, "text": "<p>I've found this to be caused more often by the <code>__EVENTVALIDATION</code> field than the ViewState not being loaded. The <code>__EVENTVALIDATION</code> is at the bottom of the page and if it hasn't been received by the client when the user causes a postback you will get that exception.</p>\n\n<p>I've not yet found a great solution, but what I usually do on pages that tend to cause this due to large amounts of content is to wire up the buttons to a javascript function that checks an isLoaded var that only gets set to true in the document.ready call. If isLoaded is false it silently eats the event, if it's true it lets if go through. This is a pain to set up, but it has ended most of my invalid postback issues.</p>\n" }, { "answer_id": 36751816, "author": "Bolo", "author_id": 4241466, "author_profile": "https://Stackoverflow.com/users/4241466", "pm_score": 0, "selected": false, "text": "<p>I spent quite a long time trying to figure out why the __EVENTVALIDATION tag renders at the bottom on a particular site but towards the top on every other website. I eventually figured out it was because of code in the Render override event. That, along with a lean viewstate mostly got rid of this error but just for good measure I added the logic below on the button that was causing the error:</p>\n\n<p><strong>javascript somewhere on the page</strong></p>\n\n<pre><code>function CheckForHiddenFields()\n{\n var EventValidation = document.getElementById('__EVENTVALIDATION');\n if (EventValidation &amp;&amp; EventValidation.value &amp;&amp; EventValidation.value != '')\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n\n<p><strong>Add attribute to asp:Button:</strong></p>\n\n<pre><code>OnClientClick=\"return CheckForHiddenFields();\"\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
I have a page with some dynamically added buttons. If you click a button before the page has fully loaded, it throws the classic exception: > > > ``` > Invalid postback or callback argument. > Event validation is enabled using in configuration or in a page. For > > ``` > > security purposes, > this feature verifies that arguments to postback or callback > events originate from the > server control that originally rendered them. If the data is valid > and expected, use > the ClientScriptManager.RegisterForEventValidation > method in order to register the > postback or callback data for validation. > > > I am guessing the Viewstate field hasn't loaded on the form yet, the the other bits are being submitted. What's the best way to prevent this error, while maintaining Event Validation?
I answered a similar question [here](https://stackoverflow.com/questions/140303/aspnet-unable-to-validate-data#254581). To quote: Essentially, you'll want to get the ViewState to load at the top of the page. In .NET 3.5 SP1 the *RenderAllHiddenFieldsAtTopOfForm* property was added to the PagesSection configuration. **Web.config** ``` <configuration> <system.web> <pages renderAllHiddenFieldsAtTopOfForm="true"></pages> </system.web> </configuration> ``` Interestingly, the default value of this is true. So, in essence, if you are using .NET 3.5 SP1 then the ViewState is automatically being rendered at the top of the form (before the rest of the page is loaded) thus eliminating the ViewState error you are getting.
254,350
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
[ { "answer_id": 254357, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 8, "selected": true, "text": "<p>The low level way:</p>\n\n<pre><code>from __future__ import with_statement\nwith open(filename1) as f1:\n with open(filename2) as f2:\n if f1.read() == f2.read():\n ...\n</code></pre>\n\n<p>The high level way:</p>\n\n<pre><code>import filecmp\nif filecmp.cmp(filename1, filename2, shallow=False):\n ...\n</code></pre>\n" }, { "answer_id": 254362, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 2, "selected": false, "text": "<pre>\n<code>\nf = open(filename1, \"r\").read()\nf2 = open(filename2,\"r\").read()\nprint f == f2\n\n</code>\n</pre>\n" }, { "answer_id": 254373, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": 5, "selected": false, "text": "<p>If you're going for even basic efficiency, you probably want to check the file size first:</p>\n\n<pre><code>if os.path.getsize(filename1) == os.path.getsize(filename2):\n if open('filename1','r').read() == open('filename2','r').read():\n # Files are the same.\n</code></pre>\n\n<p>This saves you reading every line of two files that aren't even the same size, and thus can't be the same.</p>\n\n<p>(Even further than that, you could call out to a fast MD5sum of each file and compare those, but that's not \"in Python\", so I'll stop here.)</p>\n" }, { "answer_id": 254374, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 1, "selected": false, "text": "<p>For larger files you could compute a <a href=\"http://docs.python.org/library/md5.html\" rel=\"nofollow noreferrer\">MD5</a> or <a href=\"http://docs.python.org/library/sha.html\" rel=\"nofollow noreferrer\">SHA</a> hash of the files.</p>\n" }, { "answer_id": 254518, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 2, "selected": false, "text": "<p>I would use a hash of the file's contents using MD5.</p>\n\n<pre><code>import hashlib\n\ndef checksum(f):\n md5 = hashlib.md5()\n md5.update(open(f).read())\n return md5.hexdigest()\n\ndef is_contents_same(f1, f2):\n return checksum(f1) == checksum(f2)\n\nif not is_contents_same('foo.txt', 'bar.txt'):\n print 'The contents are not the same!'\n</code></pre>\n" }, { "answer_id": 254567, "author": "user32141", "author_id": 32141, "author_profile": "https://Stackoverflow.com/users/32141", "pm_score": 3, "selected": false, "text": "<p>Since I can't comment on the answers of others I'll write my own.</p>\n\n<p>If you use md5 you definitely must not just md5.update(f.read()) since you'll use too much memory.</p>\n\n<pre><code>def get_file_md5(f, chunk_size=8192):\n h = hashlib.md5()\n while True:\n chunk = f.read(chunk_size)\n if not chunk:\n break\n h.update(chunk)\n return h.hexdigest()\n</code></pre>\n" }, { "answer_id": 255210, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": false, "text": "<p>This is a functional-style file comparison function. It returns instantly False if the files have different sizes; otherwise, it reads in 4KiB block sizes and returns False instantly upon the first difference:</p>\n<pre><code>from __future__ import with_statement\nimport os\nimport itertools, functools, operator\ntry:\n izip= itertools.izip # Python 2\nexcept AttributeError:\n izip= zip # Python 3\n\ndef filecmp(filename1, filename2):\n &quot;Do the two files have exactly the same contents?&quot;\n with open(filename1, &quot;rb&quot;) as fp1, open(filename2, &quot;rb&quot;) as fp2:\n if os.fstat(fp1.fileno()).st_size != os.fstat(fp2.fileno()).st_size:\n return False # different sizes ∴ not equal\n\n # set up one 4k-reader for each file\n fp1_reader= functools.partial(fp1.read, 4096)\n fp2_reader= functools.partial(fp2.read, 4096)\n\n # pair each 4k-chunk from the two readers while they do not return '' (EOF)\n cmp_pairs= izip(iter(fp1_reader, b''), iter(fp2_reader, b''))\n\n # return True for all pairs that are not equal\n inequalities= itertools.starmap(operator.ne, cmp_pairs)\n\n # voilà; any() stops at first True value\n return not any(inequalities)\n\nif __name__ == &quot;__main__&quot;:\n import sys\n print filecmp(sys.argv[1], sys.argv[2])\n</code></pre>\n<p>Just a different take :)</p>\n" }, { "answer_id": 41169735, "author": "Prashanth Babu", "author_id": 7303225, "author_profile": "https://Stackoverflow.com/users/7303225", "pm_score": 1, "selected": false, "text": "<pre><code>from __future__ import with_statement\n\nfilename1 = \"G:\\\\test1.TXT\"\n\nfilename2 = \"G:\\\\test2.TXT\"\n\n\nwith open(filename1) as f1:\n\n with open(filename2) as f2:\n\n file1list = f1.read().splitlines()\n\n file2list = f2.read().splitlines()\n\n list1length = len(file1list)\n\n list2length = len(file2list)\n\n if list1length == list2length:\n\n for index in range(len(file1list)):\n\n if file1list[index] == file2list[index]:\n\n print file1list[index] + \"==\" + file2list[index]\n\n else: \n\n print file1list[index] + \"!=\" + file2list[index]+\" Not-Equel\"\n\n else:\n\n print \"difference inthe size of the file and number of lines\"\n</code></pre>\n" }, { "answer_id": 68601548, "author": "Angel", "author_id": 12234006, "author_profile": "https://Stackoverflow.com/users/12234006", "pm_score": 0, "selected": false, "text": "<h1>Simple and efficient solution:</h1>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\n\ndef is_file_content_equal(\n file_path_1: str, file_path_2: str, buffer_size: int = 1024 * 8\n) -&gt; bool:\n &quot;&quot;&quot;Checks if two files content is equal\n Arguments:\n file_path_1 (str): Path to the first file\n file_path_2 (str): Path to the second file\n buffer_size (int): Size of the buffer to read the file\n Returns:\n bool that indicates if the file contents are equal\n Example:\n &gt;&gt;&gt; is_file_content_equal(&quot;filecomp.py&quot;, &quot;filecomp copy.py&quot;)\n True\n &gt;&gt;&gt; is_file_content_equal(&quot;filecomp.py&quot;, &quot;diagram.dio&quot;)\n False\n &quot;&quot;&quot;\n # First check sizes\n s1, s2 = os.path.getsize(file_path_1), os.path.getsize(file_path_2)\n if s1 != s2:\n return False\n # If the sizes are the same check the content\n with open(file_path_1, &quot;rb&quot;) as fp1, open(file_path_2, &quot;rb&quot;) as fp2:\n while True:\n b1 = fp1.read(buffer_size)\n b2 = fp2.read(buffer_size)\n if b1 != b2:\n return False\n # if the content is the same and they are both empty bytes\n # the file is the same\n if not b1:\n return True\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
I don't care what the differences are. I just want to know whether the contents are different.
The low level way: ``` from __future__ import with_statement with open(filename1) as f1: with open(filename2) as f2: if f1.read() == f2.read(): ... ``` The high level way: ``` import filecmp if filecmp.cmp(filename1, filename2, shallow=False): ... ```
254,351
<p>I wanted to make Map of Collections in Java, so I can make something like </p> <pre><code>public void add(K key, V value) { if (containsKey(key)) { get(key).add(value); } else { Collection c = new Collection(); c.add(value); put(key, value); } } </code></pre> <p>I've tried to make it with something like </p> <pre><code>public class CollectionMap&lt;K, C extends Collection&lt;V&gt;&gt; extends HashMap&lt;K, C&gt; </code></pre> <p>but compiler complains about the <code>&lt;V&gt;</code> part, and there would still be an issue of making proper new collection. </p> <p>At the moment, I've made two classes: SetMap that look like this </p> <pre><code> 1: public class SetMap&lt;K, V&gt; extends HashMap&lt;K, Set&lt;V&gt;&gt; { 2: 3: public void add(K key, V value) { 4: if (containsKey(key)) { 5: get(key).add(value); 6: } else { 7: Set&lt;V&gt; list = new HashSet&lt;V&gt;(); 8: list.add(value); 9: put(key, list); 10: } 11: } 12: 13: } </code></pre> <p>and ListMap looks pretty much the same except the line 7 where I make new ArrayList. This sort of duplication is small enough to be tolerable, but question remains is this sort of "nested generics" possible in Java? </p> <p>EDIT:</p> <p>As <a href="https://stackoverflow.com/questions/254351/map-of-collections#254372">erickson said</a>, solution is in <code>&lt;A, B extends Something&lt;A&gt;&gt;</code> rather than just <code>&lt;B extends Something&lt;A&gt;&gt;</code></p> <p>so code can look something like </p> <pre><code>public abstract class CollelctionMap&lt;K, V, C extends Collection&lt;V&gt;&gt; extends HashMap&lt;K, C&gt; { protected abstract C newCollection(); public void add(K key, V value) { if (containsKey(key)) { get(key).add(value); } else { C c = newCollection(); c.add(value); put(key, c); } } } </code></pre> <p>and ListMap and SetMap only provide proper collection </p>
[ { "answer_id": 254372, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": true, "text": "<p>If <code>map</code> is a <code>Map&lt;K, Collection&lt;V&gt;&gt;</code>, use the idiom <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-\" rel=\"noreferrer\"><code>computeIfAbsent(...).add(...)</code>,</a> like this:</p>\n\n<pre><code>map.computeIfAbsent(key, k -&gt; new ArrayList&lt;&gt;()).add(value);\n</code></pre>\n\n<p>Or, for a <code>Set</code>:</p>\n\n<pre><code>map.computeIfAbsent(key, k -&gt; new HashSet&lt;&gt;()).add(value);\n</code></pre>\n" }, { "answer_id": 254377, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 3, "selected": false, "text": "<p>If it's an option, you may want to just use the Google Collections API - <a href=\"http://code.google.com/p/google-collections/\" rel=\"noreferrer\">http://code.google.com/p/google-collections/</a>.</p>\n\n<p>Even if you can't use it, maybe having a look at how they implemented their MultiMaps would help you with your implementation.</p>\n" }, { "answer_id": 254396, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 2, "selected": false, "text": "<p>There is a problem with your code:</p>\n\n<p>Collection c = new Collection();</p>\n\n<p>Cannot be instantiated.</p>\n\n<p>I think the next piece of code will solve your problem:</p>\n\n<pre><code>public class CollectionMap&lt;K, V&gt; extends HashMap&lt;K, Collection&lt;V&gt;&gt; {\n\n\n ...\n ...\n ...\n\n\n public void add(K key, V value) {\n if (containsKey(key)) {\n get(key).add(value);\n } else {\n Collection&lt;V&gt; c = new ArrayList&lt;V&gt;();\n c.add(value);\n super.put(key, c);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 255065, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 2, "selected": false, "text": "<p>Apache Commons Collections also offers a MultiMap, but it's pre-JDK 1-.5, so you'll have no generics safety there. You can wrap it in a Collections.checkedMap(Key.class, Value.class, collection) for run-time safety. If you can use Google's Colelction API, it offers an even slicker MultiMap with all the generics, bells and whistles.</p>\n" }, { "answer_id": 257013, "author": "Manoj", "author_id": 5541, "author_profile": "https://Stackoverflow.com/users/5541", "pm_score": 2, "selected": false, "text": "<p>If possible use Google's <a href=\"https://github.com/google/guava/wiki/NewCollectionTypesExplained\" rel=\"nofollow noreferrer\">Guava</a>. Guys have done a wonderful job there.</p>\n\n<p>Here is another solution.</p>\n\n<pre><code>abstract class MultiMap&lt;K, V&gt; {\n\n private Map&lt;K, Collection&lt;V&gt;&gt; entries = new LinkedHashMap&lt;K, Collection&lt;V&gt;&gt;();\n\n public void put(K key, V value) {\n Collection&lt;V&gt; values = entries.get(key);\n if (values == null) {\n entries.put(key, values = newValueCollection());\n }\n values.add(value);\n }\n\n // other methods\n // ..\n\n abstract Collection&lt;V&gt; newValueCollection();\n\n\n\n // Helper methods to create different flavors of MultiMaps\n\n public static &lt;K, V&gt; MultiMap&lt;K, V&gt; newArrayListMultiMap() {\n return new MultiMap&lt;K, V&gt;() {\n Collection&lt;V&gt; newValueCollection() {\n return new ArrayList&lt;V&gt;();\n }\n };\n }\n\n public static &lt;K, V&gt; MultiMap&lt;K, V&gt; newHashSetMultiMap() {\n return new MultiMap&lt;K, V&gt;() {\n Collection&lt;V&gt; newValueCollection() {\n return new HashSet&lt;V&gt;();\n }\n };\n }\n\n }\n</code></pre>\n\n<p>You can use it like</p>\n\n<pre><code>MultiMap&lt;String, Integer&gt; data = MultiMap.newArrayListMultiMap();\ndata.put(\"first\", 1);\ndata.put(\"first\", 2);\ndata.put(\"first\", 3);\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4433/" ]
I wanted to make Map of Collections in Java, so I can make something like ``` public void add(K key, V value) { if (containsKey(key)) { get(key).add(value); } else { Collection c = new Collection(); c.add(value); put(key, value); } } ``` I've tried to make it with something like ``` public class CollectionMap<K, C extends Collection<V>> extends HashMap<K, C> ``` but compiler complains about the `<V>` part, and there would still be an issue of making proper new collection. At the moment, I've made two classes: SetMap that look like this ``` 1: public class SetMap<K, V> extends HashMap<K, Set<V>> { 2: 3: public void add(K key, V value) { 4: if (containsKey(key)) { 5: get(key).add(value); 6: } else { 7: Set<V> list = new HashSet<V>(); 8: list.add(value); 9: put(key, list); 10: } 11: } 12: 13: } ``` and ListMap looks pretty much the same except the line 7 where I make new ArrayList. This sort of duplication is small enough to be tolerable, but question remains is this sort of "nested generics" possible in Java? EDIT: As [erickson said](https://stackoverflow.com/questions/254351/map-of-collections#254372), solution is in `<A, B extends Something<A>>` rather than just `<B extends Something<A>>` so code can look something like ``` public abstract class CollelctionMap<K, V, C extends Collection<V>> extends HashMap<K, C> { protected abstract C newCollection(); public void add(K key, V value) { if (containsKey(key)) { get(key).add(value); } else { C c = newCollection(); c.add(value); put(key, c); } } } ``` and ListMap and SetMap only provide proper collection
If `map` is a `Map<K, Collection<V>>`, use the idiom [`computeIfAbsent(...).add(...)`,](http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-) like this: ``` map.computeIfAbsent(key, k -> new ArrayList<>()).add(value); ``` Or, for a `Set`: ``` map.computeIfAbsent(key, k -> new HashSet<>()).add(value); ```
254,354
<p><strong>General Description:</strong></p> <p>To start with what works, I have a <code>UITableView</code> which has been placed onto an Xcode-generated view using Interface Builder. The view's File Owner is set to an Xcode-generated subclass of <code>UIViewController</code>. To this subclass I have added working implementations of <code>numberOfSectionsInTableView: tableView:numberOfRowsInSection:</code> and <code>tableView:cellForRowAtIndexPath:</code> and the Table View's <code>dataSource</code> and <code>delegate</code> are connected to this class via the File Owner in Interface Builder.</p> <p>The above configuration works with no problems. The issue occurs when I want to move this Table View's <code>dataSource</code> and <code>delegate</code>-implementations out to a separate class, most likely because there are other controls on the View besides the Table View and I'd like to move the Table View-related code out to its own class. To accomplish this, I try the following:</p> <ul> <li>Create a new subclass of <code>UITableViewController</code> in Xcode</li></li> <li>Move the known-good implementations of <code>numberOfSectionsInTableView:</code>, <code>tableView:numberOfRowsInSection:</code> and <code>tableView:cellForRowAtIndexPath:</code> to the new subclass</li> <li>Drag a <code>UITableViewController</code> to the top level of the <em>existing</em> XIB in InterfaceBuilder, delete the <code>UIView</code>/<code>UITableView</code> that are automatically created for this <code>UITableViewController</code>, then set the <code>UITableViewController</code>'s class to match the new subclass</li> <li>Remove the previously-working <code>UITableView</code>'s existing <code>dataSource</code> and <code>delegate</code> connections and connect them to the new <code>UITableViewController</code></li> </ul> <p>When complete, I do not have a working <code>UITableView</code>. I end up with one of three outcomes which can seemingly happen at random:</p> <ul> <li>When the <code>UITableView</code> loads, I get a runtime error indicating I am sending <code>tableView:cellForRowAtIndexPath:</code> to an object which does not recognize it</li> <li>When the <code>UITableView</code> loads, the project breaks into the debugger without error</li> <li>There is no error, but the <code>UITableView</code> does not appear</li> </ul> <p>With some debugging and having created a basic project just to reproduce this issue, I am usually seeing the 3rd option above (no error but no visible table view). I added some NSLog calls and found that although <code>numberOfSectionsInTableView:</code> and <code>numberOfRowsInSection:</code> are both getting called, <code>cellForRowAtIndexPath:</code> is not. I am convinced I'm missing something really simple and was hoping the answer may be obvious to someone with more experience than I have. If this doesn't turn out to be an easy answer I would be happy to update with some code or a sample project. Thanks for your time!</p> <p><strong>Complete steps to reproduce:</strong></p> <ul> <li>Create a new iPhone OS, View-Based Application in Xcode and call it <code>TableTest</code></li> <li>Open <code>TableTestViewController.xib</code> in Interface Builder and drag a <code>UITableView</code> onto the provided view surface.</li> <li>Connect the <code>UITableView</code>'s <code>dataSource</code> and <code>delegate</code>-outlets to File's Owner, which should already represent the <code>TableTestViewController</code>-class. Save your changes</li> <li>Back in Xcode, add the following code to <code>TableTestViewController.m:</code></li> </ul> <hr> <pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { NSLog(@"Returning num sections"); return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSLog(@"Returning num rows"); return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Trying to return cell"); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } cell.text = @"Hello"; NSLog(@"Returning cell"); return cell; } </code></pre> <ul> <li><p>Build and Go, and you should see the word <code>Hello</code> appear in the <code>UITableView</code></p></li> <li><p>Now to attempt to move this <code>UITableView</code>'s logic out to a separate class, first create a new file in Xcode, choosing <code>UITableViewController</code> subclass and calling the class <code>TableTestTableViewController</code></p></li> <li>Remove the above code snippet from <code>TableTestViewController.m</code> and place it into <code>TableTestTableViewController.m</code>, replacing the default implementation of these three methods with ours.</li> <li>Back in Interface Builder within the same <code>TableTestViewController.xib</code>-file, drag a <code>UITableViewController</code> into the main IB window and delete the new <code>UITableView</code> object that automatically came with it</li> <li>Set the class for this new <code>UITableViewController</code> to <code>TableTestTableViewController</code></li> <li>Remove the <code>dataSource</code> and <code>delegate</code> bindings from the existing, previously-working <code>UITableView</code> and reconnect the same two bindings to the new <code>TableTestTableViewController</code> we created.</li> <li>Save changes, Build and Go, and if you're getting the results I'm getting, note the <code>UITableView</code> no longer functions properly</li> </ul> <p><strong>Solution:</strong> With some more troubleshooting and some assistance from the <a href="https://devforums.apple.com/message/5453" rel="noreferrer">iPhone Developer Forums</a>, I've documented a solution! The main <code>UIViewController</code> subclass of the project needs an outlet pointing to the <code>UITableViewController</code> instance. To accomplish this, simply add the following to the primary view's header (<code>TableTestViewController.h</code>):</p> <pre><code>#import "TableTestTableViewController.h" </code></pre> <p>and</p> <pre><code>IBOutlet TableTestTableViewController *myTableViewController; </code></pre> <p>Then, in Interface Builder, connect the new outlet from File's Owner to <code>TableTestTableViewController</code> in the main IB window. No changes are necessary in the UI part of the XIB. Simply having this outlet in place, even though no user code directly uses it, resolves the problem completely. Thanks to those who've helped and credit goes to BaldEagle on the iPhone Developer Forums for finding the solution.</p>
[ { "answer_id": 254813, "author": "keremk", "author_id": 29475, "author_profile": "https://Stackoverflow.com/users/29475", "pm_score": 2, "selected": false, "text": "<p>Yes for some reason (please chime in if anybody knows why...) <code>tableView</code> property of the <code>UITableViewController</code> is not exposed as an <code>IBOutlet</code> even though it is a public property. So when you use Interface Builder, you can't see that property to connect to your other <code>UITableView</code>. So in your subclass, you can create a <code>tableView</code> property marked as an <code>IBOutlet</code> and connect that. </p>\n\n<p>This all seems hacky and a workaround to me, but it seems to be the only way to separate a <code>UITableViewController's</code> <code>UITableView</code> and put it somewhere else in UI hierarchy. I ran into the same issue when I tried to design view where there are things other than the <code>UITableView</code> and that was the way I solved it... Is this the right approach???</p>\n" }, { "answer_id": 255874, "author": "keremk", "author_id": 29475, "author_profile": "https://Stackoverflow.com/users/29475", "pm_score": 6, "selected": true, "text": "<p>I followed your steps, recreated the project and ran into the same problem. Basically you are almost there. There are 2 things missing (once fixed it works):</p>\n\n<ul>\n<li><p>You need to connect the <code>tableView</code> of the <code>TableTestTableViewController</code> to the <code>UITableView</code> you have on the screen. As I said before because it is not <code>IBOutlet</code> you can override the <code>tableView</code> property and make it and <code>IBOutlet</code>:</p>\n\n<pre><code>@interface TableTestTableViewController : UITableViewController {\n UITableView *tableView;\n}\n\n@property (nonatomic, retain) IBOutlet UITableView *tableView;\n</code></pre></li>\n<li><p>Next thing is to add a reference to the <code>TableTestTableViewController</code> and retain it in the <code>TableTestViewController</code>. Otherwise your <code>TableTestTableViewController</code> may be released (after loading the nib with nothing hanging on to it.) and that is why you are seeing the erratic results, crashes or nothing showing. To do that add:</p>\n\n<pre><code>@interface TableTestViewController : UIViewController {\n TableTestTableViewController *tableViewController;\n}\n\n@property (nonatomic, retain) IBOutlet TableTestTableViewController *tableViewController;\n</code></pre>\n\n<p>and connect that in the Interface Builder to the <code>TableTestTableViewController</code> instance.</p></li>\n</ul>\n\n<p>With the above this worked fine on my machine.</p>\n\n<p>Also I think it would be good to state the motivation behind all this (instead of just using the <code>UITableViewController</code> with its own <code>UITableView</code>). In my case it was to use other views that just the <code>UITableView</code> on the same screenful of content. So I can add other <code>UILabels</code> or <code>UIImages</code> under <code>UIView</code> and show the <code>UITableView</code> under them or above them. </p>\n" }, { "answer_id": 621320, "author": "Pat Niemeyer", "author_id": 74975, "author_profile": "https://Stackoverflow.com/users/74975", "pm_score": 2, "selected": false, "text": "<p>I just spent many hours pulling my hair out trying to figure out why a <code>UITableView</code> wouldn't show up when when I had it embedded in a separate nib instead of in the main nib. I finally found your discussion above and realized that it was because my <code>UITableViewController</code> wasn't being retained! Apparently the delegate and datasource properties of <code>UITableView</code> are not marked \"retain\" and so my nib was loading but the controller was getting tossed... And due to the wonders of objective-c I got <em>no</em> error messages at all from this... I still don't understand why it didn't crash. I know that I've seen \"message sent to released xxx\" before... why wasn't it giving me one of those?!?</p>\n\n<p>I think most developers would assume that structure that they build in an interface builder would be held in some larger context (the Nib) and not subject to release. I guess I know why they do this.. so that the iPhone can drop and reload parts of the nib on low memory. But man, that was hard to figure out.</p>\n\n<p>Can someone tell me where I should have read about that behavior in the docs?</p>\n\n<p>Also - about hooking up the view. First, if you drag one in from the UI builder you'll see that they hook up the view property (which is an <code>IBOutlet</code>) to the table view. It's not necessary to expose the <code>tableView</code>, that seems to get set internally. In fact it doesn't even seem to be necessary to set the view unless you want <code>viewDidLoad</code> notification. I've just broken the view connection between my <code>uitableview</code> and <code>uitableviewcontroller</code> (only delegate and datasource set) and it's apparently working fine.</p>\n" }, { "answer_id": 9650964, "author": "user589642", "author_id": 589642, "author_profile": "https://Stackoverflow.com/users/589642", "pm_score": 2, "selected": false, "text": "<p>I was able to make this work. I built a really nice dashboard with 4 TableViews and a webview with video. The key is having the separate tableView controllers and the IBOutlets to the other tableview controllers defined in the view controller. In UIB you just need to connect the other tableview controllers to the file owner of the view controller. Then connect the tables to the corresponding view controllers for the datasource and delegate.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33164/" ]
**General Description:** To start with what works, I have a `UITableView` which has been placed onto an Xcode-generated view using Interface Builder. The view's File Owner is set to an Xcode-generated subclass of `UIViewController`. To this subclass I have added working implementations of `numberOfSectionsInTableView: tableView:numberOfRowsInSection:` and `tableView:cellForRowAtIndexPath:` and the Table View's `dataSource` and `delegate` are connected to this class via the File Owner in Interface Builder. The above configuration works with no problems. The issue occurs when I want to move this Table View's `dataSource` and `delegate`-implementations out to a separate class, most likely because there are other controls on the View besides the Table View and I'd like to move the Table View-related code out to its own class. To accomplish this, I try the following: * Create a new subclass of `UITableViewController` in Xcode * Move the known-good implementations of `numberOfSectionsInTableView:`, `tableView:numberOfRowsInSection:` and `tableView:cellForRowAtIndexPath:` to the new subclass * Drag a `UITableViewController` to the top level of the *existing* XIB in InterfaceBuilder, delete the `UIView`/`UITableView` that are automatically created for this `UITableViewController`, then set the `UITableViewController`'s class to match the new subclass * Remove the previously-working `UITableView`'s existing `dataSource` and `delegate` connections and connect them to the new `UITableViewController` When complete, I do not have a working `UITableView`. I end up with one of three outcomes which can seemingly happen at random: * When the `UITableView` loads, I get a runtime error indicating I am sending `tableView:cellForRowAtIndexPath:` to an object which does not recognize it * When the `UITableView` loads, the project breaks into the debugger without error * There is no error, but the `UITableView` does not appear With some debugging and having created a basic project just to reproduce this issue, I am usually seeing the 3rd option above (no error but no visible table view). I added some NSLog calls and found that although `numberOfSectionsInTableView:` and `numberOfRowsInSection:` are both getting called, `cellForRowAtIndexPath:` is not. I am convinced I'm missing something really simple and was hoping the answer may be obvious to someone with more experience than I have. If this doesn't turn out to be an easy answer I would be happy to update with some code or a sample project. Thanks for your time! **Complete steps to reproduce:** * Create a new iPhone OS, View-Based Application in Xcode and call it `TableTest` * Open `TableTestViewController.xib` in Interface Builder and drag a `UITableView` onto the provided view surface. * Connect the `UITableView`'s `dataSource` and `delegate`-outlets to File's Owner, which should already represent the `TableTestViewController`-class. Save your changes * Back in Xcode, add the following code to `TableTestViewController.m:` --- ``` - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { NSLog(@"Returning num sections"); return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSLog(@"Returning num rows"); return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Trying to return cell"); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } cell.text = @"Hello"; NSLog(@"Returning cell"); return cell; } ``` * Build and Go, and you should see the word `Hello` appear in the `UITableView` * Now to attempt to move this `UITableView`'s logic out to a separate class, first create a new file in Xcode, choosing `UITableViewController` subclass and calling the class `TableTestTableViewController` * Remove the above code snippet from `TableTestViewController.m` and place it into `TableTestTableViewController.m`, replacing the default implementation of these three methods with ours. * Back in Interface Builder within the same `TableTestViewController.xib`-file, drag a `UITableViewController` into the main IB window and delete the new `UITableView` object that automatically came with it * Set the class for this new `UITableViewController` to `TableTestTableViewController` * Remove the `dataSource` and `delegate` bindings from the existing, previously-working `UITableView` and reconnect the same two bindings to the new `TableTestTableViewController` we created. * Save changes, Build and Go, and if you're getting the results I'm getting, note the `UITableView` no longer functions properly **Solution:** With some more troubleshooting and some assistance from the [iPhone Developer Forums](https://devforums.apple.com/message/5453), I've documented a solution! The main `UIViewController` subclass of the project needs an outlet pointing to the `UITableViewController` instance. To accomplish this, simply add the following to the primary view's header (`TableTestViewController.h`): ``` #import "TableTestTableViewController.h" ``` and ``` IBOutlet TableTestTableViewController *myTableViewController; ``` Then, in Interface Builder, connect the new outlet from File's Owner to `TableTestTableViewController` in the main IB window. No changes are necessary in the UI part of the XIB. Simply having this outlet in place, even though no user code directly uses it, resolves the problem completely. Thanks to those who've helped and credit goes to BaldEagle on the iPhone Developer Forums for finding the solution.
I followed your steps, recreated the project and ran into the same problem. Basically you are almost there. There are 2 things missing (once fixed it works): * You need to connect the `tableView` of the `TableTestTableViewController` to the `UITableView` you have on the screen. As I said before because it is not `IBOutlet` you can override the `tableView` property and make it and `IBOutlet`: ``` @interface TableTestTableViewController : UITableViewController { UITableView *tableView; } @property (nonatomic, retain) IBOutlet UITableView *tableView; ``` * Next thing is to add a reference to the `TableTestTableViewController` and retain it in the `TableTestViewController`. Otherwise your `TableTestTableViewController` may be released (after loading the nib with nothing hanging on to it.) and that is why you are seeing the erratic results, crashes or nothing showing. To do that add: ``` @interface TableTestViewController : UIViewController { TableTestTableViewController *tableViewController; } @property (nonatomic, retain) IBOutlet TableTestTableViewController *tableViewController; ``` and connect that in the Interface Builder to the `TableTestTableViewController` instance. With the above this worked fine on my machine. Also I think it would be good to state the motivation behind all this (instead of just using the `UITableViewController` with its own `UITableView`). In my case it was to use other views that just the `UITableView` on the same screenful of content. So I can add other `UILabels` or `UIImages` under `UIView` and show the `UITableView` under them or above them.
254,385
<p>I want to simplify my execution of a Groovy script that makes calls to an Oracle database. How do I add the ojdbc jar to the default classpath so that I can run:</p> <pre><code>groovy RunScript.groovy </code></pre> <p>instead of:</p> <pre><code>groovy -cp ojdbc5.jar RunScript.groovy </code></pre>
[ { "answer_id": 254431, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 1, "selected": false, "text": "<p><code>groovy</code> is just a wrapper script for the Groovy JAR that sets up the Java classpath. You could modify that script to add the path to your own JAR, as well, I suppose.</p>\n" }, { "answer_id": 254443, "author": "Joey Gibson", "author_id": 6645, "author_profile": "https://Stackoverflow.com/users/6645", "pm_score": 3, "selected": false, "text": "<p>There are a few ways to do it. You can add the jar to your system's CLASSPATH variable. You can create a directory called .groovy/lib in your home directory and put the jar in there. It will be automatically added to your classpath at runtime. Or, you can do it in code: </p>\n\n<pre><code>this.class.classLoader.rootLoader.addURL(new URL(\"file:///path to file\"))\n</code></pre>\n" }, { "answer_id": 254448, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 5, "selected": true, "text": "<p>Summarized from <em>Groovy Recipes</em>, by Scott Davis, <strong>Automatically Including JARs in the ./groovy/lib Directory</strong>:</p>\n\n<ol>\n<li>Create <code>.groovy/lib</code> in your login directory</li>\n<li><p>Uncomment the following line in ${GROOVY_HOME}/conf/groovy-starter.conf</p>\n\n<p><code>load !{user.home}/.groovy/lib/*.jar</code></p></li>\n<li><p>Copy the jars you want included to <code>.groovy/lib</code></p></li>\n</ol>\n\n<p>It appears that for Groovy 1.5 or later you get this by default (no need to edit the conf), just drop the jars in the /lib dir.</p>\n" }, { "answer_id": 42890203, "author": "bonh", "author_id": 2068738, "author_profile": "https://Stackoverflow.com/users/2068738", "pm_score": 1, "selected": false, "text": "<p>You could add the following <a href=\"https://en.wikipedia.org/wiki/Shebang_(Unix)\" rel=\"nofollow noreferrer\">shebang</a> to the first line of your Groovy script:</p>\n\n<pre><code>#!/usr/bin/env groovy -cp ojdbc5.jar\n</code></pre>\n\n<p>Then, mark the script executable:</p>\n\n<pre><code>chmod u+x RunScript.groovy\n</code></pre>\n\n<p>Now, running the script by itself will set the classpath automatically.</p>\n\n<pre><code>./RunScript.groovy\n</code></pre>\n" }, { "answer_id": 61104823, "author": "Cristi B.", "author_id": 2064134, "author_profile": "https://Stackoverflow.com/users/2064134", "pm_score": 2, "selected": false, "text": "<p>One way would be using @Grab in the code:</p>\n\n<pre><code> @GrabConfig(systemClassLoader=true)\n @Grab('com.oracle:ojdbc6:12.1.0.2.0')\n Class.forName(\"oracle.jdbc.OracleDriver\").newInstance()\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013/" ]
I want to simplify my execution of a Groovy script that makes calls to an Oracle database. How do I add the ojdbc jar to the default classpath so that I can run: ``` groovy RunScript.groovy ``` instead of: ``` groovy -cp ojdbc5.jar RunScript.groovy ```
Summarized from *Groovy Recipes*, by Scott Davis, **Automatically Including JARs in the ./groovy/lib Directory**: 1. Create `.groovy/lib` in your login directory 2. Uncomment the following line in ${GROOVY\_HOME}/conf/groovy-starter.conf `load !{user.home}/.groovy/lib/*.jar` 3. Copy the jars you want included to `.groovy/lib` It appears that for Groovy 1.5 or later you get this by default (no need to edit the conf), just drop the jars in the /lib dir.
254,388
<p>How does one go about converting an image to black and white in PHP?</p> <p>Not just turning it into greyscale but every pixel made black or white?</p>
[ { "answer_id": 254393, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 3, "selected": false, "text": "<p>You could shell out to imagemagick, assuming your host supports it. What function do you want to use for deciding if a pixel should be black or white?</p>\n" }, { "answer_id": 254406, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>If you intend to do this yourself, you will need to implement a <a href=\"http://en.wikipedia.org/wiki/Dithering#Dithering_algorithms\" rel=\"nofollow noreferrer\">dithering algorithm</a>. But as <a href=\"https://stackoverflow.com/questions/254388/how-do-you-converting-an-image-to-black-and-white-in-php#254393\">@jonni</a> says, using an existing tool would be much easier?</p>\n" }, { "answer_id": 254427, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 5, "selected": true, "text": "<p>Simply round the grayscale color to either black or white.</p>\n\n<pre><code>float gray = (r + g + b) / 3\nif(gray &gt; 0x7F) return 0xFF;\nreturn 0x00;\n</code></pre>\n" }, { "answer_id": 254776, "author": "Joel Wietelmann", "author_id": 28340, "author_profile": "https://Stackoverflow.com/users/28340", "pm_score": 5, "selected": false, "text": "<p>Using the php <a href=\"http://us2.php.net/manual/en/function.imagefilter.php\" rel=\"noreferrer\">gd</a> library:</p>\n\n<pre><code>imagefilter($im, IMG_FILTER_GRAYSCALE);\nimagefilter($im, IMG_FILTER_CONTRAST, -100);\n</code></pre>\n\n<p>Check the user comments in the link above for more examples.</p>\n" }, { "answer_id": 255369, "author": "Hugh Bothwell", "author_id": 33258, "author_profile": "https://Stackoverflow.com/users/33258", "pm_score": 0, "selected": false, "text": "<p>For each pixel you must convert from color to greyscale - something like\n$grey = $red * 0.299 + $green * 0.587 + $blue * 0.114;\n(these are NTSC weighting factors; other similar weightings exist. This mimics the eye's varying responsiveness to different colors).</p>\n\n<p>Then you need to decide on a cut-off value - generally half the maximum pixel value, but depending on the image you may prefer a higher value (make the image darker) or lower (make the image brighter).</p>\n\n<p>Just comparing each pixel to the cut-off loses a lot of detail - ie large dark areas go completely black - so to retain more information, you can dither. Basically, start at the top left of the image: for each pixel add the error (the difference between the original value and final assigned value) for the pixels to the left and above before comparing to the cut-off value.</p>\n\n<p>Be aware that doing this in PHP will be very slow - you would be much further ahead to find a library which provides this.</p>\n" }, { "answer_id": 10313995, "author": "KEL", "author_id": 1355937, "author_profile": "https://Stackoverflow.com/users/1355937", "pm_score": 1, "selected": false, "text": "<pre><code>$rgb = imagecolorat($original, $x, $y);\n $r = ($rgb &gt;&gt; 16) &amp; 0xFF;\n $g = ($rgb &gt;&gt; 8 ) &amp; 0xFF;\n $b = $rgb &amp; 0xFF;\n\n $gray = $r + $g + $b/3;\n if ($gray &gt;0xFF) {$grey = 0xFFFFFF;}\n else { $grey=0x000000;}\n</code></pre>\n" }, { "answer_id": 14289672, "author": "Amed", "author_id": 1065166, "author_profile": "https://Stackoverflow.com/users/1065166", "pm_score": 1, "selected": false, "text": "<p>This function work like a charm </p>\n\n<pre><code> public function ImageToBlackAndWhite($im) {\n\n for ($x = imagesx($im); $x--;) {\n for ($y = imagesy($im); $y--;) {\n $rgb = imagecolorat($im, $x, $y);\n $r = ($rgb &gt;&gt; 16) &amp; 0xFF;\n $g = ($rgb &gt;&gt; 8 ) &amp; 0xFF;\n $b = $rgb &amp; 0xFF;\n $gray = ($r + $g + $b) / 3;\n if ($gray &lt; 0xFF) {\n\n imagesetpixel($im, $x, $y, 0xFFFFFF);\n }else\n imagesetpixel($im, $x, $y, 0x000000);\n }\n }\n\n imagefilter($im, IMG_FILTER_NEGATE);\n\n}\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2118/" ]
How does one go about converting an image to black and white in PHP? Not just turning it into greyscale but every pixel made black or white?
Simply round the grayscale color to either black or white. ``` float gray = (r + g + b) / 3 if(gray > 0x7F) return 0xFF; return 0x00; ```
254,397
<p>I'm extracting a folder from a tarball, and I see these zero-byte files showing up in the result (where they are not in the source.) Setup (all on OS X):</p> <p>On machine one, I have a directory /My/Stuff/Goes/Here/ containing several hundred files. I build it like this</p> <pre><code>tar -cZf mystuff.tgz /My/Stuff/Goes/Here/ </code></pre> <p>On machine two, I scp the tgz file to my local directory, then unpack it.</p> <pre><code>tar -xZf mystuff.tgz </code></pre> <p>It creates ~scott/My/Stuff/Goes/, but then under Goes, I see two files:</p> <pre><code>Here/ - a directory, Here.bGd - a zero byte file. </code></pre> <p>The "Here.bGd" zero-byte file has a random 3-character suffix, mixed upper and lower-case characters. It has the same name as the lowest-level directory mentioned in the tar-creation command. It only appears at the lowest level directory named. Anybody know where these come from, and how I can adjust my tar creation to get rid of them?</p> <p><strong>Update:</strong> I checked the table of contents on the files using tar tZvf: toc does not list the zero-byte files, so I'm leaning toward the suggestion that the uncompress machine is at fault. OS X is version 10.5.5 on the unzip machine (not sure how to check the filesystem type). Tar is GNU tar 1.15.1, and it came with the machine.</p>
[ { "answer_id": 254417, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": -1, "selected": false, "text": "<p>I don't know (and boy is this a hard problem to Google for!), but here's a troubleshooting step: try <code>tar</code> without <code>Z</code>. That will determine whether <code>compress</code> or <code>tar</code> is causing the issue.</p>\n" }, { "answer_id": 254422, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>You can get a table of contents from the tarball by doing</p>\n\n<p><code>tar tZvf mystuff.tgz</code></p>\n\n<p>If those zero-byte files are listed in the table of contents, then the problem is on the computer making the tarball. If they aren't listed, then the problem is on the computer decompressing the tarball.</p>\n" }, { "answer_id": 254444, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "<p>I can't replicate this on my 10.5.5 system.</p>\n\n<p>So, for each system:</p>\n\n<ol>\n<li>what version of OSX are you using?</li>\n<li>what filesystem is in use?</li>\n</ol>\n" }, { "answer_id": 254484, "author": "Jay Conrod", "author_id": 1891, "author_profile": "https://Stackoverflow.com/users/1891", "pm_score": 0, "selected": false, "text": "<p>I have not seen this particular problem before with tar. However, there is another problem where tar bundles metadata files with regular files (they have the same name but are prefixed with \"._\"). The solution to this was to set the environment variable <code>COPYFILE_DISABLE=y</code>. If those weird files you have are more metadata files, maybe this would solve your problem as well?</p>\n\n<p>Failing that, you could try installing a different version of tar.</p>\n" }, { "answer_id": 255597, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>On my MacOS X (10.4.11) machine, I sometimes acquire files .DS_Store in a directory (but these are not empty files), and I've seen other hidden file names on memory sticks that have been used on the Mac. These are somehow related to the Mac file system. I'd guess that what you are seeing are related to one or the other of these sets of files. Original Macs (MacOS 9 and earlier) had data forks and resource forks for files.</p>\n\n<p>A little bit of play shows that a directory in which I've never used Finder has no .DS_Store file; if I use the Finder to navigate to that directory, the .DS_Store file appears. It presumably contains information about how the files should appear in the Finder display (so if you move files around, they stay where you put them).</p>\n\n<p>This doesn't directly answer your question; I hope it gives some pointers.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm extracting a folder from a tarball, and I see these zero-byte files showing up in the result (where they are not in the source.) Setup (all on OS X): On machine one, I have a directory /My/Stuff/Goes/Here/ containing several hundred files. I build it like this ``` tar -cZf mystuff.tgz /My/Stuff/Goes/Here/ ``` On machine two, I scp the tgz file to my local directory, then unpack it. ``` tar -xZf mystuff.tgz ``` It creates ~scott/My/Stuff/Goes/, but then under Goes, I see two files: ``` Here/ - a directory, Here.bGd - a zero byte file. ``` The "Here.bGd" zero-byte file has a random 3-character suffix, mixed upper and lower-case characters. It has the same name as the lowest-level directory mentioned in the tar-creation command. It only appears at the lowest level directory named. Anybody know where these come from, and how I can adjust my tar creation to get rid of them? **Update:** I checked the table of contents on the files using tar tZvf: toc does not list the zero-byte files, so I'm leaning toward the suggestion that the uncompress machine is at fault. OS X is version 10.5.5 on the unzip machine (not sure how to check the filesystem type). Tar is GNU tar 1.15.1, and it came with the machine.
You can get a table of contents from the tarball by doing `tar tZvf mystuff.tgz` If those zero-byte files are listed in the table of contents, then the problem is on the computer making the tarball. If they aren't listed, then the problem is on the computer decompressing the tarball.
254,407
<p>I want to create a string that spans multiple lines to assign to a Label Caption property. How is this done in Delphi?</p>
[ { "answer_id": 254412, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 5, "selected": false, "text": "<p><code>my_string := 'Hello,' + #13#10 + 'world!';</code></p>\n\n<p><code>#13#10</code> is the CR/LF characters in decimal</p>\n" }, { "answer_id": 254465, "author": "Zartog", "author_id": 9467, "author_profile": "https://Stackoverflow.com/users/9467", "pm_score": 5, "selected": false, "text": "<p>Here's an even shorter approach:</p>\n\n<pre><code>my_string := 'Hello,'#13#10' world!';\n</code></pre>\n" }, { "answer_id": 254668, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 3, "selected": false, "text": "<p>On the side, a trick that can be useful:<br>\nIf you hold your multiple strings in a TStrings, you just have to use the Text property of the TStrings like in the following example.</p>\n\n<pre><code>Label1.Caption := Memo1.Lines.Text;\n</code></pre>\n\n<p>And you'll get your multi-line label...</p>\n" }, { "answer_id": 254820, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 4, "selected": false, "text": "<p>Or you can use the ^M+^J shortcut also. All a matter of preference. the \"CTRL-CHAR\" codes are translated by the compiler.</p>\n\n<pre><code>MyString := 'Hello,' + ^M + ^J + 'world!';\n</code></pre>\n\n<p>You can take the + away between the ^M and ^J, but then you will get a warning by the compiler (but it will still compile fine). </p>\n" }, { "answer_id": 254997, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 9, "selected": true, "text": "<p>In the System.pas (which automatically gets used) the following is defined:</p>\n\n<pre><code>const\n sLineBreak = {$IFDEF LINUX} AnsiChar(#10) {$ENDIF} \n {$IFDEF MSWINDOWS} AnsiString(#13#10) {$ENDIF};\n</code></pre>\n\n<p>This is from Delphi 2009 (notice the use of AnsiChar and AnsiString). (Line wrap added by me.)</p>\n\n<p>So if you want to make your TLabel wrap, make sure AutoSize is set to true, and then use the following code:</p>\n\n<pre><code>label1.Caption := 'Line one'+sLineBreak+'Line two';\n</code></pre>\n\n<p>Works in all versions of Delphi since sLineBreak was introduced, which I believe was Delphi 6.</p>\n" }, { "answer_id": 255769, "author": "Toby Allen", "author_id": 6244, "author_profile": "https://Stackoverflow.com/users/6244", "pm_score": 0, "selected": false, "text": "<p>I dont have a copy of Delphi to hand, but I'm fairly certain if you set the wordwrap property to true and the autosize property to false it should wrap any text you put it at the size you make the label. If you want to line break in a certain place then <strong>it might work if you set the above settings and paste from a text editor</strong>.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 734576, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>ShowMessage('Hello'+Chr(10)+'World');\n</code></pre>\n" }, { "answer_id": 24833814, "author": "Jessé Catrinck", "author_id": 3625217, "author_profile": "https://Stackoverflow.com/users/3625217", "pm_score": 2, "selected": false, "text": "<pre><code>var\n stlst: TStringList;\nbegin\n Label1.Caption := 'Hello,'+sLineBreak+'world!';\n\n Label2.Caption := 'Hello,'#13#10'world!';\n\n Label3.Caption := 'Hello,' + chr(13) + chr(10) + 'world!';\n\n stlst := TStringList.Create;\n stlst.Add('Hello,');\n stlst.Add('world!');\n Label4.Caption := stlst.Text;\n\n Label5.WordWrap := True; //Multi-line Caption\n Label5.Caption := 'Hello,'^M^J'world!';\n\n Label6.Caption := AdjustLineBreaks('Hello,'#10'world!');\n {http://delphi.about.com/library/rtl/blrtlAdjustLineBreaks.htm}\nend;\n</code></pre>\n" }, { "answer_id": 34000019, "author": "Wendigo", "author_id": 5621502, "author_profile": "https://Stackoverflow.com/users/5621502", "pm_score": 3, "selected": false, "text": "<p>The plattform agnostic way would be 'sLineBreak':\n<a href=\"http://www.freepascal.org/docs-html/rtl/system/slinebreak.html\" rel=\"noreferrer\">http://www.freepascal.org/docs-html/rtl/system/slinebreak.html</a></p>\n\n<p>Write('Hello' + sLineBreak + 'World!');</p>\n" }, { "answer_id": 45469950, "author": "Dave Sonsalla", "author_id": 2981029, "author_profile": "https://Stackoverflow.com/users/2981029", "pm_score": -1, "selected": false, "text": "<p>Sometimes I don't want to clutter up my code space, especially for a static label. To just have it defined with the form, enter the label text on the form, then right click anywhere on the same form. Choose \"View as Text\". You will now see all of the objects as designed, but as text only. Scroll down or search for your text. When you find it, edit the caption, so it looks something like: </p>\n\n<p>Caption = 'Line 1'#13'Line 2'#13'Line 3'</p>\n\n<p>#13 means an ordinal 13, or ascii for carriage return. Chr(13) is the same idea, CHR() changes the number to an ordinal type. </p>\n\n<p>Note that there are no semi-colon's in this particular facet of Delphi, and \"=\" is used rather than \":=\". The text for each line is enclosed in single quotes. </p>\n\n<p>Once you are done, right-click once again and choose \"View as Form\". You can now do any formatting such as bold, right justify, etc. You just can't re-edit the text on the form or you will lose your line breaks.</p>\n\n<p>I also use \"View as Text\" for multiple changes where I just want to scroll through and do replacements, etc. Quick.</p>\n\n<p>Dave</p>\n" }, { "answer_id": 46758569, "author": "boodyman28", "author_id": 8111869, "author_profile": "https://Stackoverflow.com/users/8111869", "pm_score": -1, "selected": false, "text": "<pre><code> private\n { Private declarations }\n {declare a variable like this}\n NewLine : string; // ok\n // in next event handler assign a value to that variable (NewLine)\n // like the code down\nprocedure TMainForm.FormCreate(Sender: TObject);\nbegin`enter code here`\n NewLine := #10;\n {Next Code To show NewLine In action}\n //ShowMessage('Hello to programming with Delphi' + NewLine + 'Print New Lin now !!!!');\nend;\n</code></pre>\n" }, { "answer_id": 67011494, "author": "Samuel Cruz", "author_id": 11515709, "author_profile": "https://Stackoverflow.com/users/11515709", "pm_score": 1, "selected": false, "text": "<p>You have the <code>const sLineBreak</code> in the <code>System.pas</code> <code>unit</code> that already does the treatment according to the OS you are working on.</p>\n<p>Example of use:</p>\n<pre><code>TForm1.btnInfoClick(Sender: TObject);\nbegin\n ShowMessage ('My name is Jhon' + sLineBreak\n 'Profession: Hollywood actor');\nend;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199/" ]
I want to create a string that spans multiple lines to assign to a Label Caption property. How is this done in Delphi?
In the System.pas (which automatically gets used) the following is defined: ``` const sLineBreak = {$IFDEF LINUX} AnsiChar(#10) {$ENDIF} {$IFDEF MSWINDOWS} AnsiString(#13#10) {$ENDIF}; ``` This is from Delphi 2009 (notice the use of AnsiChar and AnsiString). (Line wrap added by me.) So if you want to make your TLabel wrap, make sure AutoSize is set to true, and then use the following code: ``` label1.Caption := 'Line one'+sLineBreak+'Line two'; ``` Works in all versions of Delphi since sLineBreak was introduced, which I believe was Delphi 6.
254,419
<p>I have an aspx page which will upload images to server harddisk from client pc</p> <p>But now i need to change my program in such a way that it would allow me to resize the image while uploading.</p> <p>Does anyone has any idea on this ? I couldnt not find such properties/methods with Input file server control</p> <p>Any one there to guide me ?</p>
[ { "answer_id": 254430, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 3, "selected": false, "text": "<p>You will not be able to resize \"on the fly\" since you will need to have the full image before you perform any image transformations. However, after the upload is complete and before you display any results to your user, you can use this basic image resizing method that I've used in a couple of my apps now:</p>\n\n<pre><code> ''' &lt;summary&gt;\n ''' Resize image with GDI+ so that image is nice and clear with required size.\n ''' &lt;/summary&gt;\n ''' &lt;param name=\"SourceImage\"&gt;Image to resize&lt;/param&gt;\n ''' &lt;param name=\"NewHeight\"&gt;New height to resize to.&lt;/param&gt;\n ''' &lt;param name=\"NewWidth\"&gt;New width to resize to.&lt;/param&gt;\n ''' &lt;returns&gt;Image object resized to new dimensions.&lt;/returns&gt;\n ''' &lt;remarks&gt;&lt;/remarks&gt;\n Public Shared Function ImageResize(ByVal SourceImage As Image, ByVal NewHeight As Int32, ByVal NewWidth As Int32) As Image\n\n Dim bitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(NewWidth, NewHeight, SourceImage.PixelFormat)\n\n If bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format4bppIndexed Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format8bppIndexed Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Undefined Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.DontCare Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppArgb1555 Or _\n bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppGrayScale Then\n Throw New NotSupportedException(\"Pixel format of the image is not supported.\")\n End If\n\n Dim graphicsImage As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmap)\n\n graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality\n graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic\n graphicsImage.DrawImage(SourceImage, 0, 0, bitmap.Width, bitmap.Height)\n graphicsImage.Dispose()\n Return bitmap\n\n End Function\n</code></pre>\n" }, { "answer_id": 254460, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 4, "selected": false, "text": "<p>Once the file has been saved to the server you can use code like this to resize. This code will take care of length/width ratio on the resize.</p>\n\n<pre><code>public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)\n{\n\n System.Drawing.Bitmap bmpOut = null;\n\n try\n {\n Bitmap loBMP = new Bitmap(lcFilename);\n ImageFormat loFormat = loBMP.RawFormat;\n\n decimal lnRatio;\n int lnNewWidth = 0;\n int lnNewHeight = 0;\n\n if (loBMP.Width &lt; lnWidth &amp;&amp; loBMP.Height &lt; lnHeight)\n return loBMP;\n\n if (loBMP.Width &gt; loBMP.Height)\n {\n lnRatio = (decimal)lnWidth / loBMP.Width;\n lnNewWidth = lnWidth;\n decimal lnTemp = loBMP.Height * lnRatio;\n lnNewHeight = (int)lnTemp;\n }\n else\n {\n lnRatio = (decimal)lnHeight / loBMP.Height;\n lnNewHeight = lnHeight;\n decimal lnTemp = loBMP.Width * lnRatio;\n lnNewWidth = (int)lnTemp;\n }\n\n\n bmpOut = new Bitmap(lnNewWidth, lnNewHeight);\n Graphics g = Graphics.FromImage(bmpOut);\n g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;\n g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;\n g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;\n g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);\n g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);\n\n loBMP.Dispose();\n }\n catch\n {\n return null;\n }\n return bmpOut;\n}\n</code></pre>\n" }, { "answer_id": 254510, "author": "Sean", "author_id": 29941, "author_profile": "https://Stackoverflow.com/users/29941", "pm_score": 0, "selected": false, "text": "<pre><code>using System.IO;\nusing System.Drawing;\nusing System.Drawing.Imaging;\n\npublic partial class admin_AddPhoto : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n string reportPath = Server.MapPath(\"../picnic\");\n\n if (!Directory.Exists(reportPath))\n {\n Directory.CreateDirectory(Server.MapPath(\"../picnic\"));\n }\n }\n\n protected void PhotoForm_ItemInserting(object sender, FormViewInsertEventArgs e)\n {\n FormView uploadForm = sender as FormView;\n FileUpload uploadedFile = uploadForm.FindControl(\"uploadedFile\") as FileUpload;\n\n if (uploadedFile != null)\n {\n string fileName = uploadedFile.PostedFile.FileName;\n string pathFile = System.IO.Path.GetFileName(fileName);\n\n try\n {\n uploadedFile.SaveAs(Server.MapPath(\"../picnic/\") + pathFile);\n }\n catch (Exception exp)\n {\n //catch exception here\n }\n\n try\n {\n Bitmap uploadedimage = new Bitmap(uploadedFile.PostedFile.InputStream);\n\n e.Values[\"ImageWidth\"] = uploadedimage.Width.ToString();\n e.Values[\"ImageHeight\"] = uploadedimage.Height.ToString();\n // Make output File Name\n char[] splitter = { '.' };\n string[] splitFile = pathFile.Split(splitter);\n string OutputFilename = splitFile[0] + \"s\";\n\n System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);\n System.Drawing.Image thumbImage = uploadedimage.GetThumbnailImage(74, 54, myCallback, IntPtr.Zero);\n thumbImage.Save(Server.MapPath(\"../picnic/\") + OutputFilename + \".jpg\");\n e.Values[\"Thumbnail\"] = \"./picnic/\" + OutputFilename + \".jpg\";\n }\n catch (Exception ex)\n {\n //catch exception here\n }\n\n e.Values[\"Pic\"] = \"./picnic/\" + pathFile;\n e.Values[\"Url\"] = \"./picnic/\" + pathFile;\n e.Values[\"dateEntered\"] = DateTime.Now.ToString();\n }\n }\n\n public bool ThumbnailCallback()\n {\n return false;\n }\n}\n</code></pre>\n\n<p>This uses a FileUpload and a FormView to insert. Then I use the <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx\" rel=\"nofollow noreferrer\">GetThumnailImage()</a> method provided in System.Drawing.Imaging. You can enter any Width and Height values and it will shrink/stretch accordingly.</p>\n\n<pre><code>uploadedimage.GetThumbnailImage(W, H, myCallback, IntPtr.Zero);\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 254812, "author": "Kyle B.", "author_id": 6158, "author_profile": "https://Stackoverflow.com/users/6158", "pm_score": 0, "selected": false, "text": "<p>You could resize before sending to the server using an ActiveX control. There is a free ASP.net image uploading component (I believe this is the same one that Facebook actually uses) available here:</p>\n\n<p><a href=\"http://forums.aurigma.com/yaf_postst2145_Image-Uploader-ASPNET-Control.aspx\" rel=\"nofollow noreferrer\">http://forums.aurigma.com/yaf_postst2145_Image-Uploader-ASPNET-Control.aspx</a></p>\n\n<p>Let me know if it works, I am thinking about implementing it in my projects here at work.</p>\n\n<p>Edit: Looks like the wrapper for the object is free, however the actual component itself is going to run you about $200. I confirmed it is the same component Facebook is using though.</p>\n" }, { "answer_id": 266682, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You'll need to use the WebClient class to download the remote image.</p>\n\n<p>After that, then you can resize it...Use DrawImage, not GetThumbnailImage. Make sure you dispose of your bitmap and graphics handles.. (use using{}). Set all quality settings to high.</p>\n\n<p>You might want to take a look at the <a href=\"http://nathanaeljones.com/products/asp-net-image-resizer/\" rel=\"nofollow noreferrer\">source code for my popular image resizer</a> first... It will help you avoid some common trouble areas. </p>\n" }, { "answer_id": 518597, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>//Here is another WAY fox!!! i have actually modify the code from You all. HIHI\n//First, add one textBox and one FileUpload Control, and a button\n\n//paste this in your code behind file... after public partial class admin : System.Web.UI.Page\n\n string OriPath;\n string ImageName;\n\npublic Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)\n {\n Size NewSize;\n double tempval;\n\n if (OriginalHeight &gt; FormatSize &amp;&amp; OriginalWidth &gt; FormatSize)\n {\n if (OriginalHeight &gt; OriginalWidth)\n tempval = FormatSize / Convert.ToDouble(OriginalHeight);\n else\n tempval = FormatSize / Convert.ToDouble(OriginalWidth);\n\n NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));\n }\n else\n NewSize = new Size(OriginalWidth, OriginalHeight); return NewSize;\n } \n\n\n\n//Now, On Button click add the folwing code.\n\nif (FileUpload1.PostedFile != null)\n {\n ImageName = TextBox1.Text+\".jpg\";\n\n\n OriPath = Server.MapPath(\"pix\\\\\") + ImageName;\n\n //Gets the Full Path using Filecontrol1 which points to actual location in the hardisk :)\n\n using (System.Drawing.Image Img = System.Drawing.Image.FromFile(System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName)))\n {\n Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 800);\n\n using (System.Drawing.Image ImgThnail = new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))\n {\n ImgThnail.Save(OriPath, Img.RawFormat);\n ImgThnail.Dispose();\n }\n Img.Dispose();\n }\n}\n\n\n//Enjoy. If any problem,, mail me at [email protected] \n</code></pre>\n" }, { "answer_id": 591108, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>To resize down a image and get smaller sizes just make the changes below</p>\n\n<pre><code> bmpOut = new Bitmap(lnNewWidth, lnNewHeight, **System.Drawing.Imaging.PixelFormat.Format24bppRgb**);\n\n Graphics g = Graphics.FromImage(bmpOut);\n</code></pre>\n\n<p>as you above a set the imagem to Format24bppRgb PixelFormat.</p>\n\n<p>and when you save the file, you set the ImageFormat also. Like this:</p>\n\n<pre><code>bmpOut.Save(PathImage, System.Drawing.Imaging.ImageFormat.Jpeg);\n</code></pre>\n" }, { "answer_id": 2312783, "author": "Tim Meers", "author_id": 90764, "author_profile": "https://Stackoverflow.com/users/90764", "pm_score": 1, "selected": false, "text": "<p>You can use this, it does a dandy job for me. But it does not handle low res images well for me. Thankfully I down use to many of them. Just sent it the image <code>byte[]</code> and the expected output and you'll be good to go. </p>\n\n<pre><code>public static byte[] ResizeImageFile(byte[] imageFile, int targetSize) \n{ \n using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) \n { \n Size newSize = CalculateDimensions(oldImage.Size, targetSize); \n\n using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) \n { \n newImage.SetResolution(oldImage.HorizontalResolution, oldImage.VerticalResolution); \n using (Graphics canvas = Graphics.FromImage(newImage)) \n { \n canvas.SmoothingMode = SmoothingMode.AntiAlias; \n canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; \n canvas.PixelOffsetMode = PixelOffsetMode.HighQuality; \n canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize)); \n MemoryStream m = new MemoryStream(); \n newImage.Save(m, ImageFormat.Jpeg); \n return m.GetBuffer(); \n } \n } \n\n } \n} \n\nprivate static Size CalculateDimensions(Size oldSize, int targetSize) \n{ \n Size newSize = new Size(); \n if (oldSize.Width &gt; oldSize.Height) \n { \n newSize.Width = targetSize; \n newSize.Height = (int)(oldSize.Height * (float)targetSize / (float)oldSize.Width); \n } \n else \n { \n newSize.Width = (int)(oldSize.Width * (float)targetSize / (float)oldSize.Height); \n newSize.Height = targetSize; \n } \n return newSize; \n} \n</code></pre>\n" }, { "answer_id": 2316818, "author": "Naeem Sarfraz", "author_id": 40986, "author_profile": "https://Stackoverflow.com/users/40986", "pm_score": 2, "selected": false, "text": "<p>Another approach would to allow the user to adjust the size in the browser and then resize the image as described in other answers.</p>\n\n<p>So take a look at this solution which allows you to <a href=\"http://www.mikesdotnetting.com/Article/95/Upload-and-Crop-Images-with-jQuery-JCrop-and-ASP.NET\" rel=\"nofollow noreferrer\">upload and crop images with jQuery, jCrop &amp; ASP.NET</a>.</p>\n" }, { "answer_id": 9289380, "author": "Deepak Sahu", "author_id": 1210688, "author_profile": "https://Stackoverflow.com/users/1210688", "pm_score": -1, "selected": false, "text": "<pre><code>private void ResizeImage(FileUpload fileUpload)\n{\n // First we check to see if the user has selected a file\n if (fileUpload.HasFile)\n {\n // Find the fileUpload control\n string filename = fileUpload.FileName;\n\n // Check if the directory we want the image uploaded to actually exists or not\n if (!Directory.Exists(MapPath(@\"Uploaded-Files\")))\n {\n // If it doesn't then we just create it before going any further\n Directory.CreateDirectory(MapPath(@\"Uploaded-Files\"));\n }\n // Specify the upload directory\n string directory = Server.MapPath(@\"Uploaded-Files\\\");\n\n // Create a bitmap of the content of the fileUpload control in memory\n Bitmap originalBMP = new Bitmap(fileUpload.FileContent);\n\n // Calculate the new image dimensions\n int origWidth = originalBMP.Width;\n int origHeight = originalBMP.Height;\n int sngRatio = origWidth / origHeight;\n int newWidth = 100;\n int newHeight = newWidth / sngRatio;\n\n // Create a new bitmap which will hold the previous resized bitmap\n Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);\n\n // Create a graphic based on the new bitmap\n Graphics oGraphics = Graphics.FromImage(newBMP);\n // Set the properties for the new graphic file\n oGraphics.SmoothingMode = SmoothingMode.AntiAlias; \n oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n\n // Draw the new graphic based on the resized bitmap\n oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);\n // Save the new graphic file to the server\n newBMP.Save(directory + \"tn_\" + filename);\n\n // Once finished with the bitmap objects, we deallocate them.\n originalBMP.Dispose();\n newBMP.Dispose();\n oGraphics.Dispose();\n\n // Write a message to inform the user all is OK\n label.Text = \"File Name: &lt;b style='color: red;'&gt;\" + filename + \"&lt;/b&gt;&lt;br&gt;\";\n label.Text += \"Content Type: &lt;b style='color: red;'&gt;\" + fileUpload.PostedFile.ContentType + \"&lt;/b&gt;&lt;br&gt;\";\n label.Text += \"File Size: &lt;b style='color: red;'&gt;\" + fileUpload.PostedFile.ContentLength.ToString() + \"&lt;/b&gt;\";\n\n // Display the image to the user\n Image1.Visible = true;\n Image1.ImageUrl = @\"Uploaded-Files/tn_\" + filename;\n }\n else\n {\n label.Text = \"No file uploaded!\";\n }\n}\n</code></pre>\n" }, { "answer_id": 11877291, "author": "techshaan", "author_id": 1468758, "author_profile": "https://Stackoverflow.com/users/1468758", "pm_score": 0, "selected": false, "text": "<p>The uploading of the image file is performed by ASP.NET 4.0 Client Callbacks. If you are not familiar with client callbacks then I suggest that you take a look at ASP.Net AJAX Control Toolkit AsyncFileUpload Control without page refresh or PostBack in ASP.Net Web Page or ASP.Net AJAX Update Panel. The callback is fired as soon as the file is selected by the user using the file field control.</p>\n" }, { "answer_id": 12001997, "author": "Satinder singh", "author_id": 1192188, "author_profile": "https://Stackoverflow.com/users/1192188", "pm_score": 2, "selected": false, "text": "<p>This is how I did in my project, based on your condition <em><strong>(height/width)</strong></em> you can change the parameter ie(MaxHeight)</p>\n<pre><code> public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)\n {\n var ratio = (double)maxHeight / image.Height;\n \n var newWidth = (int)(image.Width * ratio);\n var newHeight = (int)(image.Height * ratio);\n \n var newImage = new Bitmap(newWidth, newHeight);\n using (var g = Graphics.FromImage(newImage))\n {\n g.DrawImage(image, 0, 0, newWidth, newHeight);\n }\n return newImage;\n }\n</code></pre>\n<hr />\n<p><strong>On Button click:</strong></p>\n<pre><code>protected void Button1_Click(object sender, EventArgs e)\n{\n lblmsg.Text=&quot;&quot;;\n if ((File1.PostedFile != null) &amp;&amp; (File1.PostedFile.ContentLength &gt; 0))\n {\n Guid uid = Guid.NewGuid();\n string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);\n string SaveLocation = Server.MapPath(&quot;LogoImagesFolder&quot;) + &quot;\\\\&quot; + uid+fn;\n try\n {\n string fileExtention = File1.PostedFile.ContentType;\n int fileLenght = File1.PostedFile.ContentLength;\n if (fileExtention == &quot;image/png&quot; || fileExtention == &quot;image/jpeg&quot; || fileExtention == &quot;image/x-png&quot;)\n {\n if (fileLenght &lt;= 1048576)\n {\n System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);\n System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);\n objImage.Save(SaveLocation,ImageFormat.Png);\n lblmsg.Text = &quot;The file has been uploaded.&quot;;\n lblmsg.Style.Add(&quot;Color&quot;, &quot;Green&quot;);\n }\n else \n {\n lblmsg.Text = &quot;Image size cannot be more then 1 MB.&quot;;\n lblmsg.Style.Add(&quot;Color&quot;, &quot;Red&quot;);\n }\n }\n else {\n lblmsg.Text = &quot;Invaild Format!&quot;;\n lblmsg.Style.Add(&quot;Color&quot;, &quot;Red&quot;);\n }\n }\n catch (Exception ex)\n {\n lblmsg.Text= &quot;Error: &quot; + ex.Message;\n lblmsg.Style.Add(&quot;Color&quot;, &quot;Red&quot;);\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 21814242, "author": "Rajib Chy", "author_id": 3301985, "author_profile": "https://Stackoverflow.com/users/3301985", "pm_score": 2, "selected": false, "text": "<p>How to resize &amp; Upload Image only for .jpg Extensions : <br/>\nIn upload.aspx page </p>\n\n<pre><code> &lt;asp:FileUpload ID=\"ProductImage\" runat=\"server\"/&gt;\n &lt;asp:Button ID=\"Button1\" runat=\"server\" OnClick=\"Button1_Click\" Text=\"Upload\" /&gt;\n &lt;asp:TextBox runat=\"server\" ID=\"txtProductName\" CssClass=\"form-control\" /&gt;\n &lt;asp:RequiredFieldValidator runat=\"server\" ControlToValidate=\"txtProductName\" ErrorMessage=\"The Product name field is required.\" /&gt;\n</code></pre>\n\n<p>And upload.aspx.cs<br/>\nFor resize</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Created By Rajib Chowdhury Mob. 01766-306306; Web: http://onlineshoping.somee.com/\n/// Complete This Page Coding On January 05, 2014\n/// Programing C# By Visual Studio 2013 For Web\n/// Dot Net Version 4.5\n/// Database Virsion MSSQL Server 2005\n/// &lt;/summary&gt;\n public bool ResizeImageAndUpload(System.IO.FileStream newFile, string folderPathAndFilenameNoExtension, double maxHeight, double maxWidth)\n {\n try\n {\n // Declare variable for the conversion\n float ratio;\n // Create variable to hold the image\n System.Drawing.Image thisImage = System.Drawing.Image.FromStream(newFile);\n // Get height and width of current image\n int width = (int)thisImage.Width;\n int height = (int)thisImage.Height;\n // Ratio and conversion for new size\n if (width &gt; maxWidth)\n {\n ratio = (float)width / (float)maxWidth;\n width = (int)(width / ratio);\n height = (int)(height / ratio);\n }\n // Ratio and conversion for new size\n if (height &gt; maxHeight)\n {\n ratio = (float)height / (float)maxHeight;\n height = (int)(height / ratio);\n width = (int)(width / ratio);\n }\n // Create \"blank\" image for drawing new image\n Bitmap outImage = new Bitmap(width, height);\n Graphics outGraphics = Graphics.FromImage(outImage);\n SolidBrush sb = new SolidBrush(System.Drawing.Color.White);\n // Fill \"blank\" with new sized image\n outGraphics.FillRectangle(sb, 0, 0, outImage.Width, outImage.Height);\n outGraphics.DrawImage(thisImage, 0, 0, outImage.Width, outImage.Height);\n sb.Dispose();\n outGraphics.Dispose();\n thisImage.Dispose();\n // Save new image as jpg\n outImage.Save(Server.MapPath(folderPathAndFilenameNoExtension + \".jpg\"), System.Drawing.Imaging.ImageFormat.Jpeg);\n outImage.Dispose();\n return true;\n }\n catch (Exception)\n {\n return false;\n }\n }\n</code></pre>\n\n<p>And Button1_Click Event</p>\n\n<pre><code> string filePath = \"~\\\\Image\\\\\";//your normal image path\n if (Page.IsValid)\n {\n HttpPostedFile myFile = ProductImage.PostedFile;//Get Slected Image\n int nFileLen = myFile.ContentLength;//Get slected Image Size\n string myimag = txtProductName.Text;//Get user input image name\n Guid ImageName = Guid.NewGuid();//get unique id\n if ((myFile != null) &amp;&amp; (nFileLen &gt; 1048576))\n {\n LabelAddStatus.Text = \"minimum size exceed\"; //If file image size 1 MB above\n }\n else\n {\n try\n {\n if (ProductImage.HasFile)\n {\n String fileExtension = System.IO.Path.GetExtension(ProductImage.FileName).ToLower();\n String[] allowedExtensions = { \".jpg\" };//Declare For Allowed Extension\n for (int i = 0; i &lt; allowedExtensions.Length; i++)\n {\n if (fileExtension == allowedExtensions[i])\n {\n // Read file into a data stream\n byte[] myData = new Byte[nFileLen];\n myFile.InputStream.Read(myData, 0, nFileLen);\n myFile.InputStream.Dispose();\n // Save the stream to disk as temporary file. make sure the path is unique!\n System.IO.FileStream newFile\n = new System.IO.FileStream(Server.MapPath(filePath + \"_temp.jpg\"),\n System.IO.FileMode.Create);\n newFile.Write(myData, 0, myData.Length);\n bool success = ResizeImageAndUpload(newFile, filePath + (\"thumbs\"+myimag + ImageName), 100, 100);//Save image your thumb image path\n success = ResizeImageAndUpload(newFile, filePath + (myimag + ImageName), 768, 1024);//Save image your normal image path\n //delete the temp file.\n newFile.Close();\n System.IO.File.Delete(Server.MapPath(filePath + \"_temp.jpg\"));\n LabelAddStatus.Text = \"File uploaded.\";\n }\n else\n {\n LabelAddStatus.Text = \"Unable to accept file type..\";\n }\n }\n }\n }\n catch (Exception)\n {\n //No Exception Message\n }\n }\n }\n</code></pre>\n\n<p>Thanks...</p>\n" }, { "answer_id": 33045949, "author": "Loai Tayem", "author_id": 4718109, "author_profile": "https://Stackoverflow.com/users/4718109", "pm_score": 0, "selected": false, "text": "<pre><code>public string ResizeImageAndSave(int Width, int Height, string imageUrl, string destPath)\n {\n System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imageUrl);\n double widthRatio = (double)fullSizeImg.Width / (double)Width;\n double heightRatio = (double)fullSizeImg.Height / (double)Height;\n double ratio = Math.Max(widthRatio, heightRatio);\n int newWidth = (int)(fullSizeImg.Width / ratio);\n int newHeight = (int)(fullSizeImg.Height / ratio);\n //System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);\n System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);\n //DateTime MyDate = DateTime.Now;\n //String MyString = MyDate.ToString(\"ddMMyyhhmmss\") + imageUrl.Substring(imageUrl.LastIndexOf(\".\"));\n thumbNailImg.Save(destPath, ImageFormat.Jpeg);\n thumbNailImg.Dispose();\n return \"\";\n }\n public bool ThumbnailCallback() { return false; }\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29982/" ]
I have an aspx page which will upload images to server harddisk from client pc But now i need to change my program in such a way that it would allow me to resize the image while uploading. Does anyone has any idea on this ? I couldnt not find such properties/methods with Input file server control Any one there to guide me ?
Once the file has been saved to the server you can use code like this to resize. This code will take care of length/width ratio on the resize. ``` public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight) { System.Drawing.Bitmap bmpOut = null; try { Bitmap loBMP = new Bitmap(lcFilename); ImageFormat loFormat = loBMP.RawFormat; decimal lnRatio; int lnNewWidth = 0; int lnNewHeight = 0; if (loBMP.Width < lnWidth && loBMP.Height < lnHeight) return loBMP; if (loBMP.Width > loBMP.Height) { lnRatio = (decimal)lnWidth / loBMP.Width; lnNewWidth = lnWidth; decimal lnTemp = loBMP.Height * lnRatio; lnNewHeight = (int)lnTemp; } else { lnRatio = (decimal)lnHeight / loBMP.Height; lnNewHeight = lnHeight; decimal lnTemp = loBMP.Width * lnRatio; lnNewWidth = (int)lnTemp; } bmpOut = new Bitmap(lnNewWidth, lnNewHeight); Graphics g = Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight); g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight); loBMP.Dispose(); } catch { return null; } return bmpOut; } ```
254,438
<p>every time i create a FileInfo object and access it's lastaccesstime property, it's always a few minutes off. the file property window remains constant, however the application shows that it is usually a few minutes after the property window time.</p> <p>Also, i noticed that if i drag the file to the cmd window to pass the filename as an argument, the access time updates most of the time, but not always.</p> <p>What could be causing this ?</p> <p>below is an example:</p> <pre><code>static void Main(string[] args) { if (args.Length &gt; 0) { FileInfo fi = new FileInfo(args[0].ToString()); Console.WriteLine(args[0]); if (fi.Exists) { Console.Write("Current: " + DateTime.Now + "\n"); Console.Write("LAT: " + fi.LastAccessTime + "\n"); Console.Write("LWT: " + fi.LastWriteTime + "\n"); Console.Write("CT: " + fi.CreationTime + "\n"); } Console.ReadKey(); } } </code></pre> <p><a href="http://img407.imageshack.us/img407/4728/propertiesox6.png" rel="nofollow noreferrer">alt text http://img407.imageshack.us/img407/4728/propertiesox6.png</a> <a href="http://img380.imageshack.us/img380/7752/appgt0.png" rel="nofollow noreferrer">alt text http://img380.imageshack.us/img380/7752/appgt0.png</a></p>
[ { "answer_id": 254508, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "<p>Hmm, possibly <a href=\"http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.lastaccesstime.aspx\" rel=\"nofollow noreferrer\">this from MSDN</a>:</p>\n\n<blockquote>\n <p>When first called, FileSystemInfo\n calls Refresh and returns the cached\n information on APIs to get attributes\n and so on. On subsequent calls, you\n must call Refresh to get the latest\n copy of the information.</p>\n</blockquote>\n\n<p>But you are seeing the LAT always being a few minutes in the [future|past]?</p>\n" }, { "answer_id": 255363, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms724290(VS.85).aspx\" rel=\"nofollow noreferrer\">The MSDN article with basic info about file times</a> has this to say about file time resolution and Last Access times:</p>\n\n<blockquote>\n <p>For example, on FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). NTFS delays updates to the last access time for a file by up to one hour after the last access.</p>\n</blockquote>\n\n<p>This would imply that on both FAT and NTFS, the Last Write Time will generally not be very precise, although I'm not sure the exact values they quote are correct.</p>\n" }, { "answer_id": 257262, "author": "Brent Rockwood", "author_id": 31253, "author_profile": "https://Stackoverflow.com/users/31253", "pm_score": 3, "selected": true, "text": "<p>In my experience, last access time is notoriously unreliable. According to <a href=\"http://technet.microsoft.com/en-us/library/cc781134.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/cc781134.aspx</a>... </p>\n\n<blockquote>\n <p>The Last Access Time on disk is not always current because NTFS looks for a one-hour interval before forcing the Last Access Time updates to disk. NTFS also delays writing the Last Access Time to disk when users or programs perform read-only operations on a file or folder, such as listing the folder’s contents or reading (but not changing) a file in the folder.</p>\n</blockquote>\n\n<p>Apparently, the in-memory copy will be correct, but in my experience, you may get a cached value which may be out of date. Also, note that last access time may be turned off by the user, and is turned off by default in Vista and 2008.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33082/" ]
every time i create a FileInfo object and access it's lastaccesstime property, it's always a few minutes off. the file property window remains constant, however the application shows that it is usually a few minutes after the property window time. Also, i noticed that if i drag the file to the cmd window to pass the filename as an argument, the access time updates most of the time, but not always. What could be causing this ? below is an example: ``` static void Main(string[] args) { if (args.Length > 0) { FileInfo fi = new FileInfo(args[0].ToString()); Console.WriteLine(args[0]); if (fi.Exists) { Console.Write("Current: " + DateTime.Now + "\n"); Console.Write("LAT: " + fi.LastAccessTime + "\n"); Console.Write("LWT: " + fi.LastWriteTime + "\n"); Console.Write("CT: " + fi.CreationTime + "\n"); } Console.ReadKey(); } } ``` [alt text http://img407.imageshack.us/img407/4728/propertiesox6.png](http://img407.imageshack.us/img407/4728/propertiesox6.png) [alt text http://img380.imageshack.us/img380/7752/appgt0.png](http://img380.imageshack.us/img380/7752/appgt0.png)
In my experience, last access time is notoriously unreliable. According to <http://technet.microsoft.com/en-us/library/cc781134.aspx>... > > The Last Access Time on disk is not always current because NTFS looks for a one-hour interval before forcing the Last Access Time updates to disk. NTFS also delays writing the Last Access Time to disk when users or programs perform read-only operations on a file or folder, such as listing the folder’s contents or reading (but not changing) a file in the folder. > > > Apparently, the in-memory copy will be correct, but in my experience, you may get a cached value which may be out of date. Also, note that last access time may be turned off by the user, and is turned off by default in Vista and 2008.
254,441
<p>I'm having problems with Iterator.remove() called on a HashSet.</p> <p>I've a Set of time stamped objects. Before adding a new item to the Set, I loop through the set, identify an old version of that data object and remove it (before adding the new object). the timestamp is included in hashCode and equals(), but not equalsData().</p> <pre><code>for (Iterator&lt;DataResult&gt; i = allResults.iterator(); i.hasNext();) { DataResult oldData = i.next(); if (data.equalsData(oldData)) { i.remove(); break; } } allResults.add(data) </code></pre> <p>The odd thing is that i.remove() silently fails (no exception) for some of the items in the set. I've verified</p> <ul> <li><p>The line i.remove() is actually called. I can call it from the debugger directly at the breakpoint in Eclipse and it still fails to change the state of Set</p></li> <li><p>DataResult is an immutable object so it can't have changed after being added to the set originally.</p></li> <li><p>The equals and hashCode() methods use @Override to ensure they are the correct methods. Unit tests verify these work. </p></li> <li><p>This also fails if I just use a for statement and Set.remove instead. (e.g. loop through the items, find the item in the list, then call Set.remove(oldData) after the loop).</p></li> <li><p>I've tested in JDK 5 and JDK 6.</p></li> </ul> <p>I thought I must be missing something basic, but after spending some significant time on this my colleague and I are stumped. Any suggestions for things to check?</p> <p>EDIT:</p> <p>There have been questions - is DataResult truly immutable. Yes. There are no setters. And when the Date object is retrieved (which is a mutable object), it is done by creating a copy.</p> <pre><code>public Date getEntryTime() { return DateUtil.copyDate(entryTime); } public static Date copyDate(Date date) { return (date == null) ? null : new Date(date.getTime()); } </code></pre> <p>FURTHER EDIT (some time later): For the record -- DataResult was not immutable! It referenced an object which had a hashcode which changed when persisted to the database (bad practice, I know). It turned out that if a DataResult was created with a transient subobject, and the subobject was persisted, the DataResult hashcode was changed.</p> <p>Very subtle -- I looked at this many times and didn't notice the lack of immutability.</p>
[ { "answer_id": 254480, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "<p>Have you tried something like</p>\n\n<pre><code>boolean removed = allResults.remove(oldData)\nif (!removed) // COMPLAIN BITTERLY!\n</code></pre>\n\n<p>In other words, remove the object from the Set and break the loop. That won't cause the <code>Iterator</code> to complain. I don't think this is a long term solution but would probably give you some information about the <code>hashCode</code>, <code>equals</code> and <code>equalsData</code> methods</p>\n" }, { "answer_id": 255488, "author": "Zach Scrivena", "author_id": 20029, "author_profile": "https://Stackoverflow.com/users/20029", "pm_score": -1, "selected": false, "text": "<p>If there are two entries with the same data, only one of them is replaced... have you accounted for that? And just in case, have you tried another collection data structure that doesn't use a hashcode, say a List?</p>\n" }, { "answer_id": 255490, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 2, "selected": false, "text": "<p>Are you absolutely certain that DataResult is immutable? What is the type of the timestamp? If it's a <code>java.util.Date</code> are you making copies of it when you're initializing the DataResult? Keep in mind that <code>java.util.Date</code> is mutable.</p>\n\n<p>For instance:</p>\n\n<pre><code>Date timestamp = new Date();\nDataResult d = new DataResult(timestamp);\nSystem.out.println(d.getTimestamp());\ntimestamp.setTime(System.currentTimeMillis());\nSystem.out.println(d.getTimestamp());\n</code></pre>\n\n<p>Would print two different times.</p>\n\n<p>It would also help if you could post some source code.</p>\n" }, { "answer_id": 255548, "author": "Spencer Kormos", "author_id": 8528, "author_profile": "https://Stackoverflow.com/users/8528", "pm_score": 3, "selected": false, "text": "<p>Under the covers, HashSet uses HashMap, which calls HashMap.removeEntryForKey(Object) when either HashSet.remove(Object) or Iterator.remove() is called. This method uses both hashCode() and equals() to validate that it is removing the proper object from the collection.</p>\n\n<p>If both Iterator.remove() and HashSet.remove(Object) are not working, then something is definitely wrong with your equals() or hashCode() methods. Posting the code for these would be helpful in diagnosis of your issue.</p>\n" }, { "answer_id": 255587, "author": "David", "author_id": 32593, "author_profile": "https://Stackoverflow.com/users/32593", "pm_score": -1, "selected": false, "text": "<p>I'm not up to speed on my Java, but I know that you can't remove an item from a collection when you are iterating over that collection in .NET, although .NET will throw an exception if it catches this. Could this be the problem?</p>\n" }, { "answer_id": 256105, "author": "Will Glass", "author_id": 32978, "author_profile": "https://Stackoverflow.com/users/32978", "pm_score": 2, "selected": false, "text": "<p>Thanks for all the help. I suspect the problem must be with equals() and hashCode() as suggested by spencerk. I did check those in my debugger and with unit tests, but I've got to be missing something. </p>\n\n<p>I ended up doing a workaround-- copying all the items except one to a new Set. For kicks, I used Apache Commons CollectionUtils.</p>\n\n<pre><code> Set&lt;DataResult&gt; tempResults = new HashSet&lt;DataResult&gt;();\n CollectionUtils.select(allResults, \n new Predicate()\n {\n public boolean evaluate(Object oldData)\n {\n return !data.equalsData((DataResult) oldData);\n }\n }\n , tempResults);\n allResults = tempResults;\n</code></pre>\n\n<p>I'm going to stop here-- too much work to simplify down to a simple test case. But the help is miuch appreciated.</p>\n" }, { "answer_id": 256247, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 7, "selected": true, "text": "<p>I was very curious about this one still, and wrote the following test:</p>\n\n<pre><code>import java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class HashCodeTest {\n private int hashCode = 0;\n\n @Override public int hashCode() {\n return hashCode ++;\n }\n\n public static void main(String[] args) {\n Set&lt;HashCodeTest&gt; set = new HashSet&lt;HashCodeTest&gt;();\n\n set.add(new HashCodeTest());\n System.out.println(set.size());\n for (Iterator&lt;HashCodeTest&gt; iter = set.iterator();\n iter.hasNext();) {\n iter.next();\n iter.remove();\n }\n System.out.println(set.size());\n }\n}\n</code></pre>\n\n<p>which results in:</p>\n\n<pre><code>1\n1\n</code></pre>\n\n<p>If the hashCode() value of an object has changed since it was added to the HashSet, it seems to render the object unremovable.</p>\n\n<p>I'm not sure if that's the problem you're running into, but it's something to look into if you decide to re-visit this.</p>\n" }, { "answer_id": 259352, "author": "Chris Kessel", "author_id": 29734, "author_profile": "https://Stackoverflow.com/users/29734", "pm_score": 1, "selected": false, "text": "<p>It's almost certainly the case the hashcodes don't match for the old and new data that are \"equals()\". I've run into this kind of thing before and you essentially end up spewing hashcodes for every object and the string representation and trying to figure out why the mismatch is happening.</p>\n\n<p>If you're comparing items pre/post database, sometimes it loses the nanoseconds (depending on your DB column type) which can cause hashcodes to change.</p>\n" }, { "answer_id": 28787298, "author": "Tomer Shalev", "author_id": 2779007, "author_profile": "https://Stackoverflow.com/users/2779007", "pm_score": 2, "selected": false, "text": "<p>You should all be careful of any Java Collection that fetches its children by hashcode, in the case that its child type's hashcode depends on its mutable state. An example:</p>\n\n<pre><code>HashSet&lt;HashSet&lt;?&gt;&gt; or HashSet&lt;AbstaractSet&lt;?&gt;&gt; or HashMap variant:\n</code></pre>\n\n<p>HashSet retrieves an item by its hashCode, but its item type\nis a HashSet, and hashSet.hashCode depends on its item's state.</p>\n\n<p>Code for that matter:</p>\n\n<pre><code>HashSet&lt;HashSet&lt;String&gt;&gt; coll = new HashSet&lt;HashSet&lt;String&gt;&gt;();\nHashSet&lt;String&gt; set1 = new HashSet&lt;String&gt;();\nset1.add(\"1\");\ncoll.add(set1);\nprint(set1.hashCode()); //---&gt; will output X\nset1.add(\"2\");\nprint(set1.hashCode()); //---&gt; will output Y\ncoll.remove(set1) // WILL FAIL TO REMOVE (SILENTLY)\n</code></pre>\n\n<p>Reason being is HashSet's remove method uses HashMap and it identifies keys by hashCode, while AbstractSet's hashCode is dynamic and depends upon the mutable properties of itself.</p>\n" }, { "answer_id": 63238523, "author": "Lance Wang", "author_id": 14044914, "author_profile": "https://Stackoverflow.com/users/14044914", "pm_score": 0, "selected": false, "text": "<p>The Java HashSet has an issue in &quot;remove()&quot; method. Check the link below. I switched to TreeSet and it works fine. But I need the O(1) time complexity.</p>\n<p><a href=\"https://bugs.openjdk.java.net/browse/JDK-8154740\" rel=\"nofollow noreferrer\">https://bugs.openjdk.java.net/browse/JDK-8154740</a></p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32978/" ]
I'm having problems with Iterator.remove() called on a HashSet. I've a Set of time stamped objects. Before adding a new item to the Set, I loop through the set, identify an old version of that data object and remove it (before adding the new object). the timestamp is included in hashCode and equals(), but not equalsData(). ``` for (Iterator<DataResult> i = allResults.iterator(); i.hasNext();) { DataResult oldData = i.next(); if (data.equalsData(oldData)) { i.remove(); break; } } allResults.add(data) ``` The odd thing is that i.remove() silently fails (no exception) for some of the items in the set. I've verified * The line i.remove() is actually called. I can call it from the debugger directly at the breakpoint in Eclipse and it still fails to change the state of Set * DataResult is an immutable object so it can't have changed after being added to the set originally. * The equals and hashCode() methods use @Override to ensure they are the correct methods. Unit tests verify these work. * This also fails if I just use a for statement and Set.remove instead. (e.g. loop through the items, find the item in the list, then call Set.remove(oldData) after the loop). * I've tested in JDK 5 and JDK 6. I thought I must be missing something basic, but after spending some significant time on this my colleague and I are stumped. Any suggestions for things to check? EDIT: There have been questions - is DataResult truly immutable. Yes. There are no setters. And when the Date object is retrieved (which is a mutable object), it is done by creating a copy. ``` public Date getEntryTime() { return DateUtil.copyDate(entryTime); } public static Date copyDate(Date date) { return (date == null) ? null : new Date(date.getTime()); } ``` FURTHER EDIT (some time later): For the record -- DataResult was not immutable! It referenced an object which had a hashcode which changed when persisted to the database (bad practice, I know). It turned out that if a DataResult was created with a transient subobject, and the subobject was persisted, the DataResult hashcode was changed. Very subtle -- I looked at this many times and didn't notice the lack of immutability.
I was very curious about this one still, and wrote the following test: ``` import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; public class HashCodeTest { private int hashCode = 0; @Override public int hashCode() { return hashCode ++; } public static void main(String[] args) { Set<HashCodeTest> set = new HashSet<HashCodeTest>(); set.add(new HashCodeTest()); System.out.println(set.size()); for (Iterator<HashCodeTest> iter = set.iterator(); iter.hasNext();) { iter.next(); iter.remove(); } System.out.println(set.size()); } } ``` which results in: ``` 1 1 ``` If the hashCode() value of an object has changed since it was added to the HashSet, it seems to render the object unremovable. I'm not sure if that's the problem you're running into, but it's something to look into if you decide to re-visit this.
254,458
<p><strong>Update</strong></p> <p><em>Got it! See my solution (fifth comment)</em></p> <p>Here is my problem:</p> <p>I have created a small binary called "jail" and in /etc/password I have made it the default shell for a test user.</p> <p>Here is the -- simplified -- source code:</p> <pre><code>#define HOME "/home/user" #define SHELL "/bin/bash" ... if(chdir(HOME) || chroot(HOME)) return -1; ... char *shellargv[] = { SHELL, "-login", "-rcfile", "/bin/myscript", 0 }; execvp(SHELL, shellargv); </code></pre> <p>Well, no matter how hard I try, it seems that, when my test user logs in, <em>/bin/myscript</em> will never be sourced. Similarly, if I drop a <code>.bashrc</code> file in user's home directory, it will be ignored as well.</p> <p>Why would bash snob these guys?</p> <p>--</p> <p>Some precisions, not necessarily relevant, but to clear out some of the points made in the comments:</p> <ul> <li>The 'jail' binary is actually suid, thus allowing it to chroot() successfully. </li> <li>I have used 'ln' to make the appropriate binaries available - my jail cell is nicely padded :)</li> <li>The issue does not seem to be with chrooting the user...something else is remiss.</li> </ul>
[ { "answer_id": 254467, "author": "dexedrine", "author_id": 20266, "author_profile": "https://Stackoverflow.com/users/20266", "pm_score": 2, "selected": false, "text": "<p>The shell isn't interactive. Try adding -i to the list of arguments.</p>\n" }, { "answer_id": 254529, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>As Jason C says, the exec'ed shell isn't interactive.</p>\n\n<p>His solution will force the shell to be interactive if it accepts <code>-i</code> to mean that (and bash does):</p>\n\n<pre><code>char *shellargv[] = { SHELL, \"-i\", \"-login\", ... };\nexecvp(SHELL, shellargv);\n</code></pre>\n\n<p>I want to add, though, that traditionally a shell will act as a login shell if <code>ARGV[0]</code> begins with a dash.</p>\n\n<pre><code>char *shellargv[] = {\"-\"SHELL, \"-i\", ...};\nexecvp(SHELL, shellargv);\n</code></pre>\n\n<p>Usually, though, Bash will autodetect whether it should run interactively or not. Its failure to in your case may be because of missing <code>/dev/*</code> nodes.</p>\n" }, { "answer_id": 254549, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>By the time your user is logging in and their shell tries to source this file, it's running under their UID. The <code>chroot()</code> system call is only usable by root -- you'll need to be cleverer than this.</p>\n\n<p>Also, chrooting to a user's home directory will make their shell useless, as (unless they have a lot of stuff in there) they won't have access to any binaries. Useful things like <code>ls</code>, for instance.</p>\n" }, { "answer_id": 254563, "author": "Damon Snyder", "author_id": 8243, "author_profile": "https://Stackoverflow.com/users/8243", "pm_score": 2, "selected": false, "text": "<p>I can identify with wanting to do this yourself, but if you haven't already, check out <a href=\"http://www.jmcresearch.com/projects/jail/\" rel=\"nofollow noreferrer\">jail chroot project</a> and <a href=\"http://olivier.sessink.nl/jailkit/index.html#intro\" rel=\"nofollow noreferrer\">jailkit</a> for some drop in tools to create a jail shell. </p>\n" }, { "answer_id": 255002, "author": "Fusion", "author_id": 6253, "author_profile": "https://Stackoverflow.com/users/6253", "pm_score": 1, "selected": false, "text": "<p>Thanks for your help, guys,</p>\n\n<p>I figured it out:</p>\n\n<p>I forgot to <strong>setuid()/setgid()</strong>, chroot(), setuid()/setgid() back, then pass a proper environment using execve()</p>\n\n<p>Oh, and, if I pass no argument to bash, it will source <em>~/.bashrc</em></p>\n\n<p>If I pass \"-l\" if will source <em>/etc/profile</em></p>\n\n<p>Cheers!</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6253/" ]
**Update** *Got it! See my solution (fifth comment)* Here is my problem: I have created a small binary called "jail" and in /etc/password I have made it the default shell for a test user. Here is the -- simplified -- source code: ``` #define HOME "/home/user" #define SHELL "/bin/bash" ... if(chdir(HOME) || chroot(HOME)) return -1; ... char *shellargv[] = { SHELL, "-login", "-rcfile", "/bin/myscript", 0 }; execvp(SHELL, shellargv); ``` Well, no matter how hard I try, it seems that, when my test user logs in, */bin/myscript* will never be sourced. Similarly, if I drop a `.bashrc` file in user's home directory, it will be ignored as well. Why would bash snob these guys? -- Some precisions, not necessarily relevant, but to clear out some of the points made in the comments: * The 'jail' binary is actually suid, thus allowing it to chroot() successfully. * I have used 'ln' to make the appropriate binaries available - my jail cell is nicely padded :) * The issue does not seem to be with chrooting the user...something else is remiss.
The shell isn't interactive. Try adding -i to the list of arguments.
254,461
<p>I have a method with an out parameter that tries to do a type conversion. Basically:</p> <pre><code>public void GetParameterValue(out object destination) { object paramVal = "I want to return this. could be any type, not just string."; destination = null; // default out param to null destination = Convert.ChangeType(paramVal, destination.GetType()); } </code></pre> <p>The problem is that usually someone would call this like:</p> <pre><code>string output; GetParameterValue(output); </code></pre> <p>This will fail because of:</p> <pre><code>destination.GetType() </code></pre> <p>destination is null, so we can't call <code>.GetType()</code> on it. We also can not call:</p> <pre><code>typeof(destination) </code></pre> <p>because destination is a variable name not a type name.</p> <p>So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.</p> <hr> <p>Just to give a bit more info, I am trying to make a utility method that will grab the output parameters of an Oracle stored procedure. The issue is that <code>DbParameter.Value</code> is of type object.</p> <p>What would be ideal would be for the developers to do something like:</p> <pre><code>string val = GetParameterValue("parameterName"); </code></pre> <p>The notable thing is that there is no casting of types. In practice, you don't know the lparam of the "equals", so I went with:</p> <pre><code>string val; GetParameterValue("parameterName", out val); </code></pre> <p>And figured within the method, I would know the destination type of the output variable. I guess that was a bad assumption. As an alternative, I also wrote the method:</p> <pre><code>public T GetParameterValue&lt;T&gt;(string paramName) </code></pre> <p>So the developers can do:</p> <pre><code>string val = GetParameterValue&lt;string&gt;("parameterName"); </code></pre> <p>I find the explicit "string" declaration to be repetitive, especially since in practice, the destination if probably an object property and the oracle data type could change (think ORM):</p> <pre><code>MyObj.SomeProp = GetParameterValue&lt;MyObj.SomeProp.GetType()&gt;("parameterName"); </code></pre> <p>But again, if MyObj.SomeProp is null, that <code>.GetType()</code> call fails. The VM has to know the type of <code>MyObj.SomeProp</code>, even when its null, right? or else how would it catch cast exceptions?</p> <hr> <p>To partially solve my own problem, I can do:</p> <pre><code>MyObj.SomeProp = GetParameterValue&lt;typeof(MyObj).GetField("SomeProp").GetType()&gt;("parameterName"); </code></pre> <p>The whole idea was to not have to explicitly use the Type in more than one place, so that if the data type changes, it only has to be changed in the destination object (<code>MyObj.SomeProp</code>) and in the DB. There has to be a better way...</p>
[ { "answer_id": 254464, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>In your example it would be null of type <code>System.Object</code>.</p>\n\n<p>Does your example even compile? I get a \"cannot convert from 'out string' to 'out object'\" error.</p>\n" }, { "answer_id": 254483, "author": "dub", "author_id": 30022, "author_profile": "https://Stackoverflow.com/users/30022", "pm_score": 2, "selected": false, "text": "<p>The type of your destination variable is always <code>System.Object</code>. You could just return</p>\n\n<pre><code>Convert.ChangeType(paramVal, System.Object).\n</code></pre>\n" }, { "answer_id": 254485, "author": "Jelon", "author_id": 2326, "author_profile": "https://Stackoverflow.com/users/2326", "pm_score": 2, "selected": false, "text": "<p>Currently, you have no way of knowing what gets passed into the method. You can convert it into a generic method like this:</p>\n<pre><code>public void GetParameterValue&lt;T&gt;(out T destination)\n{\n ...\n}\n</code></pre>\n" }, { "answer_id": 254488, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 6, "selected": true, "text": "<blockquote>\n <p>So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.</p>\n</blockquote>\n\n<p>Not necessarily. The best that you can say is that it is an <code>object</code>. A <code>null</code> reference does not point to any storage location, so there is no metadata from which it can make that determination.</p>\n\n<p>The best that you could do is change it to be more generic, as in:</p>\n\n<pre><code>public void GetParameterValue&lt;T&gt;(out T destination)\n{\n object paramVal = \"Blah\";\n destination = default(T);\n destination = Convert.ChangeType(paramVal, typeof(T));\n}\n</code></pre>\n\n<p>The type of <code>T</code> can be inferred, so you shouldn't need to give a type parameter to the method explicitly.</p>\n" }, { "answer_id": 254495, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 0, "selected": false, "text": "<p>I don't think it is possible to get the type when the value is null. Also, since you are calling inside GetParameterValue, the best you could do (when the value is null) is to get the type of the \"destination\" parameter which is \"object\". You <em>might</em> consider passing the Type as a parameter to GetParameterValue where you have more information, such as:</p>\n\n<pre><code>public void GetParameterValue(Type sourceType, out object destination) { //... }\n</code></pre>\n" }, { "answer_id": 254496, "author": "Damian Powell", "author_id": 30321, "author_profile": "https://Stackoverflow.com/users/30321", "pm_score": 4, "selected": false, "text": "<p>It's possible if you don't mind declaring your method as a generic. Try this.</p>\n\n<pre><code>class Program\n{\n public static void GetParameterValue&lt;T&gt;(out T destination)\n {\n Console.WriteLine(\"typeof(T)=\" + typeof(T).Name);\n destination = default(T);\n }\n static void Main(string[] args)\n {\n string s;\n GetParameterValue(out s);\n int i;\n GetParameterValue(out i);\n }\n}\n</code></pre>\n" }, { "answer_id": 254515, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>If there is no instance, there is no instance type.</p>\n\n<p>The best you can do is use the type of the reference, which means if you have an object reference (as in the method in the question), the reference type is object.</p>\n\n<hr>\n\n<p>You probably shouldn't be trying to convert a null instance of one type into a null instance of another type...</p>\n" }, { "answer_id": 254644, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>@Rally25s:</p>\n\n<pre><code>string val;\nGetParameterValue(\"parameterName\", out val);\n</code></pre>\n\n<p>It's unclear from your message (in the answers) what the problem with that one was. If declared as:</p>\n\n<pre><code>void GetParameterValue&lt;T&gt;(string parameterName, out T val) { }\n</code></pre>\n\n<p>Than the call, as you wrote it above, will work (you don't need to specify the type). I'm guess that didn't work for you because you can't use a property as an \"out\" parameter. The way around that is to use both methods:</p>\n\n<pre><code>T GetParameterValue&lt;T&gt;(string parameterName, T ununsed) { }\n</code></pre>\n\n<p>This would be called like this:</p>\n\n<pre><code>MyObj.SomeProp = GetParameterValue(\"parameterName\", MyObj.SomeProp);\n</code></pre>\n\n<p>which is rather kludgey, but not the worse method presented.</p>\n\n<hr>\n\n<p>A different method, which I've used in C++, but haven't tried yet in C#, is to have GetParameterValue() some object of you own design, and then implement a number of implicit cast operators for it.</p>\n\n<pre><code>class ParameterHelper\n{\n private object value;\n public ParameterHelper(object value) { this.value = value; }\n\n public static implicit operator int(ParameterHelper v)\n { return (int) v.value; }\n\n}\nParameterHelper GetParameterValue( string parameterName);\n\nMyObj.SomeProp = GetParameterValue(\"parameterName\");\n</code></pre>\n" }, { "answer_id": 254764, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 0, "selected": false, "text": "<p>At a theoretical level isn't a null really the same as a void pointer in C, which is to say that it holds a memory address and that's it? If so then it is similar to the case of a division by zero in Mathematics where the result is undefined.</p>\n\n<p>One could do the following for this line:</p>\n\n<pre><code>string val = GetParameterValue&lt;string&gt;(\"parameterName\");\n</code></pre>\n\n<p>Just remove that first string and now there isn't the repetition:</p>\n\n<pre><code>var val = GetParameterValue&lt;string&gt;(\"parameterName\");\n</code></pre>\n\n<p>Not necessarily what you are looking for, though there is the question of how does one interpret null?</p>\n" }, { "answer_id": 1187134, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>//**The working answer**\n\n//**based on your discussion eheheheheeh**\n\npublic void s&lt;T&gt;(out T varName)\n{\n if (typeof (T) == typeof(HtmlTable)) \n { \n ////////// \n }\n\n}\n\nprotected void Page_Load(object sender, EventArgs e) \n{\n HtmlTable obj=null ;\n s(out obj); \n}\n</code></pre>\n" }, { "answer_id": 9513472, "author": "Observer", "author_id": 1242244, "author_profile": "https://Stackoverflow.com/users/1242244", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/58918ffs.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/58918ffs.aspx</a></p>\n\n<p>or </p>\n\n<pre><code>private Hashtable propertyTable = new Hashtable();\n\npublic void LoadPropertyTypes()\n{\n Type t = this.GetType();\n\n System.Reflection.MemberInfo[] memberInfo = t.GetMembers();\n\n foreach (System.Reflection.MemberInfo mInfo in memberInfo)\n {\n string[] prop = mInfo.ToString().Split(Convert.ToChar(\" \"));\n propertyTable.Add(prop[1], prop[0]);\n }\n}\npublic string GetMemberType(string propName)\n{\n if (propertyTable.ContainsKey(propName))\n {\n return Convert.ToString(propertyTable[propName]);\n }\n else{\n return \"N/A\";\n }\n}\n</code></pre>\n\n<p>in that way we can use switch to manage different property types.</p>\n" }, { "answer_id": 11803825, "author": "John Beyer", "author_id": 1575257, "author_profile": "https://Stackoverflow.com/users/1575257", "pm_score": 3, "selected": false, "text": "<p>The following extension method returns the type of its parameter <em>as it was declared</em>, regardless of its contents:</p>\n\n<pre><code>using System;\n\nnamespace MyNamespace\n{\n public static class Extensions\n {\n /// &lt;summary&gt;\n /// Gets the declared type of the specified object.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of the object.&lt;/typeparam&gt;\n /// &lt;param name=\"obj\"&gt;The object.&lt;/param&gt;\n /// &lt;returns&gt;\n /// A &lt;see cref=\"Type\"/&gt; object representing type \n /// &lt;typeparamref name=\"T\"/&gt;; i.e., the type of &lt;paramref name=\"obj\"/&gt; \n /// as it was declared. Note that the contents of \n /// &lt;paramref name=\"obj\"/&gt; are irrelevant; if &lt;paramref name=\"obj\"/&gt; \n /// contains an object whose class is derived from \n /// &lt;typeparamref name=\"T\"/&gt;, then &lt;typeparamref name=\"T\"/&gt; is \n /// returned, not the derived type.\n /// &lt;/returns&gt;\n public static Type GetDeclaredType&lt;T&gt;(\n this T obj )\n {\n return typeof( T );\n }\n }\n}\n</code></pre>\n\n<p>Since this is an extension method, its argument can be a null reference, and all of the following works OK:</p>\n\n<pre><code>string myString = \"abc\";\nobject myObj = myString;\nType myObjType = myObj.GetDeclaredType();\n\nstring myNullString = null;\nobject myNullObj = myNullString;\nType myNullObjType = myNullObj.GetDeclaredType();\n</code></pre>\n\n<p>Note that <code>myObjType</code> and <code>myNullObjType</code> will both be set to System.Object, not System.String. </p>\n\n<p>If you actually want the type of obj's contents when it's not null, then change the <code>return</code> line to:</p>\n\n<pre><code>return (obj != null) ? obj.GetType() : typeof( T );\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28278/" ]
I have a method with an out parameter that tries to do a type conversion. Basically: ``` public void GetParameterValue(out object destination) { object paramVal = "I want to return this. could be any type, not just string."; destination = null; // default out param to null destination = Convert.ChangeType(paramVal, destination.GetType()); } ``` The problem is that usually someone would call this like: ``` string output; GetParameterValue(output); ``` This will fail because of: ``` destination.GetType() ``` destination is null, so we can't call `.GetType()` on it. We also can not call: ``` typeof(destination) ``` because destination is a variable name not a type name. So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything. --- Just to give a bit more info, I am trying to make a utility method that will grab the output parameters of an Oracle stored procedure. The issue is that `DbParameter.Value` is of type object. What would be ideal would be for the developers to do something like: ``` string val = GetParameterValue("parameterName"); ``` The notable thing is that there is no casting of types. In practice, you don't know the lparam of the "equals", so I went with: ``` string val; GetParameterValue("parameterName", out val); ``` And figured within the method, I would know the destination type of the output variable. I guess that was a bad assumption. As an alternative, I also wrote the method: ``` public T GetParameterValue<T>(string paramName) ``` So the developers can do: ``` string val = GetParameterValue<string>("parameterName"); ``` I find the explicit "string" declaration to be repetitive, especially since in practice, the destination if probably an object property and the oracle data type could change (think ORM): ``` MyObj.SomeProp = GetParameterValue<MyObj.SomeProp.GetType()>("parameterName"); ``` But again, if MyObj.SomeProp is null, that `.GetType()` call fails. The VM has to know the type of `MyObj.SomeProp`, even when its null, right? or else how would it catch cast exceptions? --- To partially solve my own problem, I can do: ``` MyObj.SomeProp = GetParameterValue<typeof(MyObj).GetField("SomeProp").GetType()>("parameterName"); ``` The whole idea was to not have to explicitly use the Type in more than one place, so that if the data type changes, it only has to be changed in the destination object (`MyObj.SomeProp`) and in the DB. There has to be a better way...
> > So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything. > > > Not necessarily. The best that you can say is that it is an `object`. A `null` reference does not point to any storage location, so there is no metadata from which it can make that determination. The best that you could do is change it to be more generic, as in: ``` public void GetParameterValue<T>(out T destination) { object paramVal = "Blah"; destination = default(T); destination = Convert.ChangeType(paramVal, typeof(T)); } ``` The type of `T` can be inferred, so you shouldn't need to give a type parameter to the method explicitly.
254,486
<p>Some of my MS SQL stored procedures produce messages using the 'print' command. In my Delphi 2007 application, which connects to MS SQL using TADOConnection, how can I view the output of those 'print' commands?</p> <p>Key requirements: 1) I can't run the query more than once; it might be updating things. 2) I need to see the 'print' results even if datasets are returned.</p>
[ { "answer_id": 254504, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 1, "selected": false, "text": "<p>I dont think that is possible.\nYou might use a temp table to dump print statements and return it alongwith results.</p>\n" }, { "answer_id": 254536, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 2, "selected": false, "text": "<p>In .net's connection classes there is an event called InfoMessage. In a handler for this event you can retrieve the InfoMessage (print statements) from the event args.</p>\n\n<p>I believe Delphi has a similar event called \"OnInfoMessage\" that would help you. </p>\n" }, { "answer_id": 255311, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": true, "text": "<p>That was an interesting one...<br>\n<strong>The OnInfoMessage event from the ADOConnection works but the Devil is in the details!</strong></p>\n\n<p><strong>Main points:</strong><br>\nuse CursorLocation = clUseServer instead of the default clUseClient.<br>\nuse Open and not ExecProc with your ADOStoredProc.<br>\nuse NextRecordset from the current one to get the following, but be sure to check you have one open.<br>\nuse SET NOCOUNT = ON in your stored procedure. </p>\n\n<p><strong>SQL side:</strong> your stored procedure</p>\n\n<pre><code>SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nIF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FG_TEST]') AND type in (N'P', N'PC'))\n DROP PROCEDURE [dbo].[FG_TEST]\nGO\n-- =============================================\n-- Author: François\n-- Description: test multi ADO with info\n-- =============================================\nCREATE PROCEDURE FG_TEST\nAS\nBEGIN\n -- SET NOCOUNT ON absolutely NEEDED\n SET NOCOUNT ON;\n\n PRINT '*** start ***'\n\n SELECT 'one' as Set1Field1\n\n PRINT '*** done once ***'\n\n SELECT 'two' as Set2Field2\n\n PRINT '*** done again ***'\n\n SELECT 'three' as Set3Field3\n\n PRINT '***finish ***'\nEND\nGO\n</code></pre>\n\n<p><strong>Delphi side:</strong><br>\nCreate a new VCL Forms Application.<br>\nPut a Memo and a Button in your Form. </p>\n\n<p>Copy the following text, change the Catalog and Data Source and Paste it onto your Form </p>\n\n<pre><code>object ADOConnection1: TADOConnection\n ConnectionString = \n 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security In' +\n 'fo=False;Initial Catalog=xxxYOURxxxDBxxx;Data Source=xxxYOURxxxSERVERxxx'\n CursorLocation = clUseServer\n LoginPrompt = False\n Provider = 'SQLOLEDB.1'\n OnInfoMessage = ADOConnection1InfoMessage\n Left = 24\n Top = 216\nend\nobject ADOStoredProc1: TADOStoredProc\n Connection = ADOConnection1\n CursorLocation = clUseServer\n ProcedureName = 'FG_TEST;1'\n Parameters = &lt;&gt;\n Left = 24\n Top = 264\nend\n</code></pre>\n\n<p>In the OnInfoMessage of the ADOConnection put</p>\n\n<pre><code>Memo1.Lines.Add(Error.Description);\n</code></pre>\n\n<p>For the ButtonClick, paste this code</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nconst\n adStateOpen = $00000001; // or defined in ADOInt\nvar\n I: Integer;\n ARecordSet: _Recordset;\nbegin\n Memo1.Lines.Add('==========================');\n\n ADOStoredProc1.Open; // not ExecProc !!!!!\n\n ARecordSet := ADOStoredProc1.Recordset;\n while Assigned(ARecordSet) do\n begin\n // do whatever with current RecordSet\n while not ADOStoredProc1.Eof do\n begin\n Memo1.Lines.Add(ADOStoredProc1.Fields[0].FieldName + ': ' + ADOStoredProc1.Fields[0].Value);\n ADOStoredProc1.Next;\n end;\n // switch to subsequent RecordSet if any\n ARecordSet := ADOStoredProc1.NextRecordset(I);\n if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) &lt;&gt; 0) then\n ADOStoredProc1.Recordset := ARecordSet\n else\n Break;\n end;\n\n ADOStoredProc1.Close;\nend;\n</code></pre>\n" }, { "answer_id": 13145530, "author": "Freddie bell", "author_id": 1441618, "author_profile": "https://Stackoverflow.com/users/1441618", "pm_score": 0, "selected": false, "text": "<p>Some enhancements to Francois' code (as tested with DXE2) to cater for multiple print statements and the results from a variable number of selects. The changes are subtle.</p>\n\n<pre><code>procedure TForm1.ADOConnection1InfoMessage(Connection: TADOConnection;\n const Error: Error; var EventStatus: TEventStatus);\nvar\n i: integer;\nbegin\n // show ALL print statements\n for i := 0 to AdoConnection1.Errors.Count - 1 do\n begin\n // was: cxMemo1.Lines.Add(Error.Description);\n cxMemo1.Lines.Add(\n ADOConnection1.Errors.Item[i].Description);\n end;\nend;\n\nprocedure TForm1.cxButton1Click(Sender: TObject);\nconst\n adStateOpen = $00000001; // or uses ADOInt\nvar\n records: Integer;\n ARecordSet: _RecordSet;\nbegin\n cxMemo1.Lines.Add('==========================');\n\n ADOStoredProc1.Open;\n\n try\n ARecordSet := ADOStoredProc1.RecordSet; // initial fetch\n while Assigned(ARecordSet) do\n begin\n // assign the recordset to a DataSets recordset to traverse\n AdoDataSet1.Recordset := ARecordSet;\n // do whatever with current ARecordSet\n while not ADODataSet1.eof do\n begin\n cxMemo1.Lines.Add(ADODataSet1.Fields[0].FieldName + \n ': ' + ADODataSet1.Fields[0].Value);\n AdoDataSet1.Next;\n end;\n // fetch next recordset if there is one\n ARecordSet := ADOStoredProc1.NextRecordSet(records);\n if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) &lt;&gt; 0) then\n ADOStoredProc1.Recordset := ARecordSet\n else\n Break;\n end;\n finally\n ADOStoredProc1.Close;\n end;\n\nend;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42219/" ]
Some of my MS SQL stored procedures produce messages using the 'print' command. In my Delphi 2007 application, which connects to MS SQL using TADOConnection, how can I view the output of those 'print' commands? Key requirements: 1) I can't run the query more than once; it might be updating things. 2) I need to see the 'print' results even if datasets are returned.
That was an interesting one... **The OnInfoMessage event from the ADOConnection works but the Devil is in the details!** **Main points:** use CursorLocation = clUseServer instead of the default clUseClient. use Open and not ExecProc with your ADOStoredProc. use NextRecordset from the current one to get the following, but be sure to check you have one open. use SET NOCOUNT = ON in your stored procedure. **SQL side:** your stored procedure ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FG_TEST]') AND type in (N'P', N'PC')) DROP PROCEDURE [dbo].[FG_TEST] GO -- ============================================= -- Author: François -- Description: test multi ADO with info -- ============================================= CREATE PROCEDURE FG_TEST AS BEGIN -- SET NOCOUNT ON absolutely NEEDED SET NOCOUNT ON; PRINT '*** start ***' SELECT 'one' as Set1Field1 PRINT '*** done once ***' SELECT 'two' as Set2Field2 PRINT '*** done again ***' SELECT 'three' as Set3Field3 PRINT '***finish ***' END GO ``` **Delphi side:** Create a new VCL Forms Application. Put a Memo and a Button in your Form. Copy the following text, change the Catalog and Data Source and Paste it onto your Form ``` object ADOConnection1: TADOConnection ConnectionString = 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security In' + 'fo=False;Initial Catalog=xxxYOURxxxDBxxx;Data Source=xxxYOURxxxSERVERxxx' CursorLocation = clUseServer LoginPrompt = False Provider = 'SQLOLEDB.1' OnInfoMessage = ADOConnection1InfoMessage Left = 24 Top = 216 end object ADOStoredProc1: TADOStoredProc Connection = ADOConnection1 CursorLocation = clUseServer ProcedureName = 'FG_TEST;1' Parameters = <> Left = 24 Top = 264 end ``` In the OnInfoMessage of the ADOConnection put ``` Memo1.Lines.Add(Error.Description); ``` For the ButtonClick, paste this code ``` procedure TForm1.Button1Click(Sender: TObject); const adStateOpen = $00000001; // or defined in ADOInt var I: Integer; ARecordSet: _Recordset; begin Memo1.Lines.Add('=========================='); ADOStoredProc1.Open; // not ExecProc !!!!! ARecordSet := ADOStoredProc1.Recordset; while Assigned(ARecordSet) do begin // do whatever with current RecordSet while not ADOStoredProc1.Eof do begin Memo1.Lines.Add(ADOStoredProc1.Fields[0].FieldName + ': ' + ADOStoredProc1.Fields[0].Value); ADOStoredProc1.Next; end; // switch to subsequent RecordSet if any ARecordSet := ADOStoredProc1.NextRecordset(I); if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) <> 0) then ADOStoredProc1.Recordset := ARecordSet else Break; end; ADOStoredProc1.Close; end; ```
254,494
<p>I've been struggling coming up with a good solution to separate my testing data from unit tests (hard coded values). Until it dawned on me that I could create beans with spring and use those beans to hold my data. </p> <p>Are there any draw backs to coding my unit tests this way? Albeit they run a bit slower seeing as how spring has to configure all the beans and what not.</p>
[ { "answer_id": 254504, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 1, "selected": false, "text": "<p>I dont think that is possible.\nYou might use a temp table to dump print statements and return it alongwith results.</p>\n" }, { "answer_id": 254536, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 2, "selected": false, "text": "<p>In .net's connection classes there is an event called InfoMessage. In a handler for this event you can retrieve the InfoMessage (print statements) from the event args.</p>\n\n<p>I believe Delphi has a similar event called \"OnInfoMessage\" that would help you. </p>\n" }, { "answer_id": 255311, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": true, "text": "<p>That was an interesting one...<br>\n<strong>The OnInfoMessage event from the ADOConnection works but the Devil is in the details!</strong></p>\n\n<p><strong>Main points:</strong><br>\nuse CursorLocation = clUseServer instead of the default clUseClient.<br>\nuse Open and not ExecProc with your ADOStoredProc.<br>\nuse NextRecordset from the current one to get the following, but be sure to check you have one open.<br>\nuse SET NOCOUNT = ON in your stored procedure. </p>\n\n<p><strong>SQL side:</strong> your stored procedure</p>\n\n<pre><code>SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nIF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FG_TEST]') AND type in (N'P', N'PC'))\n DROP PROCEDURE [dbo].[FG_TEST]\nGO\n-- =============================================\n-- Author: François\n-- Description: test multi ADO with info\n-- =============================================\nCREATE PROCEDURE FG_TEST\nAS\nBEGIN\n -- SET NOCOUNT ON absolutely NEEDED\n SET NOCOUNT ON;\n\n PRINT '*** start ***'\n\n SELECT 'one' as Set1Field1\n\n PRINT '*** done once ***'\n\n SELECT 'two' as Set2Field2\n\n PRINT '*** done again ***'\n\n SELECT 'three' as Set3Field3\n\n PRINT '***finish ***'\nEND\nGO\n</code></pre>\n\n<p><strong>Delphi side:</strong><br>\nCreate a new VCL Forms Application.<br>\nPut a Memo and a Button in your Form. </p>\n\n<p>Copy the following text, change the Catalog and Data Source and Paste it onto your Form </p>\n\n<pre><code>object ADOConnection1: TADOConnection\n ConnectionString = \n 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security In' +\n 'fo=False;Initial Catalog=xxxYOURxxxDBxxx;Data Source=xxxYOURxxxSERVERxxx'\n CursorLocation = clUseServer\n LoginPrompt = False\n Provider = 'SQLOLEDB.1'\n OnInfoMessage = ADOConnection1InfoMessage\n Left = 24\n Top = 216\nend\nobject ADOStoredProc1: TADOStoredProc\n Connection = ADOConnection1\n CursorLocation = clUseServer\n ProcedureName = 'FG_TEST;1'\n Parameters = &lt;&gt;\n Left = 24\n Top = 264\nend\n</code></pre>\n\n<p>In the OnInfoMessage of the ADOConnection put</p>\n\n<pre><code>Memo1.Lines.Add(Error.Description);\n</code></pre>\n\n<p>For the ButtonClick, paste this code</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nconst\n adStateOpen = $00000001; // or defined in ADOInt\nvar\n I: Integer;\n ARecordSet: _Recordset;\nbegin\n Memo1.Lines.Add('==========================');\n\n ADOStoredProc1.Open; // not ExecProc !!!!!\n\n ARecordSet := ADOStoredProc1.Recordset;\n while Assigned(ARecordSet) do\n begin\n // do whatever with current RecordSet\n while not ADOStoredProc1.Eof do\n begin\n Memo1.Lines.Add(ADOStoredProc1.Fields[0].FieldName + ': ' + ADOStoredProc1.Fields[0].Value);\n ADOStoredProc1.Next;\n end;\n // switch to subsequent RecordSet if any\n ARecordSet := ADOStoredProc1.NextRecordset(I);\n if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) &lt;&gt; 0) then\n ADOStoredProc1.Recordset := ARecordSet\n else\n Break;\n end;\n\n ADOStoredProc1.Close;\nend;\n</code></pre>\n" }, { "answer_id": 13145530, "author": "Freddie bell", "author_id": 1441618, "author_profile": "https://Stackoverflow.com/users/1441618", "pm_score": 0, "selected": false, "text": "<p>Some enhancements to Francois' code (as tested with DXE2) to cater for multiple print statements and the results from a variable number of selects. The changes are subtle.</p>\n\n<pre><code>procedure TForm1.ADOConnection1InfoMessage(Connection: TADOConnection;\n const Error: Error; var EventStatus: TEventStatus);\nvar\n i: integer;\nbegin\n // show ALL print statements\n for i := 0 to AdoConnection1.Errors.Count - 1 do\n begin\n // was: cxMemo1.Lines.Add(Error.Description);\n cxMemo1.Lines.Add(\n ADOConnection1.Errors.Item[i].Description);\n end;\nend;\n\nprocedure TForm1.cxButton1Click(Sender: TObject);\nconst\n adStateOpen = $00000001; // or uses ADOInt\nvar\n records: Integer;\n ARecordSet: _RecordSet;\nbegin\n cxMemo1.Lines.Add('==========================');\n\n ADOStoredProc1.Open;\n\n try\n ARecordSet := ADOStoredProc1.RecordSet; // initial fetch\n while Assigned(ARecordSet) do\n begin\n // assign the recordset to a DataSets recordset to traverse\n AdoDataSet1.Recordset := ARecordSet;\n // do whatever with current ARecordSet\n while not ADODataSet1.eof do\n begin\n cxMemo1.Lines.Add(ADODataSet1.Fields[0].FieldName + \n ': ' + ADODataSet1.Fields[0].Value);\n AdoDataSet1.Next;\n end;\n // fetch next recordset if there is one\n ARecordSet := ADOStoredProc1.NextRecordSet(records);\n if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) &lt;&gt; 0) then\n ADOStoredProc1.Recordset := ARecordSet\n else\n Break;\n end;\n finally\n ADOStoredProc1.Close;\n end;\n\nend;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17337/" ]
I've been struggling coming up with a good solution to separate my testing data from unit tests (hard coded values). Until it dawned on me that I could create beans with spring and use those beans to hold my data. Are there any draw backs to coding my unit tests this way? Albeit they run a bit slower seeing as how spring has to configure all the beans and what not.
That was an interesting one... **The OnInfoMessage event from the ADOConnection works but the Devil is in the details!** **Main points:** use CursorLocation = clUseServer instead of the default clUseClient. use Open and not ExecProc with your ADOStoredProc. use NextRecordset from the current one to get the following, but be sure to check you have one open. use SET NOCOUNT = ON in your stored procedure. **SQL side:** your stored procedure ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FG_TEST]') AND type in (N'P', N'PC')) DROP PROCEDURE [dbo].[FG_TEST] GO -- ============================================= -- Author: François -- Description: test multi ADO with info -- ============================================= CREATE PROCEDURE FG_TEST AS BEGIN -- SET NOCOUNT ON absolutely NEEDED SET NOCOUNT ON; PRINT '*** start ***' SELECT 'one' as Set1Field1 PRINT '*** done once ***' SELECT 'two' as Set2Field2 PRINT '*** done again ***' SELECT 'three' as Set3Field3 PRINT '***finish ***' END GO ``` **Delphi side:** Create a new VCL Forms Application. Put a Memo and a Button in your Form. Copy the following text, change the Catalog and Data Source and Paste it onto your Form ``` object ADOConnection1: TADOConnection ConnectionString = 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security In' + 'fo=False;Initial Catalog=xxxYOURxxxDBxxx;Data Source=xxxYOURxxxSERVERxxx' CursorLocation = clUseServer LoginPrompt = False Provider = 'SQLOLEDB.1' OnInfoMessage = ADOConnection1InfoMessage Left = 24 Top = 216 end object ADOStoredProc1: TADOStoredProc Connection = ADOConnection1 CursorLocation = clUseServer ProcedureName = 'FG_TEST;1' Parameters = <> Left = 24 Top = 264 end ``` In the OnInfoMessage of the ADOConnection put ``` Memo1.Lines.Add(Error.Description); ``` For the ButtonClick, paste this code ``` procedure TForm1.Button1Click(Sender: TObject); const adStateOpen = $00000001; // or defined in ADOInt var I: Integer; ARecordSet: _Recordset; begin Memo1.Lines.Add('=========================='); ADOStoredProc1.Open; // not ExecProc !!!!! ARecordSet := ADOStoredProc1.Recordset; while Assigned(ARecordSet) do begin // do whatever with current RecordSet while not ADOStoredProc1.Eof do begin Memo1.Lines.Add(ADOStoredProc1.Fields[0].FieldName + ': ' + ADOStoredProc1.Fields[0].Value); ADOStoredProc1.Next; end; // switch to subsequent RecordSet if any ARecordSet := ADOStoredProc1.NextRecordset(I); if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) <> 0) then ADOStoredProc1.Recordset := ARecordSet else Break; end; ADOStoredProc1.Close; end; ```
254,509
<p>I need to leave some instructional comments for other developers on a page/user control. Is there a better way to do this besides the below?</p> <pre><code> &lt;% /* DO NOT rename control IDs here, because blah blah blah... */ %&gt; </code></pre>
[ { "answer_id": 254525, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>That is about it, barring a HTML comment. </p>\n\n<p>Your options are:</p>\n\n<pre><code> &lt;!-- Renders to ClientOutput too --&gt;\n</code></pre>\n\n<p>or:</p>\n\n<pre><code> &lt;% /* Your original idea */ %&gt;\n</code></pre>\n" }, { "answer_id": 254538, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 4, "selected": true, "text": "<pre><code>&lt;%-- Comment Here --%&gt;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22303/" ]
I need to leave some instructional comments for other developers on a page/user control. Is there a better way to do this besides the below? ``` <% /* DO NOT rename control IDs here, because blah blah blah... */ %> ```
``` <%-- Comment Here --%> ```
254,514
<p>I know that PHP doesn't yet have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand.</p> <p>Constants do the trick, but there's the namespace collision problem and (or actually <em>because</em>) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely know how to autofill their keys without additional static analysis annotations or attributes.</p> <p>Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enumerations?</p>
[ { "answer_id": 254523, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 3, "selected": false, "text": "<p>The most common solution that I have seen to enum's in PHP has been to create a generic enum class and then extend it. You might take a look at <a href=\"http://us3.php.net/manual/en/language.oop5.php#73929\" rel=\"noreferrer\">this</a>.</p>\n\n<p><b>UPDATE:</b> Alternatively, I found <a href=\"http://www.phpclasses.org/browse/package/4169.html\" rel=\"noreferrer\">this</a> from phpclasses.org.</p>\n" }, { "answer_id": 254528, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 5, "selected": false, "text": "<p>I used classes with constants:</p>\n\n<pre><code>class Enum {\n const NAME = 'aaaa';\n const SOME_VALUE = 'bbbb';\n}\n\nprint Enum::NAME;\n</code></pre>\n" }, { "answer_id": 254532, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 6, "selected": false, "text": "<p>What about class constants?</p>\n\n<pre><code>&lt;?php\n\nclass YourClass\n{\n const SOME_CONSTANT = 1;\n\n public function echoConstant()\n {\n echo self::SOME_CONSTANT;\n }\n}\n\necho YourClass::SOME_CONSTANT;\n\n$c = new YourClass;\n$c-&gt;echoConstant();\n</code></pre>\n" }, { "answer_id": 254543, "author": "Brian Cline", "author_id": 32536, "author_profile": "https://Stackoverflow.com/users/32536", "pm_score": 12, "selected": true, "text": "<p>Depending upon use case, I would normally use something <em>simple</em> like the following:</p>\n\n<pre><code>abstract class DaysOfWeek\n{\n const Sunday = 0;\n const Monday = 1;\n // etc.\n}\n\n$today = DaysOfWeek::Sunday;\n</code></pre>\n\n<p>However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and <a href=\"https://stackoverflow.com/a/21536800/102937\">a few other notes</a>, here's an expanded example which may better serve a much wider range of cases:</p>\n\n<pre><code>abstract class BasicEnum {\n private static $constCacheArray = NULL;\n\n private static function getConstants() {\n if (self::$constCacheArray == NULL) {\n self::$constCacheArray = [];\n }\n $calledClass = get_called_class();\n if (!array_key_exists($calledClass, self::$constCacheArray)) {\n $reflect = new ReflectionClass($calledClass);\n self::$constCacheArray[$calledClass] = $reflect-&gt;getConstants();\n }\n return self::$constCacheArray[$calledClass];\n }\n\n public static function isValidName($name, $strict = false) {\n $constants = self::getConstants();\n\n if ($strict) {\n return array_key_exists($name, $constants);\n }\n\n $keys = array_map('strtolower', array_keys($constants));\n return in_array(strtolower($name), $keys);\n }\n\n public static function isValidValue($value, $strict = true) {\n $values = array_values(self::getConstants());\n return in_array($value, $values, $strict);\n }\n}\n</code></pre>\n\n<p>By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:</p>\n\n<pre><code>abstract class DaysOfWeek extends BasicEnum {\n const Sunday = 0;\n const Monday = 1;\n const Tuesday = 2;\n const Wednesday = 3;\n const Thursday = 4;\n const Friday = 5;\n const Saturday = 6;\n}\n\nDaysOfWeek::isValidName('Humpday'); // false\nDaysOfWeek::isValidName('Monday'); // true\nDaysOfWeek::isValidName('monday'); // true\nDaysOfWeek::isValidName('monday', $strict = true); // false\nDaysOfWeek::isValidName(0); // false\n\nDaysOfWeek::isValidValue(0); // true\nDaysOfWeek::isValidValue(5); // true\nDaysOfWeek::isValidValue(7); // false\nDaysOfWeek::isValidValue('Friday'); // false\n</code></pre>\n\n<p>As a side note, any time I use reflection at least once <strong>on a static/const class where the data won't change</strong> (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).</p>\n\n<p>Now that most people have <strong>finally</strong> upgraded to at least 5.3, and <code>SplEnum</code> is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum <em>instantiations</em> throughout your codebase. In the above example, <code>BasicEnum</code> and <code>DaysOfWeek</code> cannot be instantiated at all, nor should they be.</p>\n" }, { "answer_id": 3539340, "author": "Christopher Fox", "author_id": 427340, "author_profile": "https://Stackoverflow.com/users/427340", "pm_score": 3, "selected": false, "text": "<p>If you need to use enums that are globally unique (i.e. even when comparing elements between different Enums) and are easy to use, feel free to use the following code. I also added some methods that I find useful. You will find examples in the comments at the very top of the code.</p>\n\n<pre><code>&lt;?php\n\n/**\n * Class Enum\n * \n * @author Christopher Fox &lt;[email protected]&gt;\n *\n * @version 1.0\n *\n * This class provides the function of an enumeration.\n * The values of Enum elements are unique (even between different Enums)\n * as you would expect them to be.\n *\n * Constructing a new Enum:\n * ========================\n *\n * In the following example we construct an enum called \"UserState\"\n * with the elements \"inactive\", \"active\", \"banned\" and \"deleted\".\n * \n * &lt;code&gt;\n * Enum::Create('UserState', 'inactive', 'active', 'banned', 'deleted');\n * &lt;/code&gt;\n *\n * Using Enums:\n * ============\n *\n * The following example demonstrates how to compare two Enum elements\n *\n * &lt;code&gt;\n * var_dump(UserState::inactive == UserState::banned); // result: false\n * var_dump(UserState::active == UserState::active); // result: true\n * &lt;/code&gt;\n *\n * Special Enum methods:\n * =====================\n *\n * Get the number of elements in an Enum:\n *\n * &lt;code&gt;\n * echo UserState::CountEntries(); // result: 4\n * &lt;/code&gt;\n *\n * Get a list with all elements of the Enum:\n *\n * &lt;code&gt;\n * $allUserStates = UserState::GetEntries();\n * &lt;/code&gt;\n *\n * Get a name of an element:\n *\n * &lt;code&gt;\n * echo UserState::GetName(UserState::deleted); // result: deleted\n * &lt;/code&gt;\n *\n * Get an integer ID for an element (e.g. to store as a value in a database table):\n * This is simply the index of the element (beginning with 1).\n * Note that this ID is only unique for this Enum but now between different Enums.\n *\n * &lt;code&gt;\n * echo UserState::GetDatabaseID(UserState::active); // result: 2\n * &lt;/code&gt;\n */\nclass Enum\n{\n\n /**\n * @var Enum $instance The only instance of Enum (Singleton)\n */\n private static $instance;\n\n /**\n * @var array $enums An array of all enums with Enum names as keys\n * and arrays of element names as values\n */\n private $enums;\n\n /**\n * Constructs (the only) Enum instance\n */\n private function __construct()\n {\n $this-&gt;enums = array();\n }\n\n /**\n * Constructs a new enum\n *\n * @param string $name The class name for the enum\n * @param mixed $_ A list of strings to use as names for enum entries\n */\n public static function Create($name, $_)\n {\n // Create (the only) Enum instance if this hasn't happened yet\n if (self::$instance===null)\n {\n self::$instance = new Enum();\n }\n\n // Fetch the arguments of the function\n $args = func_get_args();\n // Exclude the \"name\" argument from the array of function arguments,\n // so only the enum element names remain in the array\n array_shift($args);\n self::$instance-&gt;add($name, $args);\n }\n\n /**\n * Creates an enumeration if this hasn't happened yet\n * \n * @param string $name The class name for the enum\n * @param array $fields The names of the enum elements\n */\n private function add($name, $fields)\n {\n if (!array_key_exists($name, $this-&gt;enums))\n {\n $this-&gt;enums[$name] = array();\n\n // Generate the code of the class for this enumeration\n $classDeclaration = \"class \" . $name . \" {\\n\"\n . \"private static \\$name = '\" . $name . \"';\\n\"\n . $this-&gt;getClassConstants($name, $fields)\n . $this-&gt;getFunctionGetEntries($name)\n . $this-&gt;getFunctionCountEntries($name)\n . $this-&gt;getFunctionGetDatabaseID()\n . $this-&gt;getFunctionGetName()\n . \"}\";\n\n // Create the class for this enumeration\n eval($classDeclaration);\n }\n }\n\n /**\n * Returns the code of the class constants\n * for an enumeration. These are the representations\n * of the elements.\n * \n * @param string $name The class name for the enum\n * @param array $fields The names of the enum elements\n *\n * @return string The code of the class constants\n */\n private function getClassConstants($name, $fields)\n {\n $constants = '';\n\n foreach ($fields as $field)\n {\n // Create a unique ID for the Enum element\n // This ID is unique because class and variables\n // names can't contain a semicolon. Therefore we\n // can use the semicolon as a separator here.\n $uniqueID = $name . \";\" . $field;\n $constants .= \"const \" . $field . \" = '\". $uniqueID . \"';\\n\";\n // Store the unique ID\n array_push($this-&gt;enums[$name], $uniqueID);\n }\n\n return $constants;\n }\n\n /**\n * Returns the code of the function \"GetEntries()\"\n * for an enumeration\n * \n * @param string $name The class name for the enum\n *\n * @return string The code of the function \"GetEntries()\"\n */\n private function getFunctionGetEntries($name) \n {\n $entryList = ''; \n\n // Put the unique element IDs in single quotes and\n // separate them with commas\n foreach ($this-&gt;enums[$name] as $key =&gt; $entry)\n {\n if ($key &gt; 0) $entryList .= ',';\n $entryList .= \"'\" . $entry . \"'\";\n }\n\n return \"public static function GetEntries() { \\n\"\n . \" return array(\" . $entryList . \");\\n\"\n . \"}\\n\";\n }\n\n /**\n * Returns the code of the function \"CountEntries()\"\n * for an enumeration\n * \n * @param string $name The class name for the enum\n *\n * @return string The code of the function \"CountEntries()\"\n */\n private function getFunctionCountEntries($name) \n {\n // This function will simply return a constant number (e.g. return 5;)\n return \"public static function CountEntries() { \\n\"\n . \" return \" . count($this-&gt;enums[$name]) . \";\\n\"\n . \"}\\n\";\n }\n\n /**\n * Returns the code of the function \"GetDatabaseID()\"\n * for an enumeration\n * \n * @return string The code of the function \"GetDatabaseID()\"\n */\n private function getFunctionGetDatabaseID()\n {\n // Check for the index of this element inside of the array\n // of elements and add +1\n return \"public static function GetDatabaseID(\\$entry) { \\n\"\n . \"\\$key = array_search(\\$entry, self::GetEntries());\\n\"\n . \" return \\$key + 1;\\n\"\n . \"}\\n\";\n }\n\n /**\n * Returns the code of the function \"GetName()\"\n * for an enumeration\n *\n * @return string The code of the function \"GetName()\"\n */\n private function getFunctionGetName()\n {\n // Remove the class name from the unique ID \n // and return this value (which is the element name)\n return \"public static function GetName(\\$entry) { \\n\"\n . \"return substr(\\$entry, strlen(self::\\$name) + 1 , strlen(\\$entry));\\n\"\n . \"}\\n\";\n }\n\n}\n\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 3985626, "author": "zanshine", "author_id": 482734, "author_profile": "https://Stackoverflow.com/users/482734", "pm_score": 3, "selected": false, "text": "<p>Here is a github library for handling type-safe enumerations in php:</p>\n\n<p>This library handle classes generation, classes caching and it implements the Type Safe Enumeration design pattern, with several helper methods for dealing with enums, like retrieving an ordinal for enums sorting, or retrieving a binary value, for enums combinations.</p>\n\n<p>The generated code use a plain old php template file, which is also configurable, so you can provide your own template.</p>\n\n<p>It is full test covered with phpunit.</p>\n\n<p><a href=\"http://github.com/zanshine/php-enums\" rel=\"noreferrer\">php-enums on github (feel free to fork)</a></p>\n\n<h2>Usage: (@see usage.php, or unit tests for more details)</h2>\n\n<pre><code>&lt;?php\n//require the library\nrequire_once __DIR__ . '/src/Enum.func.php';\n\n//if you don't have a cache directory, create one\n@mkdir(__DIR__ . '/cache');\nEnumGenerator::setDefaultCachedClassesDir(__DIR__ . '/cache');\n\n//Class definition is evaluated on the fly:\nEnum('FruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'));\n\n//Class definition is cached in the cache directory for later usage:\nEnum('CachedFruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'), '\\my\\company\\name\\space', true);\n\necho 'FruitsEnum::APPLE() == FruitsEnum::APPLE(): ';\nvar_dump(FruitsEnum::APPLE() == FruitsEnum::APPLE()) . \"\\n\";\n\necho 'FruitsEnum::APPLE() == FruitsEnum::ORANGE(): ';\nvar_dump(FruitsEnum::APPLE() == FruitsEnum::ORANGE()) . \"\\n\";\n\necho 'FruitsEnum::APPLE() instanceof Enum: ';\nvar_dump(FruitsEnum::APPLE() instanceof Enum) . \"\\n\";\n\necho 'FruitsEnum::APPLE() instanceof FruitsEnum: ';\nvar_dump(FruitsEnum::APPLE() instanceof FruitsEnum) . \"\\n\";\n\necho \"-&gt;getName()\\n\";\nforeach (FruitsEnum::iterator() as $enum)\n{\n echo \" \" . $enum-&gt;getName() . \"\\n\";\n}\n\necho \"-&gt;getValue()\\n\";\nforeach (FruitsEnum::iterator() as $enum)\n{\n echo \" \" . $enum-&gt;getValue() . \"\\n\";\n}\n\necho \"-&gt;getOrdinal()\\n\";\nforeach (CachedFruitsEnum::iterator() as $enum)\n{\n echo \" \" . $enum-&gt;getOrdinal() . \"\\n\";\n}\n\necho \"-&gt;getBinary()\\n\";\nforeach (CachedFruitsEnum::iterator() as $enum)\n{\n echo \" \" . $enum-&gt;getBinary() . \"\\n\";\n}\n</code></pre>\n\n<h2>Output:</h2>\n\n<pre><code>FruitsEnum::APPLE() == FruitsEnum::APPLE(): bool(true)\nFruitsEnum::APPLE() == FruitsEnum::ORANGE(): bool(false)\nFruitsEnum::APPLE() instanceof Enum: bool(true)\nFruitsEnum::APPLE() instanceof FruitsEnum: bool(true)\n-&gt;getName()\n APPLE\n ORANGE\n RASBERRY\n BANNANA\n-&gt;getValue()\n apple\n orange\n rasberry\n bannana\n-&gt;getValue() when values have been specified\n pig\n dog\n cat\n bird\n-&gt;getOrdinal()\n 1\n 2\n 3\n 4\n-&gt;getBinary()\n 1\n 2\n 4\n 8\n</code></pre>\n" }, { "answer_id": 4522078, "author": "aelg", "author_id": 552764, "author_profile": "https://Stackoverflow.com/users/552764", "pm_score": 5, "selected": false, "text": "<p>Well, for a simple java like enum in php, I use:</p>\n\n<pre><code>class SomeTypeName {\n private static $enum = array(1 =&gt; \"Read\", 2 =&gt; \"Write\");\n\n public function toOrdinal($name) {\n return array_search($name, self::$enum);\n }\n\n public function toString($ordinal) {\n return self::$enum[$ordinal];\n }\n}\n</code></pre>\n\n<p>And to call it:</p>\n\n<pre><code>SomeTypeName::toOrdinal(\"Read\");\nSomeTypeName::toString(1);\n</code></pre>\n\n<p>But I'm a PHP beginner, struggling with the syntax so this might not be the best way. I experimented some with Class Constants, using Reflection to get the constant name from it's value, might be neater.</p>\n" }, { "answer_id": 5051786, "author": "arturgspb", "author_id": 614999, "author_profile": "https://Stackoverflow.com/users/614999", "pm_score": 1, "selected": false, "text": "<p>Yesterday I wrote this class <a href=\"http://arturgspb.ru/read/enum-v-php-zhestkaya-tipizaciya-perechislenij.html\" rel=\"nofollow\">on my blog</a>. I think it's maybe be easy for use in php scripts:</p>\n\n<pre><code>final class EnumException extends Exception{}\n\nabstract class Enum\n{\n /**\n * @var array ReflectionClass\n */\n protected static $reflectorInstances = array();\n /**\n * Массив конфигурированного объекта-константы enum\n * @var array\n */\n protected static $enumInstances = array();\n /**\n * Массив соответствий значение-&gt;ключ используется для проверки - \n * если ли константа с таким значением\n * @var array\n */\n protected static $foundNameValueLink = array();\n\n protected $constName;\n protected $constValue;\n\n /**\n * Реализует паттерн \"Одиночка\"\n * Возвращает объект константы, но но как объект его использовать не стоит, \n * т.к. для него реализован \"волшебный метод\" __toString()\n * Это должно использоваться только для типизачии его как параметра\n * @paradm Node\n */\n final public static function get($value)\n {\n // Это остается здесь для увеличения производительности (по замерам ~10%)\n $name = self::getName($value);\n if ($name === false)\n throw new EnumException(\"Неизвестая константа\");\n $className = get_called_class(); \n if (!isset(self::$enumInstances[$className][$name]))\n {\n $value = constant($className.'::'.$name);\n self::$enumInstances[$className][$name] = new $className($name, $value);\n }\n\n return self::$enumInstances[$className][$name];\n }\n\n /**\n * Возвращает массив констант пар ключ-значение всего перечисления\n * @return array \n */\n final public static function toArray()\n {\n $classConstantsArray = self::getReflectorInstance()-&gt;getConstants();\n foreach ($classConstantsArray as $k =&gt; $v)\n $classConstantsArray[$k] = (string)$v;\n return $classConstantsArray;\n }\n\n /**\n * Для последующего использования в toArray для получения массива констант ключ-&gt;значение \n * @return ReflectionClass\n */\n final private static function getReflectorInstance()\n {\n $className = get_called_class();\n if (!isset(self::$reflectorInstances[$className]))\n {\n self::$reflectorInstances[$className] = new ReflectionClass($className);\n }\n return self::$reflectorInstances[$className];\n }\n\n /**\n * Получает имя константы по её значению\n * @param string $value\n */\n final public static function getName($value)\n {\n $className = (string)get_called_class();\n\n $value = (string)$value;\n if (!isset(self::$foundNameValueLink[$className][$value]))\n {\n $constantName = array_search($value, self::toArray(), true);\n self::$foundNameValueLink[$className][$value] = $constantName;\n }\n return self::$foundNameValueLink[$className][$value];\n }\n\n /**\n * Используется ли такое имя константы в перечислении\n * @param string $name\n */\n final public static function isExistName($name)\n {\n $constArray = self::toArray();\n return isset($constArray[$name]);\n }\n\n /**\n * Используется ли такое значение константы в перечислении\n * @param string $value\n */\n final public static function isExistValue($value)\n {\n return self::getName($value) === false ? false : true;\n } \n\n\n final private function __clone(){}\n\n final private function __construct($name, $value)\n {\n $this-&gt;constName = $name;\n $this-&gt;constValue = $value;\n }\n\n final public function __toString()\n {\n return (string)$this-&gt;constValue;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>class enumWorkType extends Enum\n{\n const FULL = 0;\n const SHORT = 1;\n}\n</code></pre>\n" }, { "answer_id": 5223436, "author": "markus", "author_id": 11995, "author_profile": "https://Stackoverflow.com/users/11995", "pm_score": 8, "selected": false, "text": "<p>There is a native extension, too. The <strong>SplEnum</strong></p>\n\n<blockquote>\n <p>SplEnum gives the ability to emulate and create enumeration objects\n natively in PHP.</p>\n</blockquote>\n\n<p><a href=\"http://www.php.net/manual/en/class.splenum.php\" rel=\"noreferrer\">http://www.php.net/manual/en/class.splenum.php</a></p>\n\n<p>Attention:</p>\n\n<p><a href=\"https://www.php.net/manual/en/spl-types.installation.php\" rel=\"noreferrer\">https://www.php.net/manual/en/spl-types.installation.php</a></p>\n\n<blockquote>\n <p>The PECL extension is not bundled with PHP.</p>\n \n <p>A DLL for this PECL extension is currently unavailable.</p>\n</blockquote>\n" }, { "answer_id": 5647348, "author": "user667540", "author_id": 667540, "author_profile": "https://Stackoverflow.com/users/667540", "pm_score": 3, "selected": false, "text": "<p>I like enums from java too and for this reason I write my enums in this way, I think this is the most similiar behawior like in Java enums, of course, if some want to use more methods from java should write it here, or in abstract class but core idea is embedded in code below</p>\n\n<pre><code>\nclass FruitsEnum {\n\n static $APPLE = null;\n static $ORANGE = null;\n\n private $value = null;\n\n public static $map;\n\n public function __construct($value) {\n $this->value = $value;\n }\n\n public static function init () {\n self::$APPLE = new FruitsEnum(\"Apple\");\n self::$ORANGE = new FruitsEnum(\"Orange\");\n //static map to get object by name - example Enum::get(\"INIT\") - returns Enum::$INIT object;\n self::$map = array (\n \"Apple\" => self::$APPLE,\n \"Orange\" => self::$ORANGE\n );\n }\n\n public static function get($element) {\n if($element == null)\n return null;\n return self::$map[$element];\n }\n\n public function getValue() {\n return $this->value;\n }\n\n public function equals(FruitsEnum $element) {\n return $element->getValue() == $this->getValue();\n }\n\n public function __toString () {\n return $this->value;\n }\n}\nFruitsEnum::init();\n\nvar_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$APPLE)); //true\nvar_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$ORANGE)); //false\nvar_dump(FruitsEnum::$APPLE instanceof FruitsEnum); //true\nvar_dump(FruitsEnum::get(\"Apple\")->equals(FruitsEnum::$APPLE)); //true - enum from string\nvar_dump(FruitsEnum::get(\"Apple\")->equals(FruitsEnum::get(\"Orange\"))); //false\n\n</code></pre>\n" }, { "answer_id": 5655491, "author": "Anders", "author_id": 526696, "author_profile": "https://Stackoverflow.com/users/526696", "pm_score": 2, "selected": false, "text": "<p>This is my take on \"dynamic\" enum... so that i can call it with variables, ex. from a form.</p>\n\n<p><strong>look at updated verison below this codeblock...</strong></p>\n\n<pre><code>$value = \"concert\";\n$Enumvalue = EnumCategory::enum($value);\n//$EnumValue = 1\n\nclass EnumCategory{\n const concert = 1;\n const festival = 2;\n const sport = 3;\n const nightlife = 4;\n const theatre = 5;\n const musical = 6;\n const cinema = 7;\n const charity = 8;\n const museum = 9;\n const other = 10;\n\n public function enum($string){\n return constant('EnumCategory::'.$string);\n }\n}\n</code></pre>\n\n<p><strong>UPDATE: Better way of doing it...</strong></p>\n\n<pre><code>class EnumCategory {\n\n static $concert = 1;\n static $festival = 2;\n static $sport = 3;\n static $nightlife = 4;\n static $theatre = 5;\n static $musical = 6;\n static $cinema = 7;\n static $charity = 8;\n static $museum = 9;\n static $other = 10;\n\n}\n</code></pre>\n\n<p>Call with</p>\n\n<pre><code>EnumCategory::${$category};\n</code></pre>\n" }, { "answer_id": 8258912, "author": "Andi T", "author_id": 399996, "author_profile": "https://Stackoverflow.com/users/399996", "pm_score": 5, "selected": false, "text": "<p>I use <code>interface</code> instead of <code>class</code>:</p>\n\n<pre><code>interface DaysOfWeek\n{\n const Sunday = 0;\n const Monday = 1;\n // etc.\n}\n\nvar $today = DaysOfWeek::Sunday;\n</code></pre>\n" }, { "answer_id": 8659707, "author": "Tiddo", "author_id": 532901, "author_profile": "https://Stackoverflow.com/users/532901", "pm_score": 2, "selected": false, "text": "<p>I know this is an old thread, however none of the workarounds I've seen really looked like enums, since almost all workarounds requires you to manually assign values to the enum items, or it requires you to pass an array of enum keys to a function. So I created my own solution for this. </p>\n\n<p>To create an enum class using my solution one can simply extend this Enum class below, create a bunch of static variables (no need to initialize them), and make a call to yourEnumClass::init() just below the definition of your enum class. </p>\n\n<p>edit: This only works in php >= 5.3, but it can probably be modified to work in older versions as well\n \n\n<pre><code>/**\n * A base class for enums. \n * \n * This class can be used as a base class for enums. \n * It can be used to create regular enums (incremental indices), but it can also be used to create binary flag values.\n * To create an enum class you can simply extend this class, and make a call to &lt;yourEnumClass&gt;::init() before you use the enum.\n * Preferably this call is made directly after the class declaration. \n * Example usages:\n * DaysOfTheWeek.class.php\n * abstract class DaysOfTheWeek extends Enum{\n * static $MONDAY = 1;\n * static $TUESDAY;\n * static $WEDNESDAY;\n * static $THURSDAY;\n * static $FRIDAY;\n * static $SATURDAY;\n * static $SUNDAY;\n * }\n * DaysOfTheWeek::init();\n * \n * example.php\n * require_once(\"DaysOfTheWeek.class.php\");\n * $today = date('N');\n * if ($today == DaysOfTheWeek::$SUNDAY || $today == DaysOfTheWeek::$SATURDAY)\n * echo \"It's weekend!\";\n * \n * Flags.class.php\n * abstract class Flags extends Enum{\n * static $FLAG_1;\n * static $FLAG_2;\n * static $FLAG_3;\n * }\n * Flags::init(Enum::$BINARY_FLAG);\n * \n * example2.php\n * require_once(\"Flags.class.php\");\n * $flags = Flags::$FLAG_1 | Flags::$FLAG_2;\n * if ($flags &amp; Flags::$FLAG_1)\n * echo \"Flag_1 is set\";\n * \n * @author Tiddo Langerak\n */\nabstract class Enum{\n\n static $BINARY_FLAG = 1;\n /**\n * This function must be called to initialize the enumeration!\n * \n * @param bool $flags If the USE_BINARY flag is provided, the enum values will be binary flag values. Default: no flags set.\n */ \n public static function init($flags = 0){\n //First, we want to get a list of all static properties of the enum class. We'll use the ReflectionClass for this.\n $enum = get_called_class();\n $ref = new ReflectionClass($enum);\n $items = $ref-&gt;getStaticProperties();\n //Now we can start assigning values to the items. \n if ($flags &amp; self::$BINARY_FLAG){\n //If we want binary flag values, our first value should be 1.\n $value = 1;\n //Now we can set the values for all items.\n foreach ($items as $key=&gt;$item){\n if (!isset($item)){ \n //If no value is set manually, we should set it.\n $enum::$$key = $value;\n //And we need to calculate the new value\n $value *= 2;\n } else {\n //If there was already a value set, we will continue starting from that value, but only if that was a valid binary flag value.\n //Otherwise, we will just skip this item.\n if ($key != 0 &amp;&amp; ($key &amp; ($key - 1) == 0))\n $value = 2 * $item;\n }\n }\n } else {\n //If we want to use regular indices, we'll start with index 0.\n $value = 0;\n //Now we can set the values for all items.\n foreach ($items as $key=&gt;$item){\n if (!isset($item)){\n //If no value is set manually, we should set it, and increment the value for the next item.\n $enum::$$key = $value;\n $value++;\n } else {\n //If a value was already set, we'll continue from that value.\n $value = $item+1;\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 10428012, "author": "Weke", "author_id": 1371979, "author_profile": "https://Stackoverflow.com/users/1371979", "pm_score": -1, "selected": false, "text": "<p>I use a construction like the following for simple enums. Typically you can use them for switch statements. </p>\n\n<pre><code>&lt;?php \n define(\"OPTION_1\", \"1\");\n define(\"OPTION_2\", OPTION_1 + 1);\n define(\"OPTION_3\", OPTION_2 + 1);\n\n // Some function...\n switch($Val){\n case OPTION_1:{ Perform_1();}break;\n case OPTION_2:{ Perform_2();}break;\n ...\n }\n?&gt;\n</code></pre>\n\n<p>It is not as conviniet as a native enum like in C++ but it seems to work and requires less maintenance if you later would like to add an option in between.</p>\n" }, { "answer_id": 12150762, "author": "KDog", "author_id": 1628906, "author_profile": "https://Stackoverflow.com/users/1628906", "pm_score": 1, "selected": false, "text": "<p>My attempt to create an enum with PHP...it's extremely limited since it doesn't support objects as the enum values but still somewhat useful...</p>\n\n<pre><code>class ProtocolsEnum {\n\n const HTTP = '1';\n const HTTPS = '2';\n const FTP = '3';\n\n /**\n * Retrieve an enum value\n * @param string $name\n * @return string\n */\n public static function getValueByName($name) {\n return constant('self::'. $name);\n } \n\n /**\n * Retrieve an enum key name\n * @param string $code\n * @return string\n */\n public static function getNameByValue($code) {\n foreach(get_class_constants() as $key =&gt; $val) {\n if($val == $code) {\n return $key;\n }\n }\n }\n\n /**\n * Retrieve associate array of all constants (used for creating droplist options)\n * @return multitype:\n */\n public static function toArray() { \n return array_flip(self::get_class_constants());\n }\n\n private static function get_class_constants()\n {\n $reflect = new ReflectionClass(__CLASS__);\n return $reflect-&gt;getConstants();\n }\n}\n</code></pre>\n" }, { "answer_id": 13621724, "author": "Vincent Pazeller", "author_id": 811120, "author_profile": "https://Stackoverflow.com/users/811120", "pm_score": 2, "selected": false, "text": "<p>The accepted answer is the way to go and is actually what I am doing for simplicity. Most advantages of enumeration are offered (readable, fast, etc.). One concept is missing, however: type safety. In most languages, enumerations are also used to restrict allowed values. Below is an example of how type safety can also be obtained by using private constructors, static instantiation methods and type checking:</p>\n\n<pre><code>class DaysOfWeek{\n const Sunday = 0;\n const Monday = 1;\n // etc.\n\n private $intVal;\n private function __construct($intVal){\n $this-&gt;intVal = $intVal;\n }\n\n //static instantiation methods\n public static function MONDAY(){\n return new self(self::Monday);\n }\n //etc.\n}\n\n//function using type checking\nfunction printDayOfWeek(DaysOfWeek $d){ //compiler can now use type checking\n // to something with $d...\n}\n\n//calling the function is safe!\nprintDayOfWeek(DaysOfWeek::MONDAY());\n</code></pre>\n\n<p>We could even go further: using constants in the DaysOfWeek class might lead to misusage: e.g. one might mistakenly use it this way:</p>\n\n<pre><code>printDayOfWeek(DaysOfWeek::Monday); //triggers a compiler error.\n</code></pre>\n\n<p>which is wrong (calls integer constant). We can prevent this using private static variables instead of constants:</p>\n\n<pre><code>class DaysOfWeeks{\n\n private static $monday = 1;\n //etc.\n\n private $intVal;\n //private constructor\n private function __construct($intVal){\n $this-&gt;intVal = $intVal;\n }\n\n //public instantiation methods\n public static function MONDAY(){\n return new self(self::$monday);\n }\n //etc.\n\n\n //convert an instance to its integer value\n public function intVal(){\n return $this-&gt;intVal;\n }\n\n}\n</code></pre>\n\n<p>Of course, it is not possible to access integer constants (this was actually the purpose). The intVal method allows to convert a DaysOfWeek object to its integer representation.</p>\n\n<p>Note that we could even go further by implementing a caching mechanism in instantiation methods to save memory in the case enumerations are extensively used...</p>\n\n<p>Hope this will help</p>\n" }, { "answer_id": 13665128, "author": "Brian Fisher", "author_id": 43816, "author_profile": "https://Stackoverflow.com/users/43816", "pm_score": 3, "selected": false, "text": "<p>I have taken to using the approach below as it gives me the ability to have type safety for function parameters, auto complete in NetBeans and good performance. The one thing I don't like too much is that you have to call <code>[extended class name]::enumerate();</code> after defining the class.</p>\n\n<pre><code>abstract class Enum {\n\n private $_value;\n\n protected function __construct($value) {\n $this-&gt;_value = $value;\n }\n\n public function __toString() {\n return (string) $this-&gt;_value;\n }\n\n public static function enumerate() {\n $class = get_called_class();\n $ref = new ReflectionClass($class);\n $statics = $ref-&gt;getStaticProperties();\n foreach ($statics as $name =&gt; $value) {\n $ref-&gt;setStaticPropertyValue($name, new $class($value));\n }\n }\n}\n\nclass DaysOfWeek extends Enum {\n public static $MONDAY = 0;\n public static $SUNDAY = 1;\n // etc.\n}\nDaysOfWeek::enumerate();\n\nfunction isMonday(DaysOfWeek $d) {\n if ($d == DaysOfWeek::$MONDAY) {\n return true;\n } else {\n return false;\n }\n}\n\n$day = DaysOfWeek::$MONDAY;\necho (isMonday($day) ? \"bummer it's monday\" : \"Yay! it's not monday\");\n</code></pre>\n" }, { "answer_id": 14330126, "author": "Hervé Labas", "author_id": 1092480, "author_profile": "https://Stackoverflow.com/users/1092480", "pm_score": 2, "selected": false, "text": "<p>Pointed out solution works well. Clean and smooth.</p>\n\n<p>However, if you want strongly typed enumerations, you can use this:</p>\n\n<pre><code>class TestEnum extends Enum\n{\n public static $TEST1;\n public static $TEST2;\n}\nTestEnum::init(); // Automatically initializes enum values\n</code></pre>\n\n<p>With an Enum class looking like:</p>\n\n<pre><code>class Enum\n{\n public static function parse($enum)\n {\n $class = get_called_class();\n $vars = get_class_vars($class);\n if (array_key_exists($enum, $vars)) {\n return $vars[$enum];\n }\n return null;\n }\n\n public static function init()\n {\n $className = get_called_class();\n $consts = get_class_vars($className);\n foreach ($consts as $constant =&gt; $value) {\n if (is_null($className::$$constant)) {\n $constantValue = $constant;\n $constantValueName = $className . '::' . $constant . '_VALUE';\n if (defined($constantValueName)) {\n $constantValue = constant($constantValueName);\n }\n $className::$$constant = new $className($constantValue);\n }\n }\n }\n\n public function __construct($value)\n {\n $this-&gt;value = $value;\n }\n}\n</code></pre>\n\n<p>This way, enum values are strongly typed and </p>\n\n<p><code>TestEnum::$TEST1 === TestEnum::parse('TEST1') // true statement</code></p>\n" }, { "answer_id": 15010599, "author": "Dan King", "author_id": 1490986, "author_profile": "https://Stackoverflow.com/users/1490986", "pm_score": 2, "selected": false, "text": "<p>Some good solutions on here!</p>\n<p>Here's my version.</p>\n<ul>\n<li>It's strongly typed</li>\n<li>It works with IDE auto-completion</li>\n<li>Enums are defined by a code and a description, where the code can be an integer, a binary value, a short string, or basically anything else you want. The pattern could easily be extended to support orther properties.</li>\n<li>It asupports value (==) and reference (===) comparisons and works in switch statements.</li>\n</ul>\n<p>I think the main disadvantage is that enum members do have to be separately declared and instantiated, due to the descriptions and PHP's inability to construct objects at static member declaration time. I guess a way round this might be to use reflection with parsed doc comments instead.</p>\n<p>The abstract enum looks like this:</p>\n<pre><code>&lt;?php\n\nabstract class AbstractEnum\n{\n /** @var array cache of all enum instances by class name and integer value */\n private static $allEnumMembers = array();\n\n /** @var mixed */\n private $code;\n\n /** @var string */\n private $description;\n\n /**\n * Return an enum instance of the concrete type on which this static method is called, assuming an instance\n * exists for the passed in value. Otherwise an exception is thrown.\n *\n * @param $code\n * @return AbstractEnum\n * @throws Exception\n */\n public static function getByCode($code)\n {\n $concreteMembers = &amp;self::getConcreteMembers();\n\n if (array_key_exists($code, $concreteMembers)) {\n return $concreteMembers[$code];\n }\n\n throw new Exception(&quot;Value '$code' does not exist for enum '&quot;.get_called_class().&quot;'&quot;);\n }\n\n public static function getAllMembers()\n {\n return self::getConcreteMembers();\n }\n\n /**\n * Create, cache and return an instance of the concrete enum type for the supplied primitive value.\n *\n * @param mixed $code code to uniquely identify this enum\n * @param string $description\n * @throws Exception\n * @return AbstractEnum\n */\n protected static function enum($code, $description)\n {\n $concreteMembers = &amp;self::getConcreteMembers();\n\n if (array_key_exists($code, $concreteMembers)) {\n throw new Exception(&quot;Value '$code' has already been added to enum '&quot;.get_called_class().&quot;'&quot;);\n }\n\n $concreteMembers[$code] = $concreteEnumInstance = new static($code, $description);\n\n return $concreteEnumInstance;\n }\n\n /**\n * @return AbstractEnum[]\n */\n private static function &amp;getConcreteMembers() {\n $thisClassName = get_called_class();\n\n if (!array_key_exists($thisClassName, self::$allEnumMembers)) {\n $concreteMembers = array();\n self::$allEnumMembers[$thisClassName] = $concreteMembers;\n }\n\n return self::$allEnumMembers[$thisClassName];\n }\n\n private function __construct($code, $description)\n {\n $this-&gt;code = $code;\n $this-&gt;description = $description;\n }\n\n public function getCode()\n {\n return $this-&gt;code;\n }\n\n public function getDescription()\n {\n return $this-&gt;description;\n }\n}\n</code></pre>\n<p>Here's an example concrete enum:</p>\n<pre><code>&lt;?php\n\nrequire('AbstractEnum.php');\n\nclass EMyEnum extends AbstractEnum\n{\n /** @var EMyEnum */\n public static $MY_FIRST_VALUE;\n /** @var EMyEnum */\n public static $MY_SECOND_VALUE;\n /** @var EMyEnum */\n public static $MY_THIRD_VALUE;\n\n public static function _init()\n {\n self::$MY_FIRST_VALUE = self::enum(1, 'My first value');\n self::$MY_SECOND_VALUE = self::enum(2, 'My second value');\n self::$MY_THIRD_VALUE = self::enum(3, 'My third value');\n }\n}\n\nEMyEnum::_init();\n</code></pre>\n<p>Which can be used like this:</p>\n<pre><code>&lt;?php\n\nrequire('EMyEnum.php');\n\necho EMyEnum::$MY_FIRST_VALUE-&gt;getCode().' : '.EMyEnum::$MY_FIRST_VALUE-&gt;getDescription().PHP_EOL.PHP_EOL;\n\nvar_dump(EMyEnum::getAllMembers());\n\necho PHP_EOL.EMyEnum::getByCode(2)-&gt;getDescription().PHP_EOL;\n</code></pre>\n<p>And produces this output:</p>\n<blockquote>\n<p>1 : My first value</p>\n<pre><code>array(3) { \n [1]=&gt; \n object(EMyEnum)#1 (2) { \n [&quot;code&quot;:&quot;AbstractEnum&quot;:private]=&gt; \n int(1) \n [&quot;description&quot;:&quot;AbstractEnum&quot;:private]=&gt; \n string(14) &quot;My first value&quot; \n } \n [2]=&gt; \n object(EMyEnum)#2 (2) { \n [&quot;code&quot;:&quot;AbstractEnum&quot;:private]=&gt; \n int(2) \n [&quot;description&quot;:&quot;AbstractEnum&quot;:private]=&gt; \n string(15) &quot;My second value&quot; \n } \n [3]=&gt; \n object(EMyEnum)#3 (2) { \n [&quot;code&quot;:&quot;AbstractEnum&quot;:private]=&gt; \n int(3) \n [&quot;description&quot;:&quot;AbstractEnum&quot;:private]=&gt; \n string(14) &quot;My third value&quot; \n } \n}\n</code></pre>\n<p>My second value</p>\n</blockquote>\n" }, { "answer_id": 16102873, "author": "jglatre", "author_id": 974355, "author_profile": "https://Stackoverflow.com/users/974355", "pm_score": 3, "selected": false, "text": "<pre><code>abstract class Enumeration\n{\n public static function enum() \n {\n $reflect = new ReflectionClass( get_called_class() );\n return $reflect-&gt;getConstants();\n }\n}\n\n\nclass Test extends Enumeration\n{\n const A = 'a';\n const B = 'b'; \n}\n\n\nforeach (Test::enum() as $key =&gt; $value) {\n echo \"$key -&gt; $value&lt;br&gt;\";\n}\n</code></pre>\n" }, { "answer_id": 17045081, "author": "Dan Lugg", "author_id": 409279, "author_profile": "https://Stackoverflow.com/users/409279", "pm_score": 5, "selected": false, "text": "<p>I've commented on some of the other answers here, so I figured I would weigh in too.\nAt the end of the day, since PHP doesn't support typed enumerations, you can go one of two ways: hack out typed enumerations, or live with the fact that they're extremely difficult to hack out effectively.</p>\n\n<p>I prefer to live with the fact, and instead use the <code>const</code> method that other answers here have used in some way or another:</p>\n\n<pre><code>abstract class Enum\n{\n\n const NONE = null;\n\n final private function __construct()\n {\n throw new NotSupportedException(); // \n }\n\n final private function __clone()\n {\n throw new NotSupportedException();\n }\n\n final public static function toArray()\n {\n return (new ReflectionClass(static::class))-&gt;getConstants();\n }\n\n final public static function isValid($value)\n {\n return in_array($value, static::toArray());\n }\n\n}\n</code></pre>\n\n<p>An example enumeration:</p>\n\n<pre><code>final class ResponseStatusCode extends Enum\n{\n\n const OK = 200;\n const CREATED = 201;\n const ACCEPTED = 202;\n // ...\n const SERVICE_UNAVAILABLE = 503;\n const GATEWAY_TIME_OUT = 504;\n const HTTP_VERSION_NOT_SUPPORTED = 505;\n\n}\n</code></pre>\n\n<p>Using <code>Enum</code> as a base class from which all other enumerations extend allows for helper methods, such as <code>toArray</code>, <code>isValid</code>, and so on. To me, typed enumerations (<em>and managing their instances</em>) just end up too messy.</p>\n\n<hr>\n\n<h2>Hypothetical</h2>\n\n<p><strong>If</strong>, there existed a <code>__getStatic</code> magic method (<em>and preferably an <code>__equals</code> magic method too</em>) much of this could be mitigated with a sort of multiton pattern.</p>\n\n<p>(<em>The following is hypothetical; it <strong>won't</strong> work, though perhaps one day it will</em>)</p>\n\n<pre><code>final class TestEnum\n{\n\n private static $_values = [\n 'FOO' =&gt; 1,\n 'BAR' =&gt; 2,\n 'QUX' =&gt; 3,\n ];\n private static $_instances = [];\n\n public static function __getStatic($name)\n {\n if (isset(static::$_values[$name]))\n {\n if (empty(static::$_instances[$name]))\n {\n static::$_instances[$name] = new static($name);\n }\n return static::$_instances[$name];\n }\n throw new Exception(sprintf('Invalid enumeration value, \"%s\"', $name));\n }\n\n private $_value;\n\n public function __construct($name)\n {\n $this-&gt;_value = static::$_values[$name];\n }\n\n public function __equals($object)\n {\n if ($object instanceof static)\n {\n return $object-&gt;_value === $this-&gt;_value;\n }\n return $object === $this-&gt;_value;\n }\n\n}\n\n$foo = TestEnum::$FOO; // object(TestEnum)#1 (1) {\n // [\"_value\":\"TestEnum\":private]=&gt;\n // int(1)\n // }\n\n$zap = TestEnum::$ZAP; // Uncaught exception 'Exception' with message\n // 'Invalid enumeration member, \"ZAP\"'\n\n$qux = TestEnum::$QUX;\nTestEnum::$QUX == $qux; // true\n'hello world!' == $qux; // false\n</code></pre>\n" }, { "answer_id": 18168706, "author": "Songo", "author_id": 636342, "author_profile": "https://Stackoverflow.com/users/636342", "pm_score": 3, "selected": false, "text": "<p>I found <a href=\"https://github.com/myclabs/php-enum\" rel=\"noreferrer\">this library</a> on github and I think it provides a very decent alternative to the answers here.</p>\n\n<h2>PHP Enum implementation inspired from SplEnum</h2>\n\n<ul>\n<li>You can type-hint: <code>function setAction(Action $action) {</code></li>\n<li>You can enrich the enum with methods (e.g. <code>format</code>, <code>parse</code>, …)</li>\n<li>You can extend the enum to add new values (make your enum <code>final</code> to prevent it)</li>\n<li>You can get a list of all the possible values (see below)</li>\n</ul>\n\n<h2>Declaration</h2>\n\n<pre><code>&lt;?php\nuse MyCLabs\\Enum\\Enum;\n\n/**\n * Action enum\n */\nclass Action extends Enum\n{\n const VIEW = 'view';\n const EDIT = 'edit';\n}\n</code></pre>\n\n<h2>Usage</h2>\n\n<pre><code>&lt;?php\n$action = new Action(Action::VIEW);\n\n// or\n$action = Action::VIEW();\n</code></pre>\n\n<h2>type-hint enum values:</h2>\n\n<pre><code>&lt;?php\nfunction setAction(Action $action) {\n // ...\n}\n</code></pre>\n" }, { "answer_id": 21536800, "author": "Neil Townsend", "author_id": 1242380, "author_profile": "https://Stackoverflow.com/users/1242380", "pm_score": 5, "selected": false, "text": "<p>The top answer above is fantastic. However, if you <code>extend</code> it in two different ways, then whichever extension is done first results in a call to the functions will create the cache. This cache will then be used by all subsequent calls, no matter whichever extension the calls are initiated by ...</p>\n\n<p>To solve this, replace the variable and first function with:</p>\n\n<pre><code>private static $constCacheArray = null;\n\nprivate static function getConstants() {\n if (self::$constCacheArray === null) self::$constCacheArray = array();\n\n $calledClass = get_called_class();\n if (!array_key_exists($calledClass, self::$constCacheArray)) {\n $reflect = new \\ReflectionClass($calledClass);\n self::$constCacheArray[$calledClass] = $reflect-&gt;getConstants();\n }\n\n return self::$constCacheArray[$calledClass];\n}\n</code></pre>\n" }, { "answer_id": 25526473, "author": "Buck Fixing", "author_id": 2451283, "author_profile": "https://Stackoverflow.com/users/2451283", "pm_score": 4, "selected": false, "text": "<p>Four years later I came across this again. My current approach is this as it allows for code completion in the IDE as well as type safety:</p>\n\n<p><strong>Base class:</strong></p>\n\n<pre><code>abstract class TypedEnum\n{\n private static $_instancedValues;\n\n private $_value;\n private $_name;\n\n private function __construct($value, $name)\n {\n $this-&gt;_value = $value;\n $this-&gt;_name = $name;\n }\n\n private static function _fromGetter($getter, $value)\n {\n $reflectionClass = new ReflectionClass(get_called_class());\n $methods = $reflectionClass-&gt;getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_PUBLIC); \n $className = get_called_class();\n\n foreach($methods as $method)\n {\n if ($method-&gt;class === $className)\n {\n $enumItem = $method-&gt;invoke(null);\n\n if ($enumItem instanceof $className &amp;&amp; $enumItem-&gt;$getter() === $value)\n {\n return $enumItem;\n }\n }\n }\n\n throw new OutOfRangeException();\n }\n\n protected static function _create($value)\n {\n if (self::$_instancedValues === null)\n {\n self::$_instancedValues = array();\n }\n\n $className = get_called_class();\n\n if (!isset(self::$_instancedValues[$className]))\n {\n self::$_instancedValues[$className] = array();\n }\n\n if (!isset(self::$_instancedValues[$className][$value]))\n {\n $debugTrace = debug_backtrace();\n $lastCaller = array_shift($debugTrace);\n\n while ($lastCaller['class'] !== $className &amp;&amp; count($debugTrace) &gt; 0)\n {\n $lastCaller = array_shift($debugTrace);\n }\n\n self::$_instancedValues[$className][$value] = new static($value, $lastCaller['function']);\n }\n\n return self::$_instancedValues[$className][$value];\n }\n\n public static function fromValue($value)\n {\n return self::_fromGetter('getValue', $value);\n }\n\n public static function fromName($value)\n {\n return self::_fromGetter('getName', $value);\n }\n\n public function getValue()\n {\n return $this-&gt;_value;\n }\n\n public function getName()\n {\n return $this-&gt;_name;\n }\n}\n</code></pre>\n\n<p><strong>Example Enum:</strong></p>\n\n<pre><code>final class DaysOfWeek extends TypedEnum\n{\n public static function Sunday() { return self::_create(0); } \n public static function Monday() { return self::_create(1); }\n public static function Tuesday() { return self::_create(2); } \n public static function Wednesday() { return self::_create(3); }\n public static function Thursday() { return self::_create(4); } \n public static function Friday() { return self::_create(5); }\n public static function Saturday() { return self::_create(6); } \n}\n</code></pre>\n\n<p><strong>Example usage:</strong></p>\n\n<pre><code>function saveEvent(DaysOfWeek $weekDay, $comment)\n{\n // store week day numeric value and comment:\n $myDatabase-&gt;save('myeventtable', \n array('weekday_id' =&gt; $weekDay-&gt;getValue()),\n array('comment' =&gt; $comment));\n}\n\n// call the function, note: DaysOfWeek::Monday() returns an object of type DaysOfWeek\nsaveEvent(DaysOfWeek::Monday(), 'some comment');\n</code></pre>\n\n<p>Note that all instances of the same enum entry are the same:</p>\n\n<pre><code>$monday1 = DaysOfWeek::Monday();\n$monday2 = DaysOfWeek::Monday();\n$monday1 === $monday2; // true\n</code></pre>\n\n<p>You can also use it inside of a switch statement:</p>\n\n<pre><code>function getGermanWeekDayName(DaysOfWeek $weekDay)\n{\n switch ($weekDay)\n {\n case DaysOfWeek::Monday(): return 'Montag';\n case DaysOfWeek::Tuesday(): return 'Dienstag';\n // ...\n}\n</code></pre>\n\n<p>You can also create an enum entry by name or value:</p>\n\n<pre><code>$monday = DaysOfWeek::fromValue(2);\n$tuesday = DaysOfWeek::fromName('Tuesday');\n</code></pre>\n\n<p>Or you can just get the name (i.e. the function name) from an existing enum entry:</p>\n\n<pre><code>$wednesday = DaysOfWeek::Wednesday()\necho $wednesDay-&gt;getName(); // Wednesday\n</code></pre>\n" }, { "answer_id": 27941072, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>// My Enumeration Class\nclass Enum\n{\n protected $m_actions = array();\n\n public function __construct($actions)\n {\n $this-&gt;init($actions);\n }\n\n public function init($actions)\n {\n $this-&gt;m_actions = array();\n for($i = 0; $i &lt; count($actions); ++$i)\n {\n $this-&gt;m_actions[$actions[$i]] = ($i + 1); \n define($actions[$i], ($i + 1));\n }\n }\n\n public function toString($index)\n {\n $keys = array_keys($this-&gt;m_actions);\n for($i = 0; $i &lt; count($keys); ++$i)\n {\n if($this-&gt;m_actions[$keys[$i]] == $index)\n {\n return $keys[$i];\n }\n }\n\n return \"undefined\";\n }\n\n public function fromString($str)\n {\n return $this-&gt;m_actions[$str];\n }\n}\n\n// Enumeration creation\n$actions = new Enum(array(\"CREATE\", \"READ\", \"UPDATE\", \"DELETE\"));\n\n// Examples\nprint($action_objects-&gt;toString(DELETE));\nprint($action_objects-&gt;fromString(\"DELETE\"));\n\nif($action_objects-&gt;fromString($_POST[\"myAction\"]) == CREATE)\n{\n print(\"CREATE\");\n}\n</code></pre>\n" }, { "answer_id": 28747652, "author": "Torge", "author_id": 2075537, "author_profile": "https://Stackoverflow.com/users/2075537", "pm_score": 3, "selected": false, "text": "<p>My Enum class definition below is <strong>Strongly typed</strong>, and very <strong>natural</strong> to use and define.</p>\n\n<p><strong>Definition:</strong></p>\n\n<pre><code>class Fruit extends Enum {\n static public $APPLE = 1;\n static public $ORANGE = 2;\n}\nFruit::initialize(); //Can also be called in autoloader\n</code></pre>\n\n<p><strong>Switch over Enum</strong></p>\n\n<pre><code>$myFruit = Fruit::$APPLE;\n\nswitch ($myFruit) {\n case Fruit::$APPLE : echo \"I like apples\\n\"; break;\n case Fruit::$ORANGE : echo \"I hate oranges\\n\"; break;\n}\n\n&gt;&gt; I like apples\n</code></pre>\n\n<p><strong>Pass Enum as parameter (Strongly typed)</strong></p>\n\n<pre><code>/** Function only accepts Fruit enums as input**/\nfunction echoFruit(Fruit $fruit) {\n echo $fruit-&gt;getName().\": \".$fruit-&gt;getValue().\"\\n\";\n}\n\n/** Call function with each Enum value that Fruit has */\nforeach (Fruit::getList() as $fruit) {\n echoFruit($fruit);\n}\n\n//Call function with Apple enum\nechoFruit(Fruit::$APPLE)\n\n//Will produce an error. This solution is strongly typed\nechoFruit(2);\n\n&gt;&gt; APPLE: 1\n&gt;&gt; ORANGE: 2\n&gt;&gt; APPLE: 1\n&gt;&gt; Argument 1 passed to echoFruit() must be an instance of Fruit, integer given\n</code></pre>\n\n<p><strong>Echo Enum as string</strong></p>\n\n<pre><code>echo \"I have an $myFruit\\n\";\n\n&gt;&gt; I have an APPLE\n</code></pre>\n\n<p><strong>Get Enum by integer</strong></p>\n\n<pre><code>$myFruit = Fruit::getByValue(2);\n\necho \"Now I have an $myFruit\\n\";\n\n&gt;&gt; Now I have an ORANGE\n</code></pre>\n\n<p><strong>Get Enum by Name</strong></p>\n\n<pre><code>$myFruit = Fruit::getByName(\"APPLE\");\n\necho \"But I definitely prefer an $myFruit\\n\\n\";\n\n&gt;&gt; But I definitely prefer an APPLE\n</code></pre>\n\n<p><strong>The Enum Class:</strong></p>\n\n<pre><code>/**\n * @author Torge Kummerow\n */\nclass Enum {\n\n /**\n * Holds the values for each type of Enum\n */\n static private $list = array();\n\n /**\n * Initializes the enum values by replacing the number with an instance of itself\n * using reflection\n */\n static public function initialize() {\n $className = get_called_class();\n $class = new ReflectionClass($className);\n $staticProperties = $class-&gt;getStaticProperties();\n\n self::$list[$className] = array();\n\n foreach ($staticProperties as $propertyName =&gt; &amp;$value) {\n if ($propertyName == 'list')\n continue;\n\n $enum = new $className($propertyName, $value);\n $class-&gt;setStaticPropertyValue($propertyName, $enum);\n self::$list[$className][$propertyName] = $enum;\n } unset($value);\n }\n\n\n /**\n * Gets the enum for the given value\n *\n * @param integer $value\n * @throws Exception\n *\n * @return Enum\n */\n static public function getByValue($value) {\n $className = get_called_class();\n foreach (self::$list[$className] as $propertyName=&gt;&amp;$enum) {\n /* @var $enum Enum */\n if ($enum-&gt;value == $value)\n return $enum;\n } unset($enum);\n\n throw new Exception(\"No such enum with value=$value of type \".get_called_class());\n }\n\n /**\n * Gets the enum for the given name\n *\n * @param string $name\n * @throws Exception\n *\n * @return Enum\n */\n static public function getByName($name) {\n $className = get_called_class();\n if (array_key_exists($name, static::$list[$className]))\n return self::$list[$className][$name];\n\n throw new Exception(\"No such enum \".get_called_class().\"::\\$$name\");\n }\n\n\n /**\n * Returns the list of all enum variants\n * @return Array of Enum\n */\n static public function getList() {\n $className = get_called_class();\n return self::$list[$className];\n }\n\n\n private $name;\n private $value;\n\n public function __construct($name, $value) {\n $this-&gt;name = $name;\n $this-&gt;value = $value;\n }\n\n public function __toString() {\n return $this-&gt;name;\n }\n\n public function getValue() {\n return $this-&gt;value;\n }\n\n public function getName() {\n return $this-&gt;name;\n }\n\n}\n</code></pre>\n\n<p><strong>Addition</strong></p>\n\n<p>You can ofcourse also add comments for IDEs</p>\n\n<pre><code>class Fruit extends Enum {\n\n /**\n * This comment is for autocomplete support in common IDEs\n * @var Fruit A yummy apple\n */\n static public $APPLE = 1;\n\n /**\n * This comment is for autocomplete support in common IDEs\n * @var Fruit A sour orange\n */\n static public $ORANGE = 2;\n}\n\n//This can also go to the autoloader if available.\nFruit::initialize();\n</code></pre>\n" }, { "answer_id": 28789884, "author": "Jesse", "author_id": 268083, "author_profile": "https://Stackoverflow.com/users/268083", "pm_score": 2, "selected": false, "text": "<pre><code>class DayOfWeek {\n static $values = array(\n self::MONDAY,\n self::TUESDAY,\n // ...\n );\n\n const MONDAY = 0;\n const TUESDAY = 1;\n // ...\n}\n\n$today = DayOfWeek::MONDAY;\n\n// If you want to check if a value is valid\nassert( in_array( $today, DayOfWeek::$values ) );\n</code></pre>\n\n<p>Don't use reflection. It makes it extremely difficult to reason about your code and track down where something is being used, and tends to break static analysis tools (eg what's built into your IDE).</p>\n" }, { "answer_id": 29358610, "author": "Chris Middleton", "author_id": 2407870, "author_profile": "https://Stackoverflow.com/users/2407870", "pm_score": 2, "selected": false, "text": "<p>One of the aspects missing from some of the other answers here is a way to use enums with type hinting.</p>\n\n<p>If you define your enum as a set of constants in an abstract class, e.g.</p>\n\n<pre><code>abstract class ShirtSize {\n public const SMALL = 1;\n public const MEDIUM = 2;\n public const LARGE = 3;\n}\n</code></pre>\n\n<p>then you can't type hint it in a function parameter - for one, because it's not instantiable, but also because the type of <code>ShirtSize::SMALL</code> is <code>int</code>, not <code>ShirtSize</code>.</p>\n\n<p>That's why native enums in PHP would be so much better than anything we can come up with. However, we can approximate an enum by keeping a private property which represents the value of the enum, and then restricting the initialization of this property to our predefined constants. To prevent the enum from being instantiated arbitrarily (without the overhead of type-checking a whitelist), we make the constructor private.</p>\n\n<pre><code>class ShirtSize {\n private $size;\n private function __construct ($size) {\n $this-&gt;size = $size;\n }\n public function equals (ShirtSize $s) {\n return $this-&gt;size === $s-&gt;size;\n }\n public static function SMALL () { return new self(1); }\n public static function MEDIUM () { return new self(2); }\n public static function LARGE () { return new self(3); }\n}\n</code></pre>\n\n<p>Then we can use <code>ShirtSize</code> like this:</p>\n\n<pre><code>function sizeIsAvailable ($productId, ShirtSize $size) {\n // business magic\n}\nif(sizeIsAvailable($_GET[\"id\"], ShirtSize::LARGE())) {\n echo \"Available\";\n} else {\n echo \"Out of stock.\";\n}\n$s2 = ShirtSize::SMALL();\n$s3 = ShirtSize::MEDIUM();\necho $s2-&gt;equals($s3) ? \"SMALL == MEDIUM\" : \"SMALL != MEDIUM\";\n</code></pre>\n\n<p>This way, the biggest difference from the user's perspective is that you have to tack on a <code>()</code> on the constant's name.</p>\n\n<p>One downside though is that <code>===</code> (which compares object equality) will return false when <code>==</code> returns true. For that reason, it's best to provide an <code>equals</code> method, so that users don't have to remember to use <code>==</code> and not <code>===</code> to compare two enum values.</p>\n\n<p>EDIT: A couple of the existing answers are very similar, particularly: <a href=\"https://stackoverflow.com/a/25526473/2407870\">https://stackoverflow.com/a/25526473/2407870</a>.</p>\n" }, { "answer_id": 29924814, "author": "Mark Manning", "author_id": 928121, "author_profile": "https://Stackoverflow.com/users/928121", "pm_score": 3, "selected": false, "text": "<p>I realize this is a very-very-very old thread but I had a thought about this and wanted to know what people thought.</p>\n\n<p>Notes: I was playing around with this and realized that if I just modified the <code>__call()</code> function that you can get even closer to actual <code>enums</code>. The <code>__call()</code> function handles all unknown function calls. So let's say you want to make three <code>enums</code> RED_LIGHT, YELLOW_LIGHT, and GREEN_LIGHT. You can do so now by just doing the following:</p>\n\n<pre><code>$c-&gt;RED_LIGHT();\n$c-&gt;YELLOW_LIGHT();\n$c-&gt;GREEN_LIGHT();\n</code></pre>\n\n<p>Once defined all you have to do is to call them again to get the values:</p>\n\n<pre><code>echo $c-&gt;RED_LIGHT();\necho $c-&gt;YELLOW_LIGHT();\necho $c-&gt;GREEN_LIGHT();\n</code></pre>\n\n<p>and you should get 0, 1, and 2. Have fun! This is also now up on GitHub.</p>\n\n<p>Update: I've made it so both the <code>__get()</code> and <code>__set()</code> functions are now used. These allow you to not have to call a function unless you want to. Instead, now you can just say:</p>\n\n<pre><code>$c-&gt;RED_LIGHT;\n$c-&gt;YELLOW_LIGHT;\n$c-&gt;GREEN_LIGHT;\n</code></pre>\n\n<p>For both the creation and getting of the values. Because the variables haven't been defined initially, the <code>__get()</code> function is called (because there isn't a value specified) which sees that the entry in the array hasn't been made. So it makes the entry, assigns it the last value given plus one(+1), increments the last value variable, and returns TRUE. If you set the value:</p>\n\n<pre><code>$c-&gt;RED_LIGHT = 85;\n</code></pre>\n\n<p>Then the <code>__set()</code> function is called and the last value is then set to the new value plus one (+1). So now we have a fairly good way to do enums and they can be created on the fly.</p>\n\n<pre><code>&lt;?php\n################################################################################\n# Class ENUMS\n#\n# Original code by Mark Manning.\n# Copyrighted (c) 2015 by Mark Manning.\n# All rights reserved.\n#\n# This set of code is hereby placed into the free software universe\n# via the GNU greater license thus placing it under the Copyleft\n# rules and regulations with the following modifications:\n#\n# 1. You may use this work in any other work. Commercial or otherwise.\n# 2. You may make as much money as you can with it.\n# 3. You owe me nothing except to give me a small blurb somewhere in\n# your program or maybe have pity on me and donate a dollar to\n# [email protected]. :-)\n#\n# Blurb:\n#\n# PHP Class Enums by Mark Manning (markem-AT-sim1-DOT-us).\n# Used with permission.\n#\n# Notes:\n#\n# VIM formatting. Set tabs to four(4) spaces.\n#\n################################################################################\nclass enums\n{\n private $enums;\n private $clear_flag;\n private $last_value;\n\n################################################################################\n# __construct(). Construction function. Optionally pass in your enums.\n################################################################################\nfunction __construct()\n{\n $this-&gt;enums = array();\n $this-&gt;clear_flag = false;\n $this-&gt;last_value = 0;\n\n if( func_num_args() &gt; 0 ){\n return $this-&gt;put( func_get_args() );\n }\n\n return true;\n}\n################################################################################\n# put(). Insert one or more enums.\n################################################################################\nfunction put()\n{\n $args = func_get_args();\n#\n# Did they send us an array of enums?\n# Ex: $c-&gt;put( array( \"a\"=&gt;0, \"b\"=&gt;1,...) );\n# OR $c-&gt;put( array( \"a\", \"b\", \"c\",... ) );\n#\n if( is_array($args[0]) ){\n#\n# Add them all in\n#\n foreach( $args[0] as $k=&gt;$v ){\n#\n# Don't let them change it once it is set.\n# Remove the IF statement if you want to be able to modify the enums.\n#\n if( !isset($this-&gt;enums[$k]) ){\n#\n# If they sent an array of enums like this: \"a\",\"b\",\"c\",... then we have to\n# change that to be \"A\"=&gt;#. Where \"#\" is the current count of the enums.\n#\n if( is_numeric($k) ){\n $this-&gt;enums[$v] = $this-&gt;last_value++;\n }\n#\n# Else - they sent \"a\"=&gt;\"A\", \"b\"=&gt;\"B\", \"c\"=&gt;\"C\"...\n#\n else {\n $this-&gt;last_value = $v + 1;\n $this-&gt;enums[$k] = $v;\n }\n }\n }\n }\n#\n# Nope! Did they just sent us one enum?\n#\n else {\n#\n# Is this just a default declaration?\n# Ex: $c-&gt;put( \"a\" );\n#\n if( count($args) &lt; 2 ){\n#\n# Again - remove the IF statement if you want to be able to change the enums.\n#\n if( !isset($this-&gt;enums[$args[0]]) ){\n $this-&gt;enums[$args[0]] = $this-&gt;last_value++;\n }\n#\n# No - they sent us a regular enum\n# Ex: $c-&gt;put( \"a\", \"This is the first enum\" );\n#\n else {\n#\n# Again - remove the IF statement if you want to be able to change the enums.\n#\n if( !isset($this-&gt;enums[$args[0]]) ){\n $this-&gt;last_value = $args[1] + 1;\n $this-&gt;enums[$args[0]] = $args[1];\n }\n }\n }\n }\n\n return true;\n}\n################################################################################\n# get(). Get one or more enums.\n################################################################################\nfunction get()\n{\n $num = func_num_args();\n $args = func_get_args();\n#\n# Is this an array of enums request? (ie: $c-&gt;get(array(\"a\",\"b\",\"c\"...)) )\n#\n if( is_array($args[0]) ){\n $ary = array();\n foreach( $args[0] as $k=&gt;$v ){\n $ary[$v] = $this-&gt;enums[$v];\n }\n\n return $ary;\n }\n#\n# Is it just ONE enum they want? (ie: $c-&gt;get(\"a\") )\n#\n else if( ($num &gt; 0) &amp;&amp; ($num &lt; 2) ){\n return $this-&gt;enums[$args[0]];\n }\n#\n# Is it a list of enums they want? (ie: $c-&gt;get( \"a\", \"b\", \"c\"...) )\n#\n else if( $num &gt; 1 ){\n $ary = array();\n foreach( $args as $k=&gt;$v ){\n $ary[$v] = $this-&gt;enums[$v];\n }\n\n return $ary;\n }\n#\n# They either sent something funky or nothing at all.\n#\n return false;\n}\n################################################################################\n# clear(). Clear out the enum array.\n# Optional. Set the flag in the __construct function.\n# After all, ENUMS are supposed to be constant.\n################################################################################\nfunction clear()\n{\n if( $clear_flag ){\n unset( $this-&gt;enums );\n $this-&gt;enums = array();\n }\n\n return true;\n}\n################################################################################\n# __call(). In case someone tries to blow up the class.\n################################################################################\nfunction __call( $name, $arguments )\n{\n if( isset($this-&gt;enums[$name]) ){ return $this-&gt;enums[$name]; }\n else if( !isset($this-&gt;enums[$name]) &amp;&amp; (count($arguments) &gt; 0) ){\n $this-&gt;last_value = $arguments[0] + 1;\n $this-&gt;enums[$name] = $arguments[0];\n return true;\n }\n else if( !isset($this-&gt;enums[$name]) &amp;&amp; (count($arguments) &lt; 1) ){\n $this-&gt;enums[$name] = $this-&gt;last_value++;\n return true;\n }\n\n return false;\n}\n################################################################################\n# __get(). Gets the value.\n################################################################################\nfunction __get($name)\n{\n if( isset($this-&gt;enums[$name]) ){ return $this-&gt;enums[$name]; }\n else if( !isset($this-&gt;enums[$name]) ){\n $this-&gt;enums[$name] = $this-&gt;last_value++;\n return true;\n }\n\n return false;\n}\n################################################################################\n# __set(). Sets the value.\n################################################################################\nfunction __set( $name, $value=null )\n{\n if( isset($this-&gt;enums[$name]) ){ return false; }\n else if( !isset($this-&gt;enums[$name]) &amp;&amp; !is_null($value) ){\n $this-&gt;last_value = $value + 1;\n $this-&gt;enums[$name] = $value;\n return true;\n }\n else if( !isset($this-&gt;enums[$name]) &amp;&amp; is_null($value) ){\n $this-&gt;enums[$name] = $this-&gt;last_value++;\n return true;\n }\n\n return false;\n}\n################################################################################\n# __destruct(). Deconstruct the class. Remove the list of enums.\n################################################################################\nfunction __destruct()\n{\n unset( $this-&gt;enums );\n $this-&gt;enums = null;\n\n return true;\n}\n\n}\n#\n# Test code\n#\n# $c = new enums();\n# $c-&gt;RED_LIGHT(85);\n# $c-&gt;YELLOW_LIGHT = 23;\n# $c-&gt;GREEN_LIGHT;\n#\n# echo $c-&gt;RED_LIGHT . \"\\n\";\n# echo $c-&gt;YELLOW_LIGHT . \"\\n\";\n# echo $c-&gt;GREEN_LIGHT . \"\\n\";\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 30507927, "author": "mykhal", "author_id": 234248, "author_profile": "https://Stackoverflow.com/users/234248", "pm_score": 3, "selected": false, "text": "<p>It might be as simple as</p>\n\n<pre><code>enum DaysOfWeek {\n Sunday,\n Monday,\n // ...\n}\n</code></pre>\n\n<p>in the future.</p>\n\n<p><a href=\"https://wiki.php.net/rfc/enum\" rel=\"noreferrer\">PHP RFC: Enumerated Types</a></p>\n" }, { "answer_id": 33041402, "author": "Loupax", "author_id": 208271, "author_profile": "https://Stackoverflow.com/users/208271", "pm_score": 2, "selected": false, "text": "<p>Stepping on the answer of @Brian Cline I thought I might give my 5 cents</p>\n\n<pre><code>&lt;?php \n/**\n * A class that simulates Enums behaviour\n * &lt;code&gt;\n * class Season extends Enum{\n * const Spring = 0;\n * const Summer = 1;\n * const Autumn = 2;\n * const Winter = 3;\n * }\n * \n * $currentSeason = new Season(Season::Spring);\n * $nextYearSeason = new Season(Season::Spring);\n * $winter = new Season(Season::Winter);\n * $whatever = new Season(-1); // Throws InvalidArgumentException\n * echo $currentSeason.is(Season::Spring); // True\n * echo $currentSeason.getName(); // 'Spring'\n * echo $currentSeason.is($nextYearSeason); // True\n * echo $currentSeason.is(Season::Winter); // False\n * echo $currentSeason.is(Season::Spring); // True\n * echo $currentSeason.is($winter); // False\n * &lt;/code&gt;\n * \n * Class Enum\n * \n * PHP Version 5.5\n */\nabstract class Enum\n{\n /**\n * Will contain all the constants of every enum that gets created to \n * avoid expensive ReflectionClass usage\n * @var array\n */\n private static $_constCacheArray = [];\n /**\n * The value that separates this instance from the rest of the same class\n * @var mixed\n */\n private $_value;\n /**\n * The label of the Enum instance. Will take the string name of the \n * constant provided, used for logging and human readable messages\n * @var string\n */\n private $_name;\n /**\n * Creates an enum instance, while makes sure that the value given to the \n * enum is a valid one\n * \n * @param mixed $value The value of the current\n * \n * @throws \\InvalidArgumentException\n */\n public final function __construct($value)\n {\n $constants = self::_getConstants();\n if (count($constants) !== count(array_unique($constants))) {\n throw new \\InvalidArgumentException('Enums cannot contain duplicate constant values');\n }\n if ($name = array_search($value, $constants)) {\n $this-&gt;_value = $value;\n $this-&gt;_name = $name;\n } else {\n throw new \\InvalidArgumentException('Invalid enum value provided');\n }\n }\n /**\n * Returns the constant name of the current enum instance\n * \n * @return string\n */\n public function getName()\n {\n return $this-&gt;_name;\n }\n /**\n * Returns the value of the current enum instance\n * \n * @return mixed\n */\n public function getValue()\n {\n return $this-&gt;_value;\n }\n /**\n * Checks whether this enum instance matches with the provided one.\n * This function should be used to compare Enums at all times instead\n * of an identity comparison \n * &lt;code&gt;\n * // Assuming EnumObject and EnumObject2 both extend the Enum class\n * // and constants with such values are defined\n * $var = new EnumObject('test'); \n * $var2 = new EnumObject('test');\n * $var3 = new EnumObject2('test');\n * $var4 = new EnumObject2('test2');\n * echo $var-&gt;is($var2); // true\n * echo $var-&gt;is('test'); // true\n * echo $var-&gt;is($var3); // false\n * echo $var3-&gt;is($var4); // false\n * &lt;/code&gt;\n * \n * @param mixed|Enum $enum The value we are comparing this enum object against\n * If the value is instance of the Enum class makes\n * sure they are instances of the same class as well, \n * otherwise just ensures they have the same value\n * \n * @return bool\n */\n public final function is($enum)\n {\n // If we are comparing enums, just make\n // sure they have the same toString value\n if (is_subclass_of($enum, __CLASS__)) {\n return get_class($this) === get_class($enum) \n &amp;&amp; $this-&gt;getValue() === $enum-&gt;getValue();\n } else {\n // Otherwise assume $enum is the value we are comparing against\n // and do an exact comparison\n return $this-&gt;getValue() === $enum; \n }\n }\n\n /**\n * Returns the constants that are set for the current Enum instance\n * \n * @return array\n */\n private static function _getConstants()\n {\n if (self::$_constCacheArray == null) {\n self::$_constCacheArray = [];\n }\n $calledClass = get_called_class();\n if (!array_key_exists($calledClass, self::$_constCacheArray)) {\n $reflect = new \\ReflectionClass($calledClass);\n self::$_constCacheArray[$calledClass] = $reflect-&gt;getConstants();\n }\n return self::$_constCacheArray[$calledClass];\n }\n}\n</code></pre>\n" }, { "answer_id": 43825552, "author": "Ismaelj", "author_id": 392484, "author_profile": "https://Stackoverflow.com/users/392484", "pm_score": 0, "selected": false, "text": "<p>A simpler and lighter version that doesn't use reflection:</p>\n\n<pre><code>abstract class enum {\n private function __construct() {}\n static function has($const) {\n $name = get_called_class();\n return defined(\"$name::$const\");\n }\n static function value($const) {\n $name = get_called_class();\n return defined(\"$name::$const\")? constant(\"$name::$const\") : false;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>class requestFormat extends enum { const HTML = 1; const JSON = 2; const XML = 3; const FORM = 4; }\n\necho requestFormat::value('JSON'); // 2\necho requestFormat::has('JSON'); // true\n</code></pre>\n\n<p>This gives the advantage of constants and also allows for checking the validity of them but it lacks other fancy functionality provided by more complex solutions given is this question, the more obvious the inability of checking the reverse of a value (in the example above, you can't check if '2' is a valid value) </p>\n" }, { "answer_id": 48402367, "author": "user986730", "author_id": 986730, "author_profile": "https://Stackoverflow.com/users/986730", "pm_score": 0, "selected": false, "text": "<p>If you want type safety and a bunch of constants that match that type, one way to go is to have an abstract class for your enum and then extend that class with a locked constructor, like so:</p>\n\n<pre><code>abstract class DaysOfWeekEnum{\n public function __construct(string $value){\n $this-&gt;value = $value; \n }\n public function __toString(){\n return $this-&gt;value;\n }\n\n}\nclass Monday extends DaysOfWeekEnum{\n public function __construct(){\n parent::__construct(\"Monday\");\n }\n}\n\nclass Tuesday extends DaysOfWeekEnum{\n public function __construct(){\n parent::__construct(\"Tuesday\");\n }\n}\n</code></pre>\n\n<p>Then you can have your methods take an instance of DaysOfWeek and pass it an instance of Monday, Tuesday, etc... The only downside is having to 'new-up' an instance every time you want to use your enum, but I find it worth it.</p>\n\n<pre><code>function printWeekDay(DaysOfWeek $day){\n echo \"Today is $day.\";\n}\n\nprintWeekDay(new Monday());\n</code></pre>\n" }, { "answer_id": 50545442, "author": "Krishnadas PC", "author_id": 2295484, "author_profile": "https://Stackoverflow.com/users/2295484", "pm_score": 2, "selected": false, "text": "<p>Now you can use The <strong>SplEnum</strong> class to build it natively. As per the official documentation.</p>\n<blockquote>\n<p>SplEnum gives the ability to emulate and create enumeration objects\nnatively in PHP.</p>\n</blockquote>\n<pre><code>&lt;?php\nclass Month extends SplEnum {\n const __default = self::January;\n\n const January = 1;\n const February = 2;\n const March = 3;\n const April = 4;\n const May = 5;\n const June = 6;\n const July = 7;\n const August = 8;\n const September = 9;\n const October = 10;\n const November = 11;\n const December = 12;\n}\n\necho new Month(Month::June) . PHP_EOL;\n\ntry {\n new Month(13);\n} catch (UnexpectedValueException $uve) {\n echo $uve-&gt;getMessage() . PHP_EOL;\n}\n?&gt;\n</code></pre>\n<p>Please note it's an extension which has to be installed, but it is not available by default. Which comes under <a href=\"http://php.net/manual/en/book.spl-types.php\" rel=\"nofollow noreferrer\">Special Types</a> described on the PHP website itself. The above example is taken from the PHP site.</p>\n" }, { "answer_id": 52268643, "author": "Anthony Rutledge", "author_id": 2495645, "author_profile": "https://Stackoverflow.com/users/2495645", "pm_score": 3, "selected": false, "text": "<p>Finally, a <strong>PHP 7.1+</strong> answer with constants that cannot be overridden.</p>\n<pre><code>/**\n * An interface that groups HTTP Accept: header Media Types in one place.\n */\ninterface MediaTypes\n{\n /**\n * Now, if you have to use these same constants with another class, you can\n * without creating funky inheritance / is-a relationships.\n * Also, this gets around the single inheritance limitation.\n */\n\n public const HTML = 'text/html';\n public const JSON = 'application/json';\n public const XML = 'application/xml';\n public const TEXT = 'text/plain';\n}\n\n/**\n * An generic request class.\n */\nabstract class Request\n{\n // Why not put the constants here?\n // 1) The logical reuse issue.\n // 2) Single Inheritance.\n // 3) Overriding is possible.\n\n // Why put class constants here?\n // 1) The constant value will not be necessary in other class families.\n}\n\n/**\n * An incoming / server-side HTTP request class.\n */\nclass HttpRequest extends Request implements MediaTypes\n{\n // This class can implement groups of constants as necessary.\n}\n</code></pre>\n<p>If you are using namespaces, code completion should work.</p>\n<p>However, in doing this, you lose the ability to hide the constants within the class family (<code>protected</code>) or class alone (<code>private</code>). By definition, everything in an <code>Interface</code> is <code>public</code>.</p>\n<p><a href=\"http://www.php.net/manual/en/language.oop5.interfaces.php\" rel=\"nofollow noreferrer\">PHP Manual: Interfaces</a></p>\n<p><strong>Update:</strong></p>\n<p>PHP 8.1 now has <a href=\"http://%20https://www.php.net/manual/en/language.enumerations.php\" rel=\"nofollow noreferrer\">enumerations</a>.</p>\n" }, { "answer_id": 59597159, "author": "the liquid metal", "author_id": 442388, "author_profile": "https://Stackoverflow.com/users/442388", "pm_score": 2, "selected": false, "text": "<p>Based on <a href=\"https://gist.github.com/the-liquid-metal/a2608f197e1241d11c956890b7c8a635\" rel=\"nofollow noreferrer\">this gist</a>, a base class for all enums:</p>\n<pre><code>abstract class Enum {\n protected $val;\n\n protected function __construct($arg) {\n $this-&gt;val = $arg;\n }\n\n public function __toString() {\n return $this-&gt;val;\n }\n\n public function __set($arg1, $arg2) {\n throw new Exception(&quot;enum does not have property&quot;);\n }\n\n public function __get($arg1) {\n throw new Exception(&quot;enum does not have property&quot;);\n }\n\n // not really needed\n public function __call($arg1, $arg2) {\n throw new Exception(&quot;enum does not have method&quot;);\n }\n\n // not really needed\n static public function __callStatic($arg1, $arg2) {\n throw new Exception(&quot;enum does not have static method&quot;);\n }\n}\n</code></pre>\n<p>Your enum:</p>\n<pre><code>final class MyEnum extends Enum {\n static public function val1() {\n return new self(&quot;val1&quot;);\n }\n\n static public function val2() {\n return new self(&quot;val2&quot;);\n }\n\n static public function val3() {\n return new self(&quot;val3&quot;);\n }\n}\n</code></pre>\n<p>Test it:</p>\n<pre><code>$a = MyEnum::val1();\necho &quot;1.the enum value is '$a'\\n&quot;;\n\nfunction consumeMyEnum(MyEnum $arg) {\n return &quot;2.the return value is '$arg'\\n&quot;;\n}\n\necho consumeMyEnum($a);\n$version = explode(&quot;.&quot;, PHP_VERSION);\nif ($version[0] &gt;= 7) {\n try {\n echo consumeMyEnum(&quot;val1&quot;);\n } catch (TypeError $e) {\n echo &quot;3.passing argument error happens (PHP 7.0 and above)\\n&quot;;\n }\n}\n\necho ($a == MyEnum::val1()) ? &quot;4.same\\n&quot; : &quot;4.different\\n&quot;;\necho ($a == MyEnum::val2()) ? &quot;5.same\\n&quot; : &quot;5.different\\n&quot;;\n\n$b = MyEnum::val1();\necho ($a == $b) ? &quot;6.same\\n&quot; : &quot;6.different\\n&quot;;\necho ($a === $b) ? &quot;7.same\\n&quot; : &quot;7.different\\n&quot;;\n\n$c = MyEnum::val2();\necho ($a == $c) ? &quot;8.same\\n&quot; : &quot;8.different\\n&quot;;\necho ($a === $c) ? &quot;9.same\\n&quot; : &quot;9.different\\n&quot;;\n\nswitch ($c) {\n case MyEnum::val1(): echo &quot;10.case of 1st\\n&quot;; break;\n case MyEnum::val2(): echo &quot;11.case of 2nd\\n&quot;; break;\n case MyEnum::val3(): echo &quot;12.case of 3rd\\n&quot;; break;\n}\n\ntry {\n $a-&gt;prop = 10;\n} catch (Exception $e) {\n echo &quot;13.set property error happens\\n&quot;;\n}\n\ntry {\n echo $a-&gt;prop;\n} catch (Exception $e) {\n echo &quot;14.get property error happens\\n&quot;;\n}\n\ntry {\n echo $a-&gt;meth();\n} catch (Exception $e) {\n echo &quot;15.method call error happens\\n&quot;;\n}\n\ntry {\n echo MyEnum::meth();\n} catch (Exception $e) {\n echo &quot;16.static method call error happens\\n&quot;;\n}\n\nclass Ordinary {}\necho $a instanceof MyEnum ? &quot;17.MyEnum instance\\n&quot; : &quot;17.not MyEnum instance\\n&quot;;\necho $a instanceof Enum ? &quot;18.Enum instance\\n&quot; : &quot;18.not Enum instance\\n&quot;;\necho $a instanceof Ordinary ? &quot;19.Ordinary instance\\n&quot; : &quot;19.not Ordinary instance\\n&quot;;\n</code></pre>\n<p>Try it online: <a href=\"http://sandbox.onlinephpfunctions.com/code/2af23ef344ed1af47785e4dedf7bbc96d84f172f\" rel=\"nofollow noreferrer\">sandbox</a></p>\n" }, { "answer_id": 66208862, "author": "yivi", "author_id": 1426539, "author_profile": "https://Stackoverflow.com/users/1426539", "pm_score": 7, "selected": false, "text": "<h2>From PHP 8.1, you can use <a href=\"https://wiki.php.net/rfc/enumerations\" rel=\"noreferrer\">native enumerations</a>.</h2>\n<p>The basic syntax looks like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>enum TransportMode {\n case Bicycle;\n case Car;\n case Ship;\n case Plane;\n case Feet;\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>function travelCost(TransportMode $mode, int $distance): int\n{ /* implementation */ } \n\n$mode = TransportMode::Boat;\n\n$bikeCost = travelCost(TransportMode::Bicycle, 90);\n$boatCost = travelCost($mode, 90);\n\n// this one would fail: (Enums are singletons, not scalars)\n$failCost = travelCost('Car', 90);\n</code></pre>\n<h3>Values</h3>\n<p>By default, enumerations are not backed by any kind of scalar. So <code>TransportMode::Bicycle</code> is not <code>0</code>, and you cannot compare using <code>&gt;</code> or <code>&lt;</code> between enumerations.</p>\n<p>But the following works:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$foo = TransportMode::Car;\n$bar = TransportMode::Car;\n$baz = TransportMode::Bicycle;\n\n$foo === $bar; // true\n$bar === $baz; // false\n\n$foo instanceof TransportMode; // true\n\n$foo &gt; $bar || $foo &lt; $bar; // false either way\n</code></pre>\n<h3>Backed Enumerations</h3>\n<p>You can also have &quot;backed&quot; enums, where each enumeration case is &quot;backed&quot; by either an <code>int</code> or a <code>string</code>.</p>\n<pre class=\"lang-php prettyprint-override\"><code>enum Metal: int {\n case Gold = 1932;\n case Silver = 1049;\n case Lead = 1134;\n case Uranium = 1905;\n case Copper = 894;\n}\n</code></pre>\n<ul>\n<li>If one case has a backed value, all cases need to have a backed value, there are no auto-generated values.</li>\n<li>Notice the type of the backed value is declared right after the enumeration name</li>\n<li>Backed values are <strong>read only</strong></li>\n<li>Scalar values need to be <strong>unique</strong></li>\n<li>Values need to be literals or literal expressions</li>\n<li>To read the backed value you access the <code>value</code> property: <code>Metal::Gold-&gt;value</code>.</li>\n</ul>\n<p>Finally, backed enumerations implement a <code>BackedEnum</code> interface internally, which exposes two methods:</p>\n<ul>\n<li><code>from(int|string): self</code></li>\n<li><code>tryFrom(int|string): ?self</code></li>\n</ul>\n<p>They are almost equivalent, with the important distinction that the first one will throw an exception if the value is not found, and the second will simply return <code>null</code>.</p>\n<pre><code>// usage example:\n\n$metal_1 = Metal::tryFrom(1932); // $metal_1 === Metal::Gold;\n$metal_2 = Metal::tryFrom(1000); // $metal_2 === null;\n\n$metal_3 = Metal::from(9999); // throws Exception\n</code></pre>\n<h3>Methods</h3>\n<p>Enumerations may have methods, and thus implement interfaces.</p>\n<pre class=\"lang-php prettyprint-override\"><code>interface TravelCapable\n{\n public function travelCost(int $distance): int;\n public function requiresFuel(): bool;\n}\n\nenum TransportMode: int implements TravelCapable{\n case Bicycle = 10;\n case Car = 1000 ;\n case Ship = 800 ;\n case Plane = 2000;\n case Feet = 5;\n \n public function travelCost(int $distance): int\n {\n return $this-&gt;value * $distance;\n }\n \n public function requiresFuel(): bool {\n return match($this) {\n TransportMode::Car, TransportMode::Ship, TransportMode::Plane =&gt; true,\n TransportMode::Bicycle, TransportMode::Feet =&gt; false\n }\n }\n}\n\n$mode = TransportMode::Car;\n\n$carConsumesFuel = $mode-&gt;requiresFuel(); // true\n$carTravelCost = $mode-&gt;travelCost(800); // 800000\n</code></pre>\n<h3>Value listing</h3>\n<p>Both Pure Enums and Backed Enums internally implement the interface <code>UnitEnum</code>, which includes the (static) method <code>UnitEnum::cases()</code>, and allows to retrieve an array of the cases defined in the enumeration:</p>\n<pre><code>$modes = TransportMode::cases();\n</code></pre>\n<p>And now <code>$modes</code> is:</p>\n<pre><code>[\n TransportMode::Bicycle,\n TransportMode::Car,\n TransportMode::Ship,\n TransportMode::Plane\n TransportMode::Feet\n]\n</code></pre>\n<h3>Static methods</h3>\n<p>Enumerations can implement their own <code>static</code> methods, which would generally be used for specialized constructors.</p>\n<hr />\n<p>This covers the basics. To get the whole thing, head on to the <a href=\"https://wiki.php.net/rfc/enumerations#dokuwiki__top\" rel=\"noreferrer\">relevant RFC</a> until the feature is released and published in PHP's documentation.</p>\n" }, { "answer_id": 68683590, "author": "Alexander Behling", "author_id": 9271344, "author_profile": "https://Stackoverflow.com/users/9271344", "pm_score": -1, "selected": false, "text": "<p>Another approach would be to use the magic method __set and make the enum private.</p>\n<p>e.g.</p>\n<pre><code>class Human{\n private $gender;\n\n public function __set($key, $value){\n if($key == 'day' &amp;&amp; !in_array($value, array('Man', 'Woman')){\n new Exception('Wrong value for '.__CLASS__.'-&gt;'.$key);\n }\n else{\n $this-&gt;$key = $value;\n }\n ...\n }\n}\n</code></pre>\n<p>This magic method is called whenever code outside the class itself try to set up the class property.\nThis works from PHP5 - 8.</p>\n" }, { "answer_id": 69155570, "author": "Kwaadpepper", "author_id": 4355295, "author_profile": "https://Stackoverflow.com/users/4355295", "pm_score": 0, "selected": false, "text": "<p>I just created a <em>library</em> that I hope does the job. It can be used stand-alone on any PHP project and has some Laravel goodies to make life easier. I use them on production projects.</p>\n<p><a href=\"https://github.com/Kwaadpepper/enum\" rel=\"nofollow noreferrer\">https://github.com/Kwaadpepper/enum</a></p>\n<p>Don't hesitate to provide feedbacks if you like it or not.\nIt can be printed, and serialized to JSON. Its definition is pretty simple.</p>\n<p>Usage is pretty simple:</p>\n<pre><code>$enum = BasicEnum::someValue();\necho $enum-&gt;equals(BasicEnum::someValue()) ? 'true' : 'false'; // true\necho $enum-&gt;value; // 'someValue' or the value you have defined\necho $enum-&gt;label; // 'someValue' or the label you have defined\necho $enum; // 'someValue' or the value you have defined\necho json_encode($enum); // {&quot;label&quot;: &quot;someValue&quot;, &quot;value: &quot;someValue&quot; }\n</code></pre>\n<p>An enum definition is pretty simple (values and labels methods are optional)</p>\n<pre><code>/**\n * @method static self post()\n * @method static self about()\n * @method static self contact()\n */\nclass PostType extends BaseEnum\n{\n protected static function values(): array\n {\n return [\n 'post' =&gt; 0,\n 'about' =&gt; 1,\n 'contact' =&gt; 2\n ];\n }\n\n protected static function labels(): array\n {\n return [\n 'post' =&gt; 'Regular posts',\n 'about' =&gt; 'The about page',\n 'contact' =&gt; 'The contact page'\n ];\n }\n}\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238/" ]
I know that PHP doesn't yet have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand. Constants do the trick, but there's the namespace collision problem and (or actually *because*) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely know how to autofill their keys without additional static analysis annotations or attributes. Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enumerations?
Depending upon use case, I would normally use something *simple* like the following: ``` abstract class DaysOfWeek { const Sunday = 0; const Monday = 1; // etc. } $today = DaysOfWeek::Sunday; ``` However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and [a few other notes](https://stackoverflow.com/a/21536800/102937), here's an expanded example which may better serve a much wider range of cases: ``` abstract class BasicEnum { private static $constCacheArray = NULL; private static function getConstants() { if (self::$constCacheArray == NULL) { self::$constCacheArray = []; } $calledClass = get_called_class(); if (!array_key_exists($calledClass, self::$constCacheArray)) { $reflect = new ReflectionClass($calledClass); self::$constCacheArray[$calledClass] = $reflect->getConstants(); } return self::$constCacheArray[$calledClass]; } public static function isValidName($name, $strict = false) { $constants = self::getConstants(); if ($strict) { return array_key_exists($name, $constants); } $keys = array_map('strtolower', array_keys($constants)); return in_array(strtolower($name), $keys); } public static function isValidValue($value, $strict = true) { $values = array_values(self::getConstants()); return in_array($value, $values, $strict); } } ``` By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation: ``` abstract class DaysOfWeek extends BasicEnum { const Sunday = 0; const Monday = 1; const Tuesday = 2; const Wednesday = 3; const Thursday = 4; const Friday = 5; const Saturday = 6; } DaysOfWeek::isValidName('Humpday'); // false DaysOfWeek::isValidName('Monday'); // true DaysOfWeek::isValidName('monday'); // true DaysOfWeek::isValidName('monday', $strict = true); // false DaysOfWeek::isValidName(0); // false DaysOfWeek::isValidValue(0); // true DaysOfWeek::isValidValue(5); // true DaysOfWeek::isValidValue(7); // false DaysOfWeek::isValidValue('Friday'); // false ``` As a side note, any time I use reflection at least once **on a static/const class where the data won't change** (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums). Now that most people have **finally** upgraded to at least 5.3, and `SplEnum` is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum *instantiations* throughout your codebase. In the above example, `BasicEnum` and `DaysOfWeek` cannot be instantiated at all, nor should they be.
254,544
<p>What do I put in my order by?? I want to order by Name. I have moved the orderby after the distinct because I read that it needs to be done last.</p> <pre><code> var result = (from r in db.RecordDocs where r.RecordID == recordID select new { DocTypeID = r.Document.DocType.DocTypeID, Name = r.Document.DocType.Name, Number = r.Document.DocType.Number } ).Distinct().OrderBy( ); </code></pre>
[ { "answer_id": 254547, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 5, "selected": true, "text": "<p>Just do</p>\n\n<pre><code>.OrderBy(doc =&gt; doc.Name)\n</code></pre>\n" }, { "answer_id": 254624, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 2, "selected": false, "text": "<p>Another option, if you really prefer the query expression syntax would be to chain your query construction across multiple statements:</p>\n\n<pre><code>var query = from r in db.RecordDocs\n where r.RecordID == recordID\n select new\n {\n DocTypeID = r.Document.DocType.DocTypeID,\n Name = r.Document.DocType.Name,\n Number = r.Document.DocType.Number\n };\n\nquery = query.Disctinct();\nquery = from doc in query orderby doc.Name select doc;\n</code></pre>\n\n<p>Since all of these methods are deferred, this will result in the exact same execution performance.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
What do I put in my order by?? I want to order by Name. I have moved the orderby after the distinct because I read that it needs to be done last. ``` var result = (from r in db.RecordDocs where r.RecordID == recordID select new { DocTypeID = r.Document.DocType.DocTypeID, Name = r.Document.DocType.Name, Number = r.Document.DocType.Number } ).Distinct().OrderBy( ); ```
Just do ``` .OrderBy(doc => doc.Name) ```
254,558
<p>I'm trying to build a hoverable Jquery tooltip. This tooltip should appear when I hover over some element, and stay put if I choose to hover over the tooltip itself too. The tooltip should disappear only if I hover away from the original element or from the tooltip body.</p> <p>Based on an example I found, I managed to create this behavior, but since I'm new to Jquery, I'd be glad to hear your comments about improving the function.</p> <h2>The code:</h2> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;script src="jquery-1.2.6.min.js"&gt;&lt;/script&gt; &lt;style&gt; #tooltip{ position:absolute; border:1px solid #333; background:#f7f5d1; padding:2px 5px; color:#333; display:none; text-align: left; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; jQuery.fn.extend({ 'tooltip': function(text){ xOffset = 10; yOffset = 20; var that = this; $(this).mouseover(function(e){ this.t = text; $("body").append("&lt;div id='tooltip'&gt;"+ this.t +"&lt;/div&gt;"); $("#tooltip") .css('position', 'absolute') .css("top",(e.pageY - xOffset) + "px") .css("left",(e.pageX + yOffset) + "px") .fadeIn("fast"); }); $(this).mouseout(function(){ that.hide_ff = setTimeout('$("#tooltip").hidetooltip()', 1000); $("#tooltip").hover(function(){ clearTimeout (that.hide_ff); }, function(){ $("#tooltip").hidetooltip() }); //$("#tooltip").hidetooltip() }); $(this).mousemove(function(e){ $("#tooltip") .css("top",(e.pageY - xOffset) + "px") .css("left",(e.pageX + yOffset) + "px"); }); }, 'hidetooltip': function() { var that = this; $(this).remove(); if (that.hide_ff) { clearTimeout (that.hide_ff); } } }); &lt;/script&gt; &lt;a id="fff"&gt;ToolTip&lt;/a&gt; &lt;div id="tooltip_share_text" style="display:none"&gt; &lt;div style="width: 100px;"&gt; This is a Tooltip. &lt;br/&gt; &lt;a href="javascript:void(0)" onclick="alert('boo')"&gt; Click Me&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#fff").tooltip($('#tooltip_share_text').html()); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p>Two things bother me most:</p> <ol> <li>I needed to extend Jquery with 2 function (tooltip and hidetooltip), i would like to achieve the same behavior with only one extension but I didn't succeed in accomplishing this.</li> <li>The use I made of "that.hide_ff" just doesn't seem right. Once again, I think this variable should belong to a "tooltip" object, but if I am not mistaken it is attached to the Jquery object itself.</li> </ol> <p>In addition, I would be happy to hear any other improvements...</p> <p>Thanks in advance, Gordi</p>
[ { "answer_id": 254738, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "<p>There is a <a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/\" rel=\"nofollow noreferrer\">tooltip plugin</a> for JQuery. If you'd rather roll your own, I'm sure you can get ideas by looking at what they have done.</p>\n" }, { "answer_id": 1338545, "author": "Mottie", "author_id": 145346, "author_profile": "https://Stackoverflow.com/users/145346", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if you're still interested in this... it's been almost a year o.O</p>\n\n<p>But I modified your code a little:</p>\n\n<ul>\n<li>I got rid of the hidetooltip (the extra extension)</li>\n<li>Using the that.hide_ff is fine, so I didn't change it</li>\n<li>The tooltip pops up at the end of the link and doesn't move with the mouse - it looks cleaner I think.</li>\n<li>Switched the xOffset and yOffset</li>\n<li>Commented out the original mousemove code so you can change it back if you don't like it.</li>\n</ul>\n\n<pre>\njQuery.fn.extend({\n 'tooltip': function(text){\n xOffset = 10;\n yOffset = 20;\n\n var that = this;\n $(this).mouseover(function(e){\n this.t = text;\n $(\"body\").append(\"\"+ this.t +\"\");\n $(\"#tooltip\")\n .css('position', 'absolute')\n .css(\"top\",(this.offsetTop + yOffset) + \"px\") /* .css(\"top\",(e.pageY - xOffset) + \"px\") */\n .css(\"left\",(this.offsetLeft + this.offsetWidth) + \"px\") /* .css(\"left\",(e.pageX + yOffset) + \"px\") */\n .fadeIn(\"fast\");\n });\n $(this).mouseout(function(){\n that.hide_ff = setTimeout('$(\"#tooltip\").remove()', 500);\n $(\"#tooltip\").hover(function(){\n clearTimeout (that.hide_ff);\n },\n function(){\n $(\"#tooltip\").remove();\n }\n );\n });\n/*\n $(this).mousemove(function(e){\n $(\"#tooltip\")\n .css(\"top\",(e.pageY - xOffset) + \"px\")\n .css(\"left\",(e.pageX + yOffset) + \"px\");\n });\n*/\n }\n});\n</pre>\n" }, { "answer_id": 1338585, "author": "Alex", "author_id": 447, "author_profile": "https://Stackoverflow.com/users/447", "pm_score": 0, "selected": false, "text": "<p>I've found that <a href=\"http://craigsworks.com/projects/qtip/\" rel=\"nofollow noreferrer\">qTip</a> has met all of my tooltip needs:</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to build a hoverable Jquery tooltip. This tooltip should appear when I hover over some element, and stay put if I choose to hover over the tooltip itself too. The tooltip should disappear only if I hover away from the original element or from the tooltip body. Based on an example I found, I managed to create this behavior, but since I'm new to Jquery, I'd be glad to hear your comments about improving the function. The code: --------- ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="jquery-1.2.6.min.js"></script> <style> #tooltip{ position:absolute; border:1px solid #333; background:#f7f5d1; padding:2px 5px; color:#333; display:none; text-align: left; } </style> </head> <body> <script type="text/javascript"> jQuery.fn.extend({ 'tooltip': function(text){ xOffset = 10; yOffset = 20; var that = this; $(this).mouseover(function(e){ this.t = text; $("body").append("<div id='tooltip'>"+ this.t +"</div>"); $("#tooltip") .css('position', 'absolute') .css("top",(e.pageY - xOffset) + "px") .css("left",(e.pageX + yOffset) + "px") .fadeIn("fast"); }); $(this).mouseout(function(){ that.hide_ff = setTimeout('$("#tooltip").hidetooltip()', 1000); $("#tooltip").hover(function(){ clearTimeout (that.hide_ff); }, function(){ $("#tooltip").hidetooltip() }); //$("#tooltip").hidetooltip() }); $(this).mousemove(function(e){ $("#tooltip") .css("top",(e.pageY - xOffset) + "px") .css("left",(e.pageX + yOffset) + "px"); }); }, 'hidetooltip': function() { var that = this; $(this).remove(); if (that.hide_ff) { clearTimeout (that.hide_ff); } } }); </script> <a id="fff">ToolTip</a> <div id="tooltip_share_text" style="display:none"> <div style="width: 100px;"> This is a Tooltip. <br/> <a href="javascript:void(0)" onclick="alert('boo')"> Click Me</a> </div> </div> <script type="text/javascript"> $(document).ready(function() { $("#fff").tooltip($('#tooltip_share_text').html()); }); </script> </body> </html> ``` --- Two things bother me most: 1. I needed to extend Jquery with 2 function (tooltip and hidetooltip), i would like to achieve the same behavior with only one extension but I didn't succeed in accomplishing this. 2. The use I made of "that.hide\_ff" just doesn't seem right. Once again, I think this variable should belong to a "tooltip" object, but if I am not mistaken it is attached to the Jquery object itself. In addition, I would be happy to hear any other improvements... Thanks in advance, Gordi
There is a [tooltip plugin](http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/) for JQuery. If you'd rather roll your own, I'm sure you can get ideas by looking at what they have done.
254,573
<p>Is there a way to use a <code>foreach</code> loop to iterate through a collection backwards or in a completely random order?</p>
[ { "answer_id": 254601, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>you can do it backwards:</p>\n\n<pre><code>for (int i=col.count-1; i&gt;0; i--){ \n DoSomething ( col.item[i]) ;\n}\n</code></pre>\n\n<p>Not certain about the exact syntax, but that's the paradigm. </p>\n\n<p>As for completely random order, you can access a collection element via it's index. To ensure you hit every item, you would need to keep track of which elements you had already processed (probably by copying the collection and then removing the element after access).</p>\n\n<p>EDIT: More details for random access\nThe code for the random access could look something like this:</p>\n\n<pre><code> collection c = originalCollection;\n while (c.count &gt; 0) {\n int i = randomNumber(seed) mod c.count\n element d = c[i];\n c.remove(d);\n DoSomething(d);\n}\n</code></pre>\n" }, { "answer_id": 254604, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 1, "selected": false, "text": "<p>I don't think there is a way to do so directly, but it's pretty much <code>as good</code> to use an extension method that returns a new collection <em>via the <code>yield return</code> keyword.</em> These could come from a pre-existing library; the others have pointed out that LINQ has a <code>Reverse</code> method, and things like <code>OrderBy</code> would also work.</p>\n\n<p>Example: if you use the LINQ extension method <code>Reverse()</code> on <code>IEnumerable&lt;T&gt;</code>, which uses <code>yield return</code> to give the collection in reverse order, then doing a <code>foreach(var myThing in myCollection.Reverse())</code> will enumerate through the collection in reverse order.</p>\n\n<p><em>Important</em>: <code>yield return</code> is key. It means \"when I enumerate this collection, then go fetch things.\" As opposed to the alternative of just constructing a <em>new</em>, reversed collection, which is highly inefficient and possibly has side effects.</p>\n" }, { "answer_id": 254605, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 4, "selected": false, "text": "<p>Using <code>System.Linq</code> you could do...</p>\n\n<pre><code>// List&lt;...&gt; list;\nforeach (var i in list.Reverse())\n{\n}\n</code></pre>\n\n<p>For a random order you'd have to sort it randomly using <code>list.OrderBy</code> (another Linq extension) and then iterate that ordered list.</p>\n\n<pre><code>var rnd = new Random();\nvar randomlyOrdered = list.OrderBy(i =&gt; rnd.Next());\nforeach (var i in randomlyOrdered)\n{\n}\n</code></pre>\n" }, { "answer_id": 254612, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 0, "selected": false, "text": "<p>You could sort the List by supplying your own Comparator and iterate over that one.</p>\n" }, { "answer_id": 254664, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 5, "selected": true, "text": "<p>As other answers mention, the <a href=\"http://msdn.microsoft.com/en-us/library/bb358497.aspx\" rel=\"noreferrer\"><code>Reverse()</code> extension method</a> will let you enumerate a sequence in reverse order.</p>\n\n<p>Here's a random enumeration extension method:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; OrderRandomly&lt;T&gt;(this IEnumerable&lt;T&gt; sequence)\n{\n Random random = new Random();\n List&lt;T&gt; copy = sequence.ToList();\n\n while (copy.Count &gt; 0)\n {\n int index = random.Next(copy.Count);\n yield return copy[index];\n copy.RemoveAt(index);\n }\n}\n</code></pre>\n\n<p>Your usage would be:</p>\n\n<pre><code>foreach (int n in Enumerable.Range(1, 10).OrderRandomly())\n Console.WriteLine(n);\n</code></pre>\n" }, { "answer_id": 254698, "author": "Zote", "author_id": 20683, "author_profile": "https://Stackoverflow.com/users/20683", "pm_score": 0, "selected": false, "text": "<p>Do you want to rand a collection and interect with it?</p>\n\n<p>If yes, try this:</p>\n\n<pre><code>Random rand = new Random(Environment.TickCount);\n\ntest.Sort((string v1, string v2) =&gt; {\n if (v1.Equals(v2))\n {\n return 0;\n }\n\n int x = rand.Next();\n int y = rand.Next();\n\n if (x == y)\n {\n return 0;\n }\n else if (x &gt; y)\n {\n return 1;\n }\n\n return -1; \n });\n\nfor (string item in test)\n{\n Console.WriteLn(item);\n}\n// Note that test is List&lt;string&gt;;\n</code></pre>\n" }, { "answer_id": 254748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>From my reading of the C# Language Specification, the foreach iteration statement depends on the struct/class/interface which is being iterated having the GetEnumerator() function defined upon it. The object returned by GetEnumerator() must have MoveNext() defined as a member function. MoveNext() is defined as accessing the \"first\" object in the list on its first call, then the \"next\" on subsequent calls, returning true until no further elements exist in the list, upon which it returns false.</p>\n\n<p>The feature Domenic refers to, yield return, first appears in the 2.0 version of the specification, and does appear to be useful for this purpose. For version 1.1, your only option would be to derive a new struct/class/interface from your base and override GetEnumerator() to return a new IEnumerator, where the MoveNext() function would follow different rules in select the first collection element and any subsequent collection element.</p>\n\n<p>My own recommendation would be to use an indexed collection, then use a for loop with an appropriate index calculation (here one could use a random number generator if necessary, with an integer array or some other technique for verifying that the same index value is not used twice) if you have to do this in actual practice.</p>\n" }, { "answer_id": 254783, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 1, "selected": false, "text": "<p>As of C# 2.0 you have the ability to use the yield keyword to implement custom iterators really easy. You can read more about the yield keyword over at MSDN <a href=\"http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx</a></p>\n\n<p>You can think of a yield as the ability to return a value from inside a loop, but you should refer to the link above for a full explanation of what they are and what they can do.</p>\n\n<p>I wrote a short example on how to implement a couple of custom iterators. I've implemented them as extension methods (<a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb383977.aspx</a>) to make the code a bit more stream lined and I also use array initializers (<a href=\"http://msdn.microsoft.com/en-us/library/aa664573.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa664573.aspx</a>) to set the initial values for the list of integers.</p>\n\n<p>Neither extension methods nor array initializers are necessary for implementing custom iterators but they are nice features of c# 3.0 which helps write cleaner code</p>\n\n<p>Here are my examples. It shows how to iterate over a list of integers by only returning Odd numbers, Even numbers, the numbers in reversed or in a completly random fashion.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n List&lt;int&gt; ints = \n new List&lt;int&gt; { 1,2,3,4,5,6,7,8,9,10};\n\n Console.WriteLine(\"Iterating over Odd numbers only.\");\n foreach (int i in ints.Odd())\n {\n Console.WriteLine(i);\n }\n\n Console.WriteLine(\"Iterating over Even numbers only.\");\n foreach (int i in ints.Even())\n {\n Console.WriteLine(i);\n }\n\n Console.WriteLine(\"Iterating over the list in reversed order.\");\n foreach (int i in ints.Reversed())\n {\n Console.WriteLine(i);\n }\n\n Console.WriteLine(\"Iterating over the list in random order.\");\n foreach (int i in ints.Random())\n {\n Console.WriteLine(i);\n }\n\n Console.ReadLine();\n }\n }\n\n public static class ListExtensions\n {\n /// &lt;summary&gt;\n /// Iterates over the list only returns even numbers\n /// &lt;/summary&gt;\n /// &lt;param name=\"list\"&gt;&lt;/param&gt;\n public static IEnumerable&lt;int&gt; Even(this List&lt;int&gt; list)\n {\n foreach (var i in list)\n {\n if (i % 2 == 0)\n {\n yield return i;\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Iterates over the list only returns odd numbers\n /// &lt;/summary&gt;\n public static IEnumerable&lt;int&gt; Odd(this List&lt;int&gt; list)\n {\n foreach (var i in list)\n {\n if (i % 2 != 0)\n {\n yield return i;\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Iterates over the list in reversed order\n /// &lt;/summary&gt;\n public static IEnumerable&lt;int&gt; Reversed(this List&lt;int&gt; list)\n {\n for (int i = list.Count; i &gt;= 0; i--)\n {\n yield return i;\n }\n }\n\n /// &lt;summary&gt;\n /// Iterates over the list in random order\n /// &lt;/summary&gt;\n public static IEnumerable&lt;int&gt; Random(this List&lt;int&gt; list)\n {\n // Initialize a random number generator with a seed.\n System.Random rnd =\n new Random((int)DateTime.Now.Ticks);\n\n // Create a list to keep track of which indexes we've\n // already returned\n List&lt;int&gt; visited =\n new List&lt;int&gt;();\n\n // loop until we've returned the value of all indexes\n // in the list\n while (visited.Count &lt; list.Count)\n {\n int index =\n rnd.Next(0, list.Count);\n\n // Make sure we've not returned it already\n if (!visited.Contains(index))\n {\n visited.Add(index);\n yield return list[index];\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 254917, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 1, "selected": false, "text": "<p>I actually liked cfeduke approach with LINQ and it bugs me that it slipped my mind. To add to my previous example. If you want to do the Odd and Even iterations with the help of LINQ you can use</p>\n\n<pre><code>// Even\nforeach (var i in ints.FindAll(number =&gt; number % 2 == 0))\n{\n Console.WriteLine(i);\n}\n\n// Odd\nforeach (var i in ints.FindAll(number =&gt; number % 2 != 0))\n{\n Console.WriteLine(i);\n}\n</code></pre>\n" }, { "answer_id": 254947, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 1, "selected": false, "text": "<p>Using an <code>IList&lt;T&gt;</code> from the <a href=\"http://www.itu.dk/research/c5\" rel=\"nofollow noreferrer\">C5 Generic Collection Library</a>, Reverse iteration is a feature, rather than extension:</p>\n\n<pre><code>foreach (var i in list.Reverse())\n{\n}\n</code></pre>\n\n<p>As well, you can use the <code>Shuffle()</code> method to get a random ordering:</p>\n\n<pre><code>var listClone = (IList&lt;T&gt;) list.Clone();\nlistClone.Shuffle();\nforeach (var i in listClone)\n{\n}\n</code></pre>\n" }, { "answer_id": 308742, "author": "Ramesh Soni", "author_id": 191, "author_profile": "https://Stackoverflow.com/users/191", "pm_score": 0, "selected": false, "text": "<p>Use random ordering<br>\n<a href=\"http://www.dailycoding.com/Posts/random_sort_a_list_using_linq.aspx\" rel=\"nofollow noreferrer\">http://www.dailycoding.com/..using_linq.aspx</a></p>\n\n<pre><code>List&lt;Employee&gt; list = new List&lt;Employee&gt;();\n\nlist.Add(new Employee { Id = 1, Name = \"Davolio Nancy\" });\nlist.Add(new Employee { Id = 2, Name = \"Fuller Andrew\" });\nlist.Add(new Employee { Id = 3, Name = \"Leverling Janet\" });\nlist.Add(new Employee { Id = 4, Name = \"Peacock Margaret\" });\nlist.Add(new Employee { Id = 5, Name = \"Buchanan Steven\" });\nlist.Add(new Employee { Id = 6, Name = \"Suyama Michael\" });\nlist.Add(new Employee { Id = 7, Name = \"King Robert\" });\nlist.Add(new Employee { Id = 8, Name = \"Callahan Laura\" });\nlist.Add(new Employee { Id = 9, Name = \"Dodsworth Anne\" });\n\nlist = list.OrderBy(emp =&gt; Guid.NewGuid()).ToList();\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
Is there a way to use a `foreach` loop to iterate through a collection backwards or in a completely random order?
As other answers mention, the [`Reverse()` extension method](http://msdn.microsoft.com/en-us/library/bb358497.aspx) will let you enumerate a sequence in reverse order. Here's a random enumeration extension method: ``` public static IEnumerable<T> OrderRandomly<T>(this IEnumerable<T> sequence) { Random random = new Random(); List<T> copy = sequence.ToList(); while (copy.Count > 0) { int index = random.Next(copy.Count); yield return copy[index]; copy.RemoveAt(index); } } ``` Your usage would be: ``` foreach (int n in Enumerable.Range(1, 10).OrderRandomly()) Console.WriteLine(n); ```
254,613
<p>When a web site is licensed under Creative Commons, I use the <a href="http://microformats.org/wiki/rel-license" rel="noreferrer">rel-license microformat</a>. When a web site is licensed under regular copyright, I have a boring paragraph element.</p> <pre><code>&lt;p id="copyright"&gt;&amp;copy; 2008 Example Corporation&lt;/p&gt; </code></pre> <p>That id attribute on there is just for CSS styling purposes. I'm wondering if there's some better way to markup a copyright notice that is more semantic. Is this a job for Dublin Core metadata? If so, how do I go about it? (I've never used Dublin Core before.)</p> <p>Some web sites advocate using a meta tag in the head element:</p> <pre><code>&lt;meta name="copyright" content="name of owner"&gt; </code></pre> <p>Which might be seen by search engines, but doesn't replace the user-visible notice on the page itself.</p>
[ { "answer_id": 254642, "author": "Marcin", "author_id": 21640, "author_profile": "https://Stackoverflow.com/users/21640", "pm_score": 1, "selected": false, "text": "<p>Why not use the CC format, but indicate that no rights are granted?</p>\n\n<p>In any case, the main problem with the use of the CC formats is that people do not clearly identify which elements of the webpage that they appear on they apply to.</p>\n" }, { "answer_id": 254666, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "<p>Probably the most semantically correct way to mark it up is with a definition list.</p>\n\n<pre><code>&lt;dl id=\"copyright\"&gt;\n &lt;dt title=\"Copyright\"&gt;&amp;copy;&lt;/dt&gt;\n &lt;dd&gt;2008 Example Corporation&lt;/dd&gt;\n&lt;/dl&gt;\n</code></pre>\n" }, { "answer_id": 254710, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "<p>Have you taken a look at <a href=\"http://www.w3.org/TR/2008/NOTE-xhtml-rdfa-primer-20081014/\" rel=\"noreferrer\">RDFa</a>? It was <a href=\"http://www.w3.org/News/2008#item174\" rel=\"noreferrer\">recently accepted</a> as a W3C recommendation. I mention that just in case you want to take a look at other aspects of semantic structure it recommends. The licensing part is the same as the format you currently use. (So in that sense to answer your question, I think you're handling it correctly, assuming people adopt RDFa)</p>\n\n<p>For lazy people who don't want to click links:</p>\n\n<pre><code>// RDFa recomendation and rel=license microformat\n&lt;a rel=\"license\" href=\"http://creativecommons.org/licenses/by/3.0/\"&gt;\n a Creative Commons License\n&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 254836, "author": "Scott", "author_id": 6126, "author_profile": "https://Stackoverflow.com/users/6126", "pm_score": 5, "selected": true, "text": "<p>Thanks to Owen for pointing me in the direction of RDFa, I think I've got the solution now:</p>\n\n<pre><code>&lt;div id=\"footer\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"&gt;\n&lt;p id=\"copyright\" property=\"dc:rights\"&gt;&amp;copy;\n &lt;span property=\"dc:dateCopyrighted\"&gt;2008&lt;/span&gt;\n &lt;span property=\"dc:publisher\"&gt;Example Corporation&lt;/span&gt;\n&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Depending on the situation, it might be better to use dc:creator instead of dc:publisher. From the Dublin Core web site:</p>\n\n<blockquote>If the Creator and Publisher are the same, do not repeat the name in the Publisher area. If the nature of the responsibility is ambiguous, the recommended practice is to use Publisher for organizations, and Creator for individuals. In cases of lesser or ambiguous responsibility, other than creation, use Contributor.</blockquote>\n\n<p>I will also be adding a meta tag to my head element for search engines that don't support RDFa yet.</p>\n\n<pre><code>&lt;meta name=\"copyright\" content=\"&amp;copy; 2008 Example Corporation\" /&gt;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6126/" ]
When a web site is licensed under Creative Commons, I use the [rel-license microformat](http://microformats.org/wiki/rel-license). When a web site is licensed under regular copyright, I have a boring paragraph element. ``` <p id="copyright">&copy; 2008 Example Corporation</p> ``` That id attribute on there is just for CSS styling purposes. I'm wondering if there's some better way to markup a copyright notice that is more semantic. Is this a job for Dublin Core metadata? If so, how do I go about it? (I've never used Dublin Core before.) Some web sites advocate using a meta tag in the head element: ``` <meta name="copyright" content="name of owner"> ``` Which might be seen by search engines, but doesn't replace the user-visible notice on the page itself.
Thanks to Owen for pointing me in the direction of RDFa, I think I've got the solution now: ``` <div id="footer" xmlns:dc="http://purl.org/dc/elements/1.1/"> <p id="copyright" property="dc:rights">&copy; <span property="dc:dateCopyrighted">2008</span> <span property="dc:publisher">Example Corporation</span> </p> </div> ``` Depending on the situation, it might be better to use dc:creator instead of dc:publisher. From the Dublin Core web site: > If the Creator and Publisher are the same, do not repeat the name in the Publisher area. If the nature of the responsibility is ambiguous, the recommended practice is to use Publisher for organizations, and Creator for individuals. In cases of lesser or ambiguous responsibility, other than creation, use Contributor. I will also be adding a meta tag to my head element for search engines that don't support RDFa yet. ``` <meta name="copyright" content="&copy; 2008 Example Corporation" /> ```
254,616
<p>I am wondering how I can break up my index.php homepage to multiple php pages (i.e. header.php, footer.php) and build a working index.php page using those separate php pages. I know WordPress uses this with different functions like:</p> <pre><code>GetHeader(); GetFoodter(); </code></pre> <p>But when I tried to use those functions, it errors. I am guessing they are not native functions to PHP.</p> <p>What would I need to do to get this functionality?</p>
[ { "answer_id": 254622, "author": "Scott", "author_id": 6126, "author_profile": "https://Stackoverflow.com/users/6126", "pm_score": 4, "selected": true, "text": "<pre><code>include 'header.php';\n\ninclude 'footer.php';\n</code></pre>\n" }, { "answer_id": 254626, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": -1, "selected": false, "text": "<p>Use include statements to just include those files to your Page</p>\n\n<p>I think it's </p>\n\n<pre><code>include '[filename]'\n</code></pre>\n" }, { "answer_id": 254629, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 1, "selected": false, "text": "<p>You could do the following:</p>\n\n<pre><code>&lt;?php\n include('header.php');\n // Template Processing Code\n include('footer.php');\n?&gt;\n</code></pre>\n" }, { "answer_id": 254648, "author": "Jilles", "author_id": 13864, "author_profile": "https://Stackoverflow.com/users/13864", "pm_score": 2, "selected": false, "text": "<p>Go with an MVC framework like Zend's. That way you'll keep more maintainable code.</p>\n" }, { "answer_id": 254659, "author": "belunch", "author_id": 32867, "author_profile": "https://Stackoverflow.com/users/32867", "pm_score": 1, "selected": false, "text": "<p>The include() statement includes and evaluates the specified file. </p>\n\n<p>so if you create index.php as:</p>\n\n<pre><code>&lt;?php\ninclude(\"1.php\"); include(\"2.php\"); include(\"3.php\");\n?&gt;\n</code></pre>\n\n<p>processing it will combine three php files (result of parsing them by php) into output of your index.php ... check more at <a href=\"http://pl.php.net/manual/pl/function.include.php\" rel=\"nofollow noreferrer\">http://pl.php.net/manual/pl/function.include.php</a></p>\n" }, { "answer_id": 395730, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If your server is configured accordingly, you can use PHP's built in auto append/prepend settings and set it in a .htaccess file:<br><br></p>\n\n<p>php_value auto_prepend_file \"header.php\"<br>\nphp_value auto_append_file \"footer.php\"<br><br></p>\n\n<p>Info:<br>\nwww.php.net/manual/en/configuration.changes.php#configuration.changes.apache<br>\nwww.php.net/ini.core#ini.auto-prepend-file<br>\nwww.php.net/ini.core#ini.auto-append-file</p>\n" }, { "answer_id": 395736, "author": "EroSan", "author_id": 48540, "author_profile": "https://Stackoverflow.com/users/48540", "pm_score": 1, "selected": false, "text": "<p>Also, if i recall correctly, you can also use </p>\n\n<pre><code>&lt;?php\nrequire('filename');\n?&gt;\n</code></pre>\n\n<p>the difference being, if php can't find the file you want to include, it will stop right there instead of keep excecuting the script...</p>\n" }, { "answer_id": 1982094, "author": "AgentConundrum", "author_id": 1588, "author_profile": "https://Stackoverflow.com/users/1588", "pm_score": 0, "selected": false, "text": "<p>I realize this is an old question, which already has a perfectly valid accepted answer, but I wanted to add a little more information. </p>\n\n<p>While <code>include 'file.php';</code> is fine on it's own, there are benefits to wrapping these sorts of things up in functions, such as providing scope.</p>\n\n<p>I'm somewhat new to PHP, so last night I was playing with breaking things into files such as <code>'header.php'</code>, <code>'footer.php'</code>, <code>'menu.php'</code> for the first time.</p>\n\n<p>One issue I had was that I wanted to have the menu item for a page/section highlighted differently when you were on that page or in that section. I.e. the same way 'Questions' is highlighted in orange on this page on StackOverflow. I could define a variable on each page which would be used in the include, but this made the variable sort of global. If you wrap the include in a function, you can define variables with local scope to handle it.</p>\n" }, { "answer_id": 3556944, "author": "Chris Bloom", "author_id": 83743, "author_profile": "https://Stackoverflow.com/users/83743", "pm_score": 0, "selected": false, "text": "<p>You could also look into a template engine like <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a>. That way you define the the header and footer and all other common elements in a single file, then fill in the rest through smaller templates or direct output.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33194/" ]
I am wondering how I can break up my index.php homepage to multiple php pages (i.e. header.php, footer.php) and build a working index.php page using those separate php pages. I know WordPress uses this with different functions like: ``` GetHeader(); GetFoodter(); ``` But when I tried to use those functions, it errors. I am guessing they are not native functions to PHP. What would I need to do to get this functionality?
``` include 'header.php'; include 'footer.php'; ```
254,661
<p>When I try to allocate a Texture2D the app just crashes. I've stepped through the code where the crash occurs... all I can tell is "EXC BAD ACCESS". Here is the line in the app delegate that makes it crash:</p> <pre><code>_textures[myTex] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"sometex.png"]]; </code></pre> <p>sometex.png has been added to the resources folder via "add existing files". I've was able to load this png just fine in some sample code... but now when I try to duplicate the functionality of the sample code it just crashes. Any ideas?</p> <p>Also I can do the following just fine:</p> <pre><code>_textField = [[UITextField alloc] initWithFrame:CGRectMake(60, 214, 200, 30)]; </code></pre>
[ { "answer_id": 254720, "author": "MrDatabase", "author_id": 22471, "author_profile": "https://Stackoverflow.com/users/22471", "pm_score": 0, "selected": false, "text": "<p>Looks like the program can't find \"sometex.png\". When I replace \"sometex.png\" with the entire path\"users/ blah blah /sometex.png\" the crash doesn't happen.</p>\n" }, { "answer_id": 254759, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": true, "text": "<p>Is \"sometex.png\" in your resources? If you right-click on the .app that Xcode creates and select \"Show Package Contents\", do you see it there? It sounds like it's not being bundled with your app at build time.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/254661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
When I try to allocate a Texture2D the app just crashes. I've stepped through the code where the crash occurs... all I can tell is "EXC BAD ACCESS". Here is the line in the app delegate that makes it crash: ``` _textures[myTex] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"sometex.png"]]; ``` sometex.png has been added to the resources folder via "add existing files". I've was able to load this png just fine in some sample code... but now when I try to duplicate the functionality of the sample code it just crashes. Any ideas? Also I can do the following just fine: ``` _textField = [[UITextField alloc] initWithFrame:CGRectMake(60, 214, 200, 30)]; ```
Is "sometex.png" in your resources? If you right-click on the .app that Xcode creates and select "Show Package Contents", do you see it there? It sounds like it's not being bundled with your app at build time.