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
234,515
<p>I reloaded an old project, and tried to run it only to run into the Binding Failure MDA Assistant:</p> <pre> BindingFailure was detected Message: The assembly with display name 'SoapTest.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'SoapTest.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. </pre> <p>After googling this, the only solution I could find was to turn off the MDA. This works, but I would prefer to solve the underlying problem (SoapTest.XmlSerializers.dll not being in the bin\Debug directory). How can I fix this? What creates the SoapTest.XmlSerializers.dll, and why is it not being created on a Rebuild? Yes, I have tried updating the Web Reference (this doesn't help). No I don't want to upgrade to WCF Soap Services.</p>
[ { "answer_id": 236732, "author": "Geoff Cox", "author_id": 30505, "author_profile": "https://Stackoverflow.com/users/30505", "pm_score": 1, "selected": false, "text": "<p>In VS.NET you can go to the project settings and try different settings for XmlSerialization - I believe there is a setting for auto that you may want to disable.</p>\n" }, { "answer_id": 394933, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>actually yes , i went to the propensities window and set the option of \"Generate serialization assembly\" to \"on\" , by this you insure every time you build the project ,\ni guess that error happens when you edit the assmbly info of the class library you are referencing without re building it </p>\n" }, { "answer_id": 9011650, "author": "Claudiu Constantin", "author_id": 805353, "author_profile": "https://Stackoverflow.com/users/805353", "pm_score": 0, "selected": false, "text": "<p>I also encountered this issue. The problem was that the project causing the Exception was created in another folder than the .exe file. I easily resolved it by changing the Deployment Path from Properties/Build settings page. No other change on \"Generate serialization assembly\" was necessary.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
I reloaded an old project, and tried to run it only to run into the Binding Failure MDA Assistant: ``` BindingFailure was detected Message: The assembly with display name 'SoapTest.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'SoapTest.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. ``` After googling this, the only solution I could find was to turn off the MDA. This works, but I would prefer to solve the underlying problem (SoapTest.XmlSerializers.dll not being in the bin\Debug directory). How can I fix this? What creates the SoapTest.XmlSerializers.dll, and why is it not being created on a Rebuild? Yes, I have tried updating the Web Reference (this doesn't help). No I don't want to upgrade to WCF Soap Services.
actually yes , i went to the propensities window and set the option of "Generate serialization assembly" to "on" , by this you insure every time you build the project , i guess that error happens when you edit the assmbly info of the class library you are referencing without re building it
234,526
<p>Can I setup a custom MIME type through ASP.NET or some .NET code? I need to register the Silverlight XAML and XAP MIME types in IIS 6.</p>
[ { "answer_id": 234613, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "<p>To add to the master mime type list:</p>\n\n<pre><code>using (DirectoryEntry mimeMap = new DirectoryEntry(\"IIS://Localhost/MimeMap\"))\n{\n PropertyValueCollection propValues = mimeMap.Properties[\"MimeMap\"];\n\n IISOle.MimeMapClass newMimeType = new IISOle.MimeMapClass();\n newMimeType.Extension = extension; // string - .xap\n newMimeType.MimeType = mimeType; // string - application/x-silverlight-app\n\n propValues.Add(newMimeType);\n mimeMap.CommitChanges();\n}\n</code></pre>\n\n<p>Add a reference to :</p>\n\n<p>'System.DirectoryServices' on the .NET add references tab<br>\n'Active DS IIS Namespace Provider' on the COM add references tab.</p>\n\n<p>To configure a mime type for a specific site, change ..</p>\n\n<p><code>'IIS://Localhost/MimeMap'</code> </p>\n\n<p>to </p>\n\n<p><code>'IIS://Localhost/W3SVC/[iisnumber]/root'</code> </p>\n\n<p>...replacing <code>'[iisnumber]'</code> with the IISNumber of the website.</p>\n" }, { "answer_id": 1767260, "author": "TomEberhard", "author_id": 215067, "author_profile": "https://Stackoverflow.com/users/215067", "pm_score": 1, "selected": false, "text": "<p>'Active DS IIS Namespace Provider' on the COM add references tab.</p>\n\n<p>If it's not there, you have to install IIS on your machine.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1191811/is-there-a-way-to-get-all-the-mime-types-instead-of-wrinting-a-huge-case-statemen/1767242#1767242\">Is there a way to get ALL the MIME types instead of wrinting a huge case statement?</a></p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
Can I setup a custom MIME type through ASP.NET or some .NET code? I need to register the Silverlight XAML and XAP MIME types in IIS 6.
To add to the master mime type list: ``` using (DirectoryEntry mimeMap = new DirectoryEntry("IIS://Localhost/MimeMap")) { PropertyValueCollection propValues = mimeMap.Properties["MimeMap"]; IISOle.MimeMapClass newMimeType = new IISOle.MimeMapClass(); newMimeType.Extension = extension; // string - .xap newMimeType.MimeType = mimeType; // string - application/x-silverlight-app propValues.Add(newMimeType); mimeMap.CommitChanges(); } ``` Add a reference to : 'System.DirectoryServices' on the .NET add references tab 'Active DS IIS Namespace Provider' on the COM add references tab. To configure a mime type for a specific site, change .. `'IIS://Localhost/MimeMap'` to `'IIS://Localhost/W3SVC/[iisnumber]/root'` ...replacing `'[iisnumber]'` with the IISNumber of the website.
234,532
<p>I have data that looks like</p> <blockquote> <pre><code>CUSTOMER, CUSTOMER_ID, PRODUCT ABC INC 1 XYX ABC INC 1 ZZZ DEF CO 2 XYX DEF CO 2 ZZZ DEF CO 2 WWW GHI LLC 3 ZYX </code></pre> </blockquote> <p>I'd like to write a query that'd make the data look like this:</p> <blockquote> <pre><code>CUSTOMER, CUSTOMER_ID, PRODUCTS ABC INC 1 XYX, ZZZ DEF CO 2 XYX, ZZZ, WWW GHI LLC 3 ZYX </code></pre> </blockquote> <p>Using Oracle 10g if helps. I saw something that would work using MYSQL, but I need a plain SQL or ORACLE equivalent. I've also seen examples of stored procs that could be made, however, I cannot use a stored proc with the product i'm using.</p> <p>Here's how'd it work in MySQL if I were using it</p> <pre><code>SELECT CUSTOMER, CUSTOMER_ID, GROUP_CONCAT( PRODUCT ) FROM MAGIC_TABLE GROUP BY CUSTOMER, CUSTOMER_ID </code></pre> <p>Thank you.</p>
[ { "answer_id": 234573, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php\" rel=\"nofollow noreferrer\">This link</a> refers to a number of examples of different ways to do this on Oracle. See if there's something there that you have permissions on your database to do.</p>\n" }, { "answer_id": 234843, "author": "Roy Rico", "author_id": 1580, "author_profile": "https://Stackoverflow.com/users/1580", "pm_score": 0, "selected": false, "text": "<p>Thanks Nigel,</p>\n\n<p>My SQL is not as elegant as could be, but I needed a solution that required SQL only, not PLSQL or TSQL, so it ended up looking like this:</p>\n\n<pre><code>SELECT CUSTOMER, CUSTOMER_ID, COUNT(PRODUCT) PROD_COUNT, \n RTRIM( \n XMLAGG( XMLELEMENT (C, PRODUCT || ',') ORDER BY PRODUCT\n).EXTRACT ('//text()'), ',' \n ) AS PRODUCTS FROM (\n SELECT DISTINCT CUSTOMER, CUSTOMER_ID, PRODUCT\n FROM MAGIC_TABLE\n ) GROUP BY CUSTOMER, CUSTOMER_ID ORDER BY 1 , 2\n</code></pre>\n\n<p>Still not exactly sure what the XML functions do exactly, but I'll dig in when the need arrises.</p>\n" }, { "answer_id": 10252843, "author": "ScrappyDev", "author_id": 620192, "author_profile": "https://Stackoverflow.com/users/620192", "pm_score": 4, "selected": false, "text": "<p>I think LISTAGG is the best aggregate group by function to use in this situation:</p>\n\n<pre><code> SELECT CUSTOMER, CUSTOMER_ID,\n LISTAGG(PRODUCT, ', ') WITHIN GROUP (ORDER BY PRODUCT)\n FROM SOME_TABLE\nGROUP BY CUSTOMER, CUSTOMER_ID\nORDER BY 1, 2\n</code></pre>\n" }, { "answer_id": 13346212, "author": "Chris Gurley", "author_id": 1551847, "author_profile": "https://Stackoverflow.com/users/1551847", "pm_score": 2, "selected": false, "text": "<p>The oracle user function 'wm_concat' works the same way as LISTAGG except you cannot specify a delimiter ',' by default or a sort order. It is however compatible with 10g.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1580/" ]
I have data that looks like > > > ``` > CUSTOMER, CUSTOMER_ID, PRODUCT > ABC INC 1 XYX > ABC INC 1 ZZZ > DEF CO 2 XYX > DEF CO 2 ZZZ > DEF CO 2 WWW > GHI LLC 3 ZYX > > ``` > > I'd like to write a query that'd make the data look like this: > > > ``` > CUSTOMER, CUSTOMER_ID, PRODUCTS > ABC INC 1 XYX, ZZZ > DEF CO 2 XYX, ZZZ, WWW > GHI LLC 3 ZYX > > ``` > > Using Oracle 10g if helps. I saw something that would work using MYSQL, but I need a plain SQL or ORACLE equivalent. I've also seen examples of stored procs that could be made, however, I cannot use a stored proc with the product i'm using. Here's how'd it work in MySQL if I were using it ``` SELECT CUSTOMER, CUSTOMER_ID, GROUP_CONCAT( PRODUCT ) FROM MAGIC_TABLE GROUP BY CUSTOMER, CUSTOMER_ID ``` Thank you.
[This link](http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php) refers to a number of examples of different ways to do this on Oracle. See if there's something there that you have permissions on your database to do.
234,558
<p>I can't seem to be able to disable ViewState for controls that I add to a page dynamically.</p> <p><strong>ASPX</strong></p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Page1.aspx.cs" Inherits="Page1" EnableViewState="false" %&gt; ... &lt;asp:PlaceHolder ID="DropDownPlaceHolder" runat="server" EnableViewState="false" /&gt; &lt;asp:Button ID="Submit" runat="server" OnClick="Submit_OnClick" Text="Click Me!" EnableViewState="false"/&gt; ... </code></pre> <p><strong>ASPX.CS</strong></p> <pre><code>protected override void OnInit(EventArgs e) { DropDownList dropDown = new DropDownList(); TextBox textBox = new TextBox(); textBox.EnableViewState = false; dropDown.Items.Add("Apple"); dropDown.Items.Add("Dell"); dropDown.Items.Add("HP"); dropDown.AutoPostBack = true; dropDown.EnableViewState = false; DropDownPlaceHolder.Controls.Add(dropDown); DropDownPlaceHolder.Controls.Add(textBox); base.OnInit(e); } </code></pre> <p>If I can't disable ViewState on these controls, then I can never programmatically override what a user has entered/selected.</p> <p>I've tried placing this code in OnInit and Page_Load, but the effect is the same in either location -- ViewState is enabled (the DropDownList maintains selected value and TextBox retains text that was entered).</p> <p>So, how can I disable ViewState and keep it from populating these controls?</p> <p>Thanks!</p> <hr> <p>Thanks for your response. Unfortunately, this isn't a workable solution in my situation.</p> <p>I will be dynamically loading controls based upon a configuration file, and some of those controls will load child controls.</p> <p>I need to be able to turn the ViewState of controls off individually, without the need to code logic for loading controls in different places (in OnInit vs. LoadComplete method).</p>
[ { "answer_id": 234763, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 0, "selected": false, "text": "<p>I tested this a bit and found it a little odd. It seems the post(back) will send the selected value, even if a control has it's viewstate turned off.</p>\n\n<p>I did find a good solution around it though, is that if you handle everything after the init and load, you will reload your control after the viewstate has been processed and it will thus, reset the values.</p>\n\n<p>I used the LoadComplete event, example below:</p>\n\n<blockquote>\n<pre><code> Public Sub Page_In(ByVal sender As Object, ByVal e As EventArgs) _ \n Handles Me.LoadComplete\n\n Dim ddl As New DropDownList()\n ddl.EnableViewState = False\n ddl.Items.Add(\"Hello\")\n ddl.Items.Add(\"Stackoverflow\")\n\n phTest.Controls.Add(ddl)\n\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 234951, "author": "Bret Walker", "author_id": 8797, "author_profile": "https://Stackoverflow.com/users/8797", "pm_score": 2, "selected": true, "text": "<p>It's a \"feature\" -- <a href=\"http://support.microsoft.com/?id=316813\" rel=\"nofollow noreferrer\">http://support.microsoft.com/?id=316813</a></p>\n\n<p>Thanks, Microsoft!!</p>\n" }, { "answer_id": 243052, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 2, "selected": false, "text": "<p>What you are seeing there is the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.pagestatepersister.controlstate.aspx\" rel=\"nofollow noreferrer\" title=\".NET Framework Class Library - PageStatePersister.ControlState Property \"><code>ControlState</code></a> which was introduced with .Net Framework 2.0. It is designed to store the absolute minimum information for a control to work, such as the selection in your <code>DropDownList</code> and the text in your <code>TextBox</code>. Properties which are only related to appearance, such as <code>BackColor</code>, are still persisted within the <code>ViewState</code>.</p>\n\n<p>Unlike <code>ViewState</code> <a href=\"http://msdn.microsoft.com/en-us/library/ms178577.aspx\" rel=\"nofollow noreferrer\" title=\"What's New in ASP.NET State Management\">you can't turn ControlState off</a>.</p>\n\n<p>I can only assume this is to avoid confusion from end-users when controls do not do what they are supposed to if they disable <code>ViewState</code> without understanding the consequences.</p>\n" }, { "answer_id": 243602, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>@This Mat</p>\n \n <p>It seems the post(back) will send the selected value, even if a control has it's viewstate turned off.</p>\n</blockquote>\n\n<p>Yes. The post will always send a controls selected/current value. That's a behavior of HTTP form posting and nothing to do with ASP.NET control/view state.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8797/" ]
I can't seem to be able to disable ViewState for controls that I add to a page dynamically. **ASPX** ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Page1.aspx.cs" Inherits="Page1" EnableViewState="false" %> ... <asp:PlaceHolder ID="DropDownPlaceHolder" runat="server" EnableViewState="false" /> <asp:Button ID="Submit" runat="server" OnClick="Submit_OnClick" Text="Click Me!" EnableViewState="false"/> ... ``` **ASPX.CS** ``` protected override void OnInit(EventArgs e) { DropDownList dropDown = new DropDownList(); TextBox textBox = new TextBox(); textBox.EnableViewState = false; dropDown.Items.Add("Apple"); dropDown.Items.Add("Dell"); dropDown.Items.Add("HP"); dropDown.AutoPostBack = true; dropDown.EnableViewState = false; DropDownPlaceHolder.Controls.Add(dropDown); DropDownPlaceHolder.Controls.Add(textBox); base.OnInit(e); } ``` If I can't disable ViewState on these controls, then I can never programmatically override what a user has entered/selected. I've tried placing this code in OnInit and Page\_Load, but the effect is the same in either location -- ViewState is enabled (the DropDownList maintains selected value and TextBox retains text that was entered). So, how can I disable ViewState and keep it from populating these controls? Thanks! --- Thanks for your response. Unfortunately, this isn't a workable solution in my situation. I will be dynamically loading controls based upon a configuration file, and some of those controls will load child controls. I need to be able to turn the ViewState of controls off individually, without the need to code logic for loading controls in different places (in OnInit vs. LoadComplete method).
It's a "feature" -- <http://support.microsoft.com/?id=316813> Thanks, Microsoft!!
234,564
<p>How do I make <a href="http://en.wikipedia.org/wiki/Vi" rel="noreferrer">vi</a>-<a href="http://en.wikipedia.org/wiki/Vim_%28text_editor%29" rel="noreferrer">Vim</a> never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like <a href="http://en.wikipedia.org/wiki/Emacs" rel="noreferrer">Emacs</a> does?</p> <p>Also, how do I save these settings so I never have to input them again?</p> <p>I've seen other questions related to this, but it always seems to be a little off from what I want.</p>
[ { "answer_id": 234578, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 12, "selected": true, "text": "<p>As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your <a href=\"https://stackoverflow.com/questions/10921441/where-is-my-vimrc-file\"><code>.vimrc</code></a>):</p>\n<pre><code>filetype plugin indent on\n&quot; show existing tab with 4 spaces width\nset tabstop=4\n&quot; when indenting with '&gt;', use 4 spaces width\nset shiftwidth=4\n&quot; On pressing tab, insert 4 spaces\nset expandtab\n</code></pre>\n<hr />\n<strike>\nIn your [.vimrc:][1] file:\n<pre><code>set smartindent\nset tabstop=4\nset shiftwidth=4\nset expandtab\n</code></pre>\n<p>The help files take a bit of time to get used to, but the more you read, the better Vim gets:</p>\n<pre><code>:help smartindent\n</code></pre>\n<p>Even better, you can embed these settings in your source for portability:</p>\n<pre><code>:help auto-setting\n</code></pre>\n<p>To see your current settings:</p>\n<pre><code>:set all\n</code></pre>\n<p>As <a href=\"https://stackoverflow.com/users/18038/graywh\">graywh</a> points out in the comments, smartindent has been replaced by cindent which &quot;Works more cleverly&quot;, although still mainly for languages with C-like syntax:</p>\n<pre><code>:help C-indenting\n</code></pre>\n</strike>\n" }, { "answer_id": 234597, "author": "Joey Gibson", "author_id": 6645, "author_profile": "https://Stackoverflow.com/users/6645", "pm_score": 4, "selected": false, "text": "<p>The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a <code>{</code> and hitting <kbd>Enter</kbd> indents the following line.</p>\n\n<p>As for tabs, there are two settings. Within Vim, type a colon and then \"set tabstop=4\" which will set the tabs to display as four spaces. Hit colon again and type \"set expandtab\" which will insert spaces for tabs. </p>\n\n<p>You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.</p>\n" }, { "answer_id": 323014, "author": "netjeff", "author_id": 41191, "author_profile": "https://Stackoverflow.com/users/41191", "pm_score": 8, "selected": false, "text": "<p>Related, if you open a file that uses both tabs and spaces, assuming you've got</p>\n\n<pre><code>set expandtab ts=4 sw=4 ai\n</code></pre>\n\n<p>You can replace all the tabs with spaces in the entire file with</p>\n\n<pre><code>:%retab\n</code></pre>\n" }, { "answer_id": 411670, "author": "graywh", "author_id": 18038, "author_profile": "https://Stackoverflow.com/users/18038", "pm_score": 7, "selected": false, "text": "<p>The best way to get filetype-specific indentation is to use <code>filetype plugin indent on</code> in your vimrc. Then you can specify things like <code>set sw=4 sts=4 et</code> in .vim/ftplugin/c.vim, for example, without having to make those global for all files being edited and other non-C type syntaxes will get indented correctly, too <em>(even lisps)</em>.</p>\n" }, { "answer_id": 21323445, "author": "Shervin Emami", "author_id": 199142, "author_profile": "https://Stackoverflow.com/users/199142", "pm_score": 6, "selected": false, "text": "<p>To have 4-space tabs in most files, real 8-wide tab char in Makefiles, and automatic indenting in various files including C/C++, put this in your <code>~/.vimrc</code> file:</p>\n\n<pre><code>\" Only do this part when compiled with support for autocommands.\nif has(\"autocmd\")\n \" Use filetype detection and file-based automatic indenting.\n filetype plugin indent on\n\n \" Use actual tab chars in Makefiles.\n autocmd FileType make set tabstop=8 shiftwidth=8 softtabstop=0 noexpandtab\nendif\n\n\" For everything else, use a tab width of 4 space chars.\nset tabstop=4 \" The width of a TAB is set to 4.\n \" Still it is a \\t. It is just that\n \" Vim will interpret it to be having\n \" a width of 4.\nset shiftwidth=4 \" Indents will have a width of 4.\nset softtabstop=4 \" Sets the number of columns for a TAB.\nset expandtab \" Expand TABs to spaces.\n</code></pre>\n" }, { "answer_id": 23426067, "author": "Chaudhry Junaid", "author_id": 2082308, "author_profile": "https://Stackoverflow.com/users/2082308", "pm_score": 5, "selected": false, "text": "<p>The recommended way is to use filetype based indentation and only use smartindent and cindent if that doesn't suffice.</p>\n\n<p>Add the following to your .vimrc</p>\n\n<pre><code>set expandtab\nset shiftwidth=2\nset softtabstop=2\nfiletype plugin indent on\n</code></pre>\n\n<p>Hope it helps as being a different answer.</p>\n" }, { "answer_id": 25119808, "author": "Erick", "author_id": 1125122, "author_profile": "https://Stackoverflow.com/users/1125122", "pm_score": 6, "selected": false, "text": "<p>On many Linux systems, like Ubuntu, the <code>.vimrc</code> file doesn't exist by default, so it is recommended that you create it first.</p>\n\n<p>Don't use the <code>.viminfo</code> file that exist in the home directory. It is used for a different purpose.</p>\n\n<p>Step 1: Go to your home directory</p>\n\n<p><code>cd ~</code></p>\n\n<p>Step 2: Create the file</p>\n\n<p><code>vim .vimrc</code></p>\n\n<p>Step 3: Add the configuration stated above</p>\n\n<pre><code>filetype plugin indent on\nset tabstop=4\nset shiftwidth=4\nset expandtab\n</code></pre>\n\n<p>Step 3: Save file, by pressing <kbd>Shift</kbd> + <kbd>ZZ</kbd>.</p>\n" }, { "answer_id": 33005115, "author": "Yusuf Ibrahim", "author_id": 2674072, "author_profile": "https://Stackoverflow.com/users/2674072", "pm_score": 4, "selected": false, "text": "<p>edit your ~/.vimrc</p>\n\n<pre><code>$ vim ~/.vimrc\n</code></pre>\n\n<p>add following lines :</p>\n\n<pre><code>set tabstop=4\nset shiftwidth=4\nset softtabstop=4\nset expandtab\n</code></pre>\n" }, { "answer_id": 33788330, "author": "User", "author_id": 2199852, "author_profile": "https://Stackoverflow.com/users/2199852", "pm_score": 4, "selected": false, "text": "<p>From the <a href=\"http://vim.wikia.com/wiki/Converting_tabs_to_spaces\">VIM wiki</a>:</p>\n\n<pre><code>:set tabstop=4\n:set shiftwidth=4\n:set expandtab\n</code></pre>\n" }, { "answer_id": 60103290, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 2, "selected": false, "text": "<p>Firstly, do not use the <kbd>Tab</kbd> key in Vim for manual indentation. Vim has a pair of commands in insert mode for manually increasing or decreasing the indentation amount. Those commands are <kbd>Ctrl-T</kbd> and <kbd>Ctrl-D</kbd>. These commands observe the values of <code>tabstop</code>, <code>shiftwidth</code> and <code>expandtab</code>, and maintain the correct mixture of spaces and tabs (maximum number of tabs followed by any necessary number of spaces).</p>\n\n<p>Secondly, these manual indenting keys don't have to be used very much anyway if you use automatic indentation.</p>\n\n<p>If <kbd>Ctrl-T</kbd> instead of <kbd>Tab</kbd> bothers you, you can remap it:</p>\n\n<pre><code>:imap &lt;Tab&gt; ^T\n</code></pre>\n\n<p>You can also remap <kbd>Shift-Tab</kbd> to do the <kbd>Ctrl-D</kbd> deindent:</p>\n\n<pre><code>:imap &lt;S-Tab&gt; ^D\n</code></pre>\n\n<p>Here ^T and ^D are literal control characters that can be inserted as <kbd>Ctrl-V</kbd><kbd>Ctrl-T</kbd>.</p>\n\n<p>With this mapping in place, you can still type literal Tab into the buffer using <kbd>Ctrl-V</kbd><kbd>Tab</kbd>. Note that if you do this, even if <code>:set expandtab</code> is on, you get an unexpanded tab character.</p>\n\n<p>A similar effect to the <code>&lt;Tab&gt;</code> map is achieved using <code>:set smarttab</code>, which also causes backspace at the front of a line to behave smart.</p>\n\n<p>In <code>smarttab</code> mode, when <kbd>Tab</kbd> is used not at the start of a line, it has no special meaning. That's different from my above mapping of <kbd>Tab</kbd> to <kbd>Ctrl-T</kbd>, because a <kbd>Ctrl-T</kbd> used anywhere in a line (in insert mode) will increase that line's indentation.</p>\n\n<p>Other useful mappings may be:</p>\n\n<pre><code>:map &lt;Tab&gt; &gt;\n:map &lt;S-Tab&gt; &lt;\n</code></pre>\n\n<p>Now we can do things like select some lines, and hit <kbd>Tab</kbd> to indent them over. Or hit <kbd>Tab</kbd> twice on a line (in command mode) to increase its indentation.</p>\n\n<p>If you use the proper indentation management commands, then everything is controlled by the three parameters: <code>shiftwidth</code>, <code>tabstop</code> and <code>expandtab</code>.</p>\n\n<p>The <code>shiftwidth</code> parameter controls your indentation size; if you want four space indents, use <code>:set shiftwidth=4</code>, or the abbreviation <code>:set sw=4</code>.</p>\n\n<p>If only this is done, then indentation will be created using a mixture of spaces and tabs, because <code>noexpandtab</code> is the default. Use <code>:set expandtab</code>. This causes tab characters which you type into the buffer to expand into spaces, and for Vim-managed indentation to use only spaces.</p>\n\n<p>When <code>expandtab</code> is on, and if you manage your indentation through all the proper Vim mechanisms, the value of <code>tabstop</code> becomes irrelevant. It controls how tabs appear if they happen to occur in the file. If you have <code>set tabstop=8 expandtab</code> and then sneak a hard tab into the file using <kbd>Ctrl-V</kbd><kbd>Tab</kbd>, it will produce an alignment to the next 8-column-based tab position, as usual.</p>\n" }, { "answer_id": 63152909, "author": "Cheung Johnson", "author_id": 11235024, "author_profile": "https://Stackoverflow.com/users/11235024", "pm_score": 2, "selected": false, "text": "<p>Afterall, you could edit the .vimrc,then add the conf</p>\n<pre><code>set tabstop=4\n</code></pre>\n<p>Or exec the command</p>\n" }, { "answer_id": 71031011, "author": "ashish", "author_id": 1542701, "author_profile": "https://Stackoverflow.com/users/1542701", "pm_score": 2, "selected": false, "text": "<p>Simplest one will be n vim file</p>\n<pre><code>set tabstop=4\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
How do I make [vi](http://en.wikipedia.org/wiki/Vi)-[Vim](http://en.wikipedia.org/wiki/Vim_%28text_editor%29) never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like [Emacs](http://en.wikipedia.org/wiki/Emacs) does? Also, how do I save these settings so I never have to input them again? I've seen other questions related to this, but it always seems to be a little off from what I want.
As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your [`.vimrc`](https://stackoverflow.com/questions/10921441/where-is-my-vimrc-file)): ``` filetype plugin indent on " show existing tab with 4 spaces width set tabstop=4 " when indenting with '>', use 4 spaces width set shiftwidth=4 " On pressing tab, insert 4 spaces set expandtab ``` --- In your [.vimrc:][1] file: ``` set smartindent set tabstop=4 set shiftwidth=4 set expandtab ``` The help files take a bit of time to get used to, but the more you read, the better Vim gets: ``` :help smartindent ``` Even better, you can embed these settings in your source for portability: ``` :help auto-setting ``` To see your current settings: ``` :set all ``` As [graywh](https://stackoverflow.com/users/18038/graywh) points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax: ``` :help C-indenting ```
234,589
<p>One problem that I come across regularly and yet don't have a solution to is to restrict or permit access to specific entities in a system. Some companies (banks, for example) have very strict policies regarding which employees may access certain information. For example, an employee at a specific branch may access account information for customers of that specific branch but not from other branches. Also, banks that have branches in many countries may be subject to legal restrictions that restricts employees in other countries from accessing information about domestic customers.</p> <p>Another example I've come across is a public website where users belong to a specific entity (such as a company) and may access information regarding that entity only and not other entities.</p> <p>If the number of entities is small and fixed, this is not a problem. Simply specify domain groups in the active directory (if you're working in Microsoft environments, which is the case for me), add users to the groups and restrict access using IsInRole() for each entity. So if there is a company called ABC in the system I'd create a domain group called "Admins_ABC" or something like that and when a user tries to administer information about ABC, I'd make sure the user is a member of that group. This is not really the way the AD is intended to be used, but for a small number of entities I've found it reasonable.</p> <p>The complexity increases when the number of entities change often and when the requirements become more detailed. I've seen security requirements that are similar to security in NTFS - some users (or groups of users) should be able to access some entities (files in NTFS) or groups of entities (the permissions that are set on directories in NTFS are propagated to it's children). </p> <p>I try to avoid situations like these because they tend to be a nightmare to model and code and they usually become complex to administer, but the customers I work with often need solutions to this problem.</p> <p>Like I said, I have never actually solved this problem in a <em>good</em> way. How would you go about modeling and developing a solution for this problem in a way that can be reused? Do you know of any general, proprietary solutions that can be used?</p>
[ { "answer_id": 234649, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 1, "selected": false, "text": "<p>Have you looked into the <a href=\"http://msdn.microsoft.com/en-us/library/930b76w0(VS.80).aspx\" rel=\"nofollow noreferrer\">Code Access Security</a> model that Microsoft created for the .NET framework? I have only looked at it on a few occasions myself, but the jist of it is that you can lock down certain objects and methods so that only users from internal networks can actually call that code. Or similarly, a method that does maintenance can only be called from the machine itself that the code is installed upon, preventing a third party from hacking a maintenance routine.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Code_Access_Security\" rel=\"nofollow noreferrer\">Wikipedia</a> makes a nice summary of CAS:</p>\n\n<blockquote>\n <p>Code Access Security (CAS), in the\n Microsoft .NET framework, is\n Microsoft's solution to prevent\n untrusted code from performing\n privileged actions. When the CLR loads\n an assembly it will obtain evidence\n for the assembly and use this to\n identify the code group that the\n assembly belongs to. A code group\n contains a permission set (one or more\n permissions). Code that performs a\n privileged action will perform a code\n access demand which will cause the CLR\n to walk up the call stack and examine\n the permission set granted to the\n assembly of each method in the call\n stack. The code groups and permission\n sets are determined by the\n administrator of the machine who\n defines the security policy.</p>\n</blockquote>\n\n<p><a href=\"http://www.15seconds.com/issue/040121.htm\" rel=\"nofollow noreferrer\">This article</a> from 15 Seconds has a nice and quick overview on how to get things going.</p>\n" }, { "answer_id": 234735, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": true, "text": "<p>I've beat my head against this wall on several occasions.</p>\n\n<p>The best solution I've come to was to model everything in a tree hierarchy, where every domain class is an branch in the tree, and instances are leaves of that branch. Leaves can have veins if you need to secure parts of instances. Each branch has its own assigned actions (such as \"Read\", \"Write\", \"Delete\", \"Publish\"). Use the same hierarchy for security but the root then becomes a user or a group. You end up with a structure like:</p>\n\n<pre><code>&lt;domain&gt; Project\n|- &lt;class&gt; Person\n| |- &lt;instance&gt; John\n| |- &lt;instance&gt; Mary\n|- &lt;class&gt; FormX\n| |- &lt;instance&gt; John's Leave Form\n...\n</code></pre>\n\n<p>and to apply security you may have a group named Administrators who can do stuff with people:</p>\n\n<pre><code>&lt;group&gt; Administrators\n|- &lt;class&gt; Person: actions (Read, Create, Update, Suspend)\n</code></pre>\n\n<p>and an office admin who can process forms and make new people:</p>\n\n<pre><code>&lt;group&gt; Office Administrator\n|- &lt;class&gt; Person: actions (Create)\n|- &lt;class&gt; FormX: actions (Approve, Deny)\n</code></pre>\n\n<p>and then John can do stuff with his own profile:</p>\n\n<pre><code>&lt;user&gt; John\n|- &lt;class&gt; Person\n| |- &lt;instance&gt; John: actions (Edit)\n</code></pre>\n\n<p>When I implemented this structure it was using C# and SQL Server 2000 so I was able to use the XML schema data type and perform security queries against the database or [as more often the case] merge a person's security profile into a single tree to determine what rights someone has to an instance, class, or other (I had <code>&lt;group&gt;</code>s - not security groups - in the domain above class for ease of maintenance).</p>\n\n<p>Its also important to include - though I did not illustrate it - that each action was a permission, not a boolean, where the permission values were <code>{ Allow, None, Deny }</code> with Allow granting access to that verb except when explicitly denied, None neither allowing nor denying, and Deny preventing access no matter what.</p>\n\n<p>An advantage you gain from this structure is that you can add other types of branches into it, such as a data driven taxonomy, and still use the same API.</p>\n\n<p>In my specific implementation I added custom metadata attributes to methods and properties and I had to invoke a <code>SecurityManager.Test</code> method in each \"secured\" function as a final layer of authorization (<code>SecurityManager.Test</code> was normally invoked to determine whether to show or hide pieces of a form, and determine which buttons were visible in the UI). Now that I am aware of it if I ever have to implement the same thing again, I'll use <a href=\"http://www.postsharp.org/\" rel=\"nofollow noreferrer\">PostSharp</a> to inject security tests into my domain model.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15157/" ]
One problem that I come across regularly and yet don't have a solution to is to restrict or permit access to specific entities in a system. Some companies (banks, for example) have very strict policies regarding which employees may access certain information. For example, an employee at a specific branch may access account information for customers of that specific branch but not from other branches. Also, banks that have branches in many countries may be subject to legal restrictions that restricts employees in other countries from accessing information about domestic customers. Another example I've come across is a public website where users belong to a specific entity (such as a company) and may access information regarding that entity only and not other entities. If the number of entities is small and fixed, this is not a problem. Simply specify domain groups in the active directory (if you're working in Microsoft environments, which is the case for me), add users to the groups and restrict access using IsInRole() for each entity. So if there is a company called ABC in the system I'd create a domain group called "Admins\_ABC" or something like that and when a user tries to administer information about ABC, I'd make sure the user is a member of that group. This is not really the way the AD is intended to be used, but for a small number of entities I've found it reasonable. The complexity increases when the number of entities change often and when the requirements become more detailed. I've seen security requirements that are similar to security in NTFS - some users (or groups of users) should be able to access some entities (files in NTFS) or groups of entities (the permissions that are set on directories in NTFS are propagated to it's children). I try to avoid situations like these because they tend to be a nightmare to model and code and they usually become complex to administer, but the customers I work with often need solutions to this problem. Like I said, I have never actually solved this problem in a *good* way. How would you go about modeling and developing a solution for this problem in a way that can be reused? Do you know of any general, proprietary solutions that can be used?
I've beat my head against this wall on several occasions. The best solution I've come to was to model everything in a tree hierarchy, where every domain class is an branch in the tree, and instances are leaves of that branch. Leaves can have veins if you need to secure parts of instances. Each branch has its own assigned actions (such as "Read", "Write", "Delete", "Publish"). Use the same hierarchy for security but the root then becomes a user or a group. You end up with a structure like: ``` <domain> Project |- <class> Person | |- <instance> John | |- <instance> Mary |- <class> FormX | |- <instance> John's Leave Form ... ``` and to apply security you may have a group named Administrators who can do stuff with people: ``` <group> Administrators |- <class> Person: actions (Read, Create, Update, Suspend) ``` and an office admin who can process forms and make new people: ``` <group> Office Administrator |- <class> Person: actions (Create) |- <class> FormX: actions (Approve, Deny) ``` and then John can do stuff with his own profile: ``` <user> John |- <class> Person | |- <instance> John: actions (Edit) ``` When I implemented this structure it was using C# and SQL Server 2000 so I was able to use the XML schema data type and perform security queries against the database or [as more often the case] merge a person's security profile into a single tree to determine what rights someone has to an instance, class, or other (I had `<group>`s - not security groups - in the domain above class for ease of maintenance). Its also important to include - though I did not illustrate it - that each action was a permission, not a boolean, where the permission values were `{ Allow, None, Deny }` with Allow granting access to that verb except when explicitly denied, None neither allowing nor denying, and Deny preventing access no matter what. An advantage you gain from this structure is that you can add other types of branches into it, such as a data driven taxonomy, and still use the same API. In my specific implementation I added custom metadata attributes to methods and properties and I had to invoke a `SecurityManager.Test` method in each "secured" function as a final layer of authorization (`SecurityManager.Test` was normally invoked to determine whether to show or hide pieces of a form, and determine which buttons were visible in the UI). Now that I am aware of it if I ever have to implement the same thing again, I'll use [PostSharp](http://www.postsharp.org/) to inject security tests into my domain model.
234,594
<p>In Eclipse, under <kbd>Windows</kbd> -> <kbd>Preference</kbd> -> <kbd>Java</kbd> -> <kbd>Code Style</kbd>, you can define code templates for comments and code, and you can setup a code formatter. </p> <p>I'm wondering if it is possible in Eclipse to have these setting take affect every time I save a source file. Basically, instead of me highlighting everything and pressing <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd>, I want Eclipse to be responsible for making sure my code is formatted properly.</p> <p>Is this possible and how do you set it up?</p> <p><strong>Note On Using the Auto-Format:</strong> It's probably best to choose "Format Edited Lines" as merging changes becomes very difficult when you reformat a whole file that is in source control already that was not formatted properly. Already did this to a co-worker.</p>
[ { "answer_id": 234625, "author": "Neal Swearer", "author_id": 29962, "author_profile": "https://Stackoverflow.com/users/29962", "pm_score": 9, "selected": true, "text": "<p>Under <kbd>Preferences</kbd>, choose <kbd>Java</kbd> --> <kbd>Editor</kbd> --> <kbd>Save Actions</kbd>. Check the <kbd>Perform the selected actions on save</kbd>, and check the <kbd>Format source code</kbd> box.</p>\n\n<p>This may or may not be available in previous versions of Eclipse. I know it works in:</p>\n\n<pre><code>Version: 3.3.3.r33x_r20080129-_19UEl7Ezk_gXF1kouft&lt;br&gt;\nBuild id: M20080221-1800\n</code></pre>\n" }, { "answer_id": 685268, "author": "serg10", "author_id": 1853, "author_profile": "https://Stackoverflow.com/users/1853", "pm_score": 4, "selected": false, "text": "<p>I strongly recommend checking your eclipse format xml descriptor into source control. That way all members of the team can use it and you don't get to and fro reformatting battles.</p>\n" }, { "answer_id": 1256078, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you find that you do not have a <kbd>Save Actions</kbd> preference under <kbd>Java</kbd>--> <kbd>Editor</kbd>, it may be because you are using an older version of Eclipse. In that case you can install the Format on save plugin from <a href=\"http://sourceforge.net/projects/ejp/files/eclipse%20formatonsave%20plugin/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Then, under <kbd>Preferences</kbd>, choose <kbd>Java</kbd> --> <kbd>Format on save</kbd>. Select the <kbd>Run Format</kbd> option under <kbd>Select a code formatting action</kbd> </p>\n" }, { "answer_id": 31066160, "author": "VeKe", "author_id": 1878022, "author_profile": "https://Stackoverflow.com/users/1878022", "pm_score": 4, "selected": false, "text": "<p>I have a snapshot of the setting.\nPlease follow the path:</p>\n\n<p>In the <kbd>Preferences</kbd> window, choose <kbd>Java</kbd> --> <kbd>Editor</kbd> --> <kbd>Save Actions</kbd>.</p>\n\n<p>Check the <kbd>Perform the selected actions on save</kbd>, and check the <kbd>Format source code box</kbd>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/t3Q9d.png\" alt=\"enter image description here\"></p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16524/" ]
In Eclipse, under `Windows` -> `Preference` -> `Java` -> `Code Style`, you can define code templates for comments and code, and you can setup a code formatter. I'm wondering if it is possible in Eclipse to have these setting take affect every time I save a source file. Basically, instead of me highlighting everything and pressing `Ctrl`+`Shift`+`F`, I want Eclipse to be responsible for making sure my code is formatted properly. Is this possible and how do you set it up? **Note On Using the Auto-Format:** It's probably best to choose "Format Edited Lines" as merging changes becomes very difficult when you reformat a whole file that is in source control already that was not formatted properly. Already did this to a co-worker.
Under `Preferences`, choose `Java` --> `Editor` --> `Save Actions`. Check the `Perform the selected actions on save`, and check the `Format source code` box. This may or may not be available in previous versions of Eclipse. I know it works in: ``` Version: 3.3.3.r33x_r20080129-_19UEl7Ezk_gXF1kouft<br> Build id: M20080221-1800 ```
234,600
<p>I would like to use <code>Class.newInstance()</code> but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?</p>
[ { "answer_id": 234610, "author": "iny", "author_id": 27067, "author_profile": "https://Stackoverflow.com/users/27067", "pm_score": 3, "selected": false, "text": "<p>You can get other constructors with <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getConstructor(java.lang.Class...)\" rel=\"noreferrer\">getConstructor(...)</a>.</p>\n" }, { "answer_id": 234614, "author": "Marko", "author_id": 31141, "author_profile": "https://Stackoverflow.com/users/31141", "pm_score": 7, "selected": false, "text": "<pre><code>myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);\n</code></pre>\n\n<p>Edit: according to the comments seems like pointing class and method names is not enough for some users. For more info take a look at the documentation for <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getDeclaredConstructor%28java.lang.Class...%29\" rel=\"noreferrer\">getting constuctor</a> and <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance%28java.lang.Object...%29\" rel=\"noreferrer\">invoking it</a>.</p>\n" }, { "answer_id": 234617, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 8, "selected": false, "text": "<pre><code>MyClass.class.getDeclaredConstructor(String.class).newInstance(\"HERESMYARG\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>obj.getClass().getDeclaredConstructor(String.class).newInstance(\"HERESMYARG\");\n</code></pre>\n" }, { "answer_id": 235196, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "<p>Do not use <code>Class.newInstance()</code>; see this thread: <a href=\"https://stackoverflow.com/questions/195321/why-is-classnewinstance-evil\">Why is Class.newInstance() evil?</a></p>\n\n<p>Like other answers say, use <code>Constructor.newInstance()</code> instead.</p>\n" }, { "answer_id": 17428883, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 1, "selected": false, "text": "<p>You can use the <code>getDeclaredConstructor</code> method of Class. It expects an array of classes. Here is a tested and working example:</p>\n\n<pre><code>public static JFrame createJFrame(Class c, String name, Component parentComponent)\n{\n try\n {\n JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance(\"name\");\n if (parentComponent != null)\n {\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n else\n {\n frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n }\n frame.setLocationRelativeTo(parentComponent);\n frame.pack();\n frame.setVisible(true);\n }\n catch (InstantiationException instantiationException)\n {\n ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());\n }\n catch(NoSuchMethodException noSuchMethodException)\n {\n //ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, \"NamedConstructor\");\n ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), \"(Constructor or a JFrame method)\");\n }\n catch (IllegalAccessException illegalAccessException)\n {\n ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));\n }\n catch (InvocationTargetException invocationTargetException)\n {\n ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));\n }\n finally\n {\n return null;\n }\n}\n</code></pre>\n" }, { "answer_id": 23267674, "author": "Spyros Doulgeridis", "author_id": 547190, "author_profile": "https://Stackoverflow.com/users/547190", "pm_score": 1, "selected": false, "text": "<p>I think this is exactly what you want \n<a href=\"http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html\" rel=\"nofollow\">http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html</a></p>\n\n<p>Although it seems a dead thread, someone might find it useful</p>\n" }, { "answer_id": 24109870, "author": "Martin Konecny", "author_id": 276949, "author_profile": "https://Stackoverflow.com/users/276949", "pm_score": 6, "selected": false, "text": "<p>Assuming you have the following constructor</p>\n\n<pre><code>class MyClass {\n public MyClass(Long l, String s, int i) {\n\n }\n}\n</code></pre>\n\n<p>You will need to show you intend to use this constructor like so:</p>\n\n<pre><code>Class classToLoad = MyClass.class;\n\nClass[] cArg = new Class[3]; //Our constructor has 3 arguments\ncArg[0] = Long.class; //First argument is of *object* type Long\ncArg[1] = String.class; //Second argument is of *object* type String\ncArg[2] = int.class; //Third argument is of *primitive* type int\n\nLong l = new Long(88);\nString s = \"text\";\nint i = 5;\n\nclassToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);\n</code></pre>\n" }, { "answer_id": 40318262, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 3, "selected": false, "text": "<p>Follow below steps to call parameterized consturctor.</p>\n\n<ol>\n<li>Get <code>Constructor</code> with parameter types by passing types in <code>Class[]</code>\nfor <code>getDeclaredConstructor</code> method of <code>Class</code></li>\n<li>Create constructor instance by passing values in <code>Object[]</code> for<br>\n<code>newInstance</code> method of <code>Constructor</code></li>\n</ol>\n\n<p>Example code:</p>\n\n<pre><code>import java.lang.reflect.*;\n\nclass NewInstanceWithReflection{\n public NewInstanceWithReflection(){\n System.out.println(\"Default constructor\");\n }\n public NewInstanceWithReflection( String a){\n System.out.println(\"Constructor :String =&gt; \"+a);\n }\n public static void main(String args[]) throws Exception {\n\n NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName(\"NewInstanceWithReflection\").newInstance();\n Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});\n NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{\"StackOverFlow\"});\n\n }\n}\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>java NewInstanceWithReflection\nDefault constructor\nConstructor :String =&gt; StackOverFlow\n</code></pre>\n" }, { "answer_id": 74557289, "author": "Optimus Prime", "author_id": 1723626, "author_profile": "https://Stackoverflow.com/users/1723626", "pm_score": 0, "selected": false, "text": "<p>This is how I created an instance of <code>Class clazz</code> using a dynamic constructor args list.</p>\n<pre><code>final Constructor constructor = clazz.getConstructors()[0];\nfinal int constructorArgsCount = constructor.getParameterCount();\nif (constructorArgsCount &gt; 0) {\n final Object[] constructorArgs = new Object[constructorArgsCount];\n int i = 0;\n for (Class parameterClass : constructor.getParameterTypes()) {\n Object dummyParameterValue = getDummyValue(Class.forName(parameterClass.getTypeName()), null);\n constructorArgs[i++] = dummyParameterValue;\n }\n instance = constructor.newInstance(constructorArgs);\n} else {\n instance = clazz.newInstance();\n}\n</code></pre>\n<p>This is what <code>getDummyValue()</code> method looks like,</p>\n<pre><code>private static Object getDummyValue(final Class clazz, final Field field) throws Exception {\n if (int.class.equals(clazz) || Integer.class.equals(clazz)) {\n return DUMMY_INT;\n } else if (String.class.equals(clazz)) {\n return DUMMY_STRING;\n } else if (boolean.class.equals(clazz) || Boolean.class.equals(clazz)) {\n return DUMMY_BOOL;\n } else if (List.class.equals(clazz)) {\n Class fieldClassGeneric = Class.forName(((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0].getTypeName());\n return List.of(getDummyValue(fieldClassGeneric, null));\n } else if (USER_DEFINED_CLASSES.contains(clazz.getSimpleName())) {\n return createClassInstance(clazz);\n } else {\n throw new Exception(&quot;Dummy value for class type not defined - &quot; + clazz.getName();\n }\n}\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like to use `Class.newInstance()` but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?
``` MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG"); ``` or ``` obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG"); ```
234,657
<p>We have a Procedure in Oracle with a SYS_REFCURSOR output parameter that returns the data we want to bind to an ASP.NET GridView control. I've seen this done before but I can't find the original reference I used to solve the problem.</p> <p>Here is what the procedure looks like:</p> <pre><code>create or replace PROCEDURE GETSOMEDATA ( P_Data OUT SYS_REFCURSOR ) AS BEGIN OPEN P_Data FOR SELECT * FROM SOMETABLE; END GETSOMEDATA; </code></pre> <p>And for now the GridView is just bare-bones:</p> <pre><code>&lt;asp:GridView ID="grdData" runat="server" AutoGenerateColumns="true"&gt;&lt;/asp:GridView&gt; </code></pre>
[ { "answer_id": 234798, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 1, "selected": false, "text": "<p>just GooglingIt trying to find out an answer for you, <a href=\"http://www.enterprisedb.com/documentation/dotnetprovider-refcursors.html\" rel=\"nofollow noreferrer\">I come across this article</a>.</p>\n\n<p>maybe it can help you on this matter.</p>\n" }, { "answer_id": 243611, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 2, "selected": true, "text": "<p>Try something like: (didn't specify which language)</p>\n\n<pre><code> Public Function GetSomeData() as DataTable\n Dim OrclConn as New OracleConnection(\"Connectionstring\")\n Dim OrclCmd as New Oraclecommand(\"GETSOMEDATA\", OrclConn)\n OrclCmd.CommandType = CommandType.StoredProcedure\n OrclCmd.Parameters.Add(\"P_Data\", OracleType.Cursor).Direction = ParameterDirection.Output 'Or ParameterDirection.ReturnValue\n\n Dim OrclDA as New OracleDataAdapter(OrclCmd)\n Dim RtnTable as DataTable\n OrclConn.Open\n OrclDA.Fill(RtnTable)\n OrclConn.Close\n\n Return RtnTable\n End Function\n</code></pre>\n" }, { "answer_id": 359073, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<pre><code>Dim oracon As New OracleConnection(\"User Id=developer;Password=developer;Data Source=orcl;\")\n Dim ds As New Data.DataSet\n Dim qry As String\n oracon.Open()\n qry = \"select * from Employee\"\n Dim adp As New OracleDataAdapter(qry, oracon)\n adp.Fill(ds)\n GridView1.DataSource = ds\n GridView1.DataBind()\n oracon.Close()\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31267/" ]
We have a Procedure in Oracle with a SYS\_REFCURSOR output parameter that returns the data we want to bind to an ASP.NET GridView control. I've seen this done before but I can't find the original reference I used to solve the problem. Here is what the procedure looks like: ``` create or replace PROCEDURE GETSOMEDATA ( P_Data OUT SYS_REFCURSOR ) AS BEGIN OPEN P_Data FOR SELECT * FROM SOMETABLE; END GETSOMEDATA; ``` And for now the GridView is just bare-bones: ``` <asp:GridView ID="grdData" runat="server" AutoGenerateColumns="true"></asp:GridView> ```
Try something like: (didn't specify which language) ``` Public Function GetSomeData() as DataTable Dim OrclConn as New OracleConnection("Connectionstring") Dim OrclCmd as New Oraclecommand("GETSOMEDATA", OrclConn) OrclCmd.CommandType = CommandType.StoredProcedure OrclCmd.Parameters.Add("P_Data", OracleType.Cursor).Direction = ParameterDirection.Output 'Or ParameterDirection.ReturnValue Dim OrclDA as New OracleDataAdapter(OrclCmd) Dim RtnTable as DataTable OrclConn.Open OrclDA.Fill(RtnTable) OrclConn.Close Return RtnTable End Function ```
234,683
<p>Which algorithm does the JavaScript <code>Array#sort()</code> function use? I understand that it can take all manner of arguments and functions to perform different kinds of sorts, I'm simply interested in which algorithm the vanilla sort uses.</p>
[ { "answer_id": 234706, "author": "Huibert Gill", "author_id": 1254442, "author_profile": "https://Stackoverflow.com/users/1254442", "pm_score": 3, "selected": false, "text": "<p>I think that would depend on what browser implementation you are refering to.</p>\n\n<p>Every browser type has it's own javascript engine implementation, so it depends.\nYou could check the sourcecode repos for Mozilla and Webkit/Khtml for different implementations.</p>\n\n<p>IE is closed source however, so you may have to ask somebody at microsoft.</p>\n" }, { "answer_id": 234777, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>The ECMAscript standard does not specify which sort algorithm is to be used. Indeed, different browsers feature different sort algorithms. For example, Mozilla/Firefox's sort() is not <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm#Stability\" rel=\"noreferrer\">stable</a> (in the sorting sense of the word) when sorting a map. IE's sort() is stable.</p>\n" }, { "answer_id": 234808, "author": "latortuga", "author_id": 11042, "author_profile": "https://Stackoverflow.com/users/11042", "pm_score": 3, "selected": false, "text": "<p>After some more research, it appears, for Mozilla/Firefox, that Array.sort() uses mergesort. See the code <a href=\"https://dxr.mozilla.org/seamonkey/source/js/src/jsarray.c\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 234813, "author": "Britton", "author_id": 26274, "author_profile": "https://Stackoverflow.com/users/26274", "pm_score": 6, "selected": false, "text": "<p>If you look at this bug <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=224128\" rel=\"noreferrer\">224128</a>, it appears that MergeSort is being used by Mozilla.</p>\n" }, { "answer_id": 236534, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 9, "selected": true, "text": "<p>I've just had a look at the WebKit (Chrome, Safari …) <a href=\"http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/ArrayPrototype.cpp?rev=138530#L647\" rel=\"noreferrer\">source</a>. Depending on the type of array, different sort methods are used:</p>\n\n<p><a href=\"http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/JSArray.cpp?rev=138530#L972\" rel=\"noreferrer\">Numeric arrays</a> (or arrays of primitive type) are sorted using the C++ standard library function <a href=\"http://en.cppreference.com/w/cpp/algorithm/qsort\" rel=\"noreferrer\"><code>std::qsort</code></a> which implements some variation of quicksort (usually <a href=\"https://en.wikipedia.org/wiki/Introsort\" rel=\"noreferrer\">introsort</a>).</p>\n\n<p><a href=\"http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/JSArray.cpp?rev=138530#L1065\" rel=\"noreferrer\">Contiguous arrays of non-numeric type</a> are stringified and sorted using mergesort, if available (to obtain a stable sorting) or <code>qsort</code> if no merge sort is available.</p>\n\n<p>For other types (non-contiguous arrays and presumably for associative arrays) WebKit uses either <a href=\"http://en.wikipedia.org/wiki/Selection_Sort\" rel=\"noreferrer\">selection sort</a> (which they call <a href=\"http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/ArrayPrototype.cpp?rev=138530#L668\" rel=\"noreferrer\">“min” sort</a>) or, in some cases, it sorts via an AVL tree. Unfortunately, the documentation here is rather vague so you’d have to trace the code paths to actually see for which types which sort method is used.</p>\n\n<p>And then there are gems like <a href=\"http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/JSArray.cpp?rev=138530#L1124\" rel=\"noreferrer\">this comment</a>:</p>\n\n<pre><code>// FIXME: Since we sort by string value, a fast algorithm might be to use a\n// radix sort. That would be O(N) rather than O(N log N).\n</code></pre>\n\n<p>– Let’s just hope that whoever actually “fixes” this has a better understanding of asymptotic runtime than the writer of this comment, and realises that <a href=\"https://stackoverflow.com/a/474040/1968\">radix sort has a slightly more complex runtime description</a> than simply O(N).</p>\n\n<p>(Thanks to phsource for pointing out the error in the original answer.)</p>\n" }, { "answer_id": 37245185, "author": "Joe Thomas", "author_id": 3072896, "author_profile": "https://Stackoverflow.com/users/3072896", "pm_score": 6, "selected": false, "text": "<p>There is no draft requirement for JS to use a specific sorting algorthim. As many have mentioned here, Mozilla uses merge sort.However, In Chrome's v8 source code, as of today, it uses QuickSort and InsertionSort, for smaller arrays.</p>\n\n<p><a href=\"https://github.com/v8/v8/blob/master/src/js/array.js#L720\" rel=\"noreferrer\">V8 Engine Source</a></p>\n\n<p>From Lines 807 - 891</p>\n\n<pre><code> var QuickSort = function QuickSort(a, from, to) {\n var third_index = 0;\n while (true) {\n // Insertion sort is faster for short arrays.\n if (to - from &lt;= 10) {\n InsertionSort(a, from, to);\n return;\n }\n if (to - from &gt; 1000) {\n third_index = GetThirdIndex(a, from, to);\n } else {\n third_index = from + ((to - from) &gt;&gt; 1);\n }\n // Find a pivot as the median of first, last and middle element.\n var v0 = a[from];\n var v1 = a[to - 1];\n var v2 = a[third_index];\n var c01 = comparefn(v0, v1);\n if (c01 &gt; 0) {\n // v1 &lt; v0, so swap them.\n var tmp = v0;\n v0 = v1;\n v1 = tmp;\n } // v0 &lt;= v1.\n var c02 = comparefn(v0, v2);\n if (c02 &gt;= 0) {\n // v2 &lt;= v0 &lt;= v1.\n var tmp = v0;\n v0 = v2;\n v2 = v1;\n v1 = tmp;\n } else {\n // v0 &lt;= v1 &amp;&amp; v0 &lt; v2\n var c12 = comparefn(v1, v2);\n if (c12 &gt; 0) {\n // v0 &lt;= v2 &lt; v1\n var tmp = v1;\n v1 = v2;\n v2 = tmp;\n }\n }\n // v0 &lt;= v1 &lt;= v2\n a[from] = v0;\n a[to - 1] = v2;\n var pivot = v1;\n var low_end = from + 1; // Upper bound of elements lower than pivot.\n var high_start = to - 1; // Lower bound of elements greater than pivot.\n a[third_index] = a[low_end];\n a[low_end] = pivot;\n\n // From low_end to i are elements equal to pivot.\n // From i to high_start are elements that haven't been compared yet.\n partition: for (var i = low_end + 1; i &lt; high_start; i++) {\n var element = a[i];\n var order = comparefn(element, pivot);\n if (order &lt; 0) {\n a[i] = a[low_end];\n a[low_end] = element;\n low_end++;\n } else if (order &gt; 0) {\n do {\n high_start--;\n if (high_start == i) break partition;\n var top_elem = a[high_start];\n order = comparefn(top_elem, pivot);\n } while (order &gt; 0);\n a[i] = a[high_start];\n a[high_start] = element;\n if (order &lt; 0) {\n element = a[i];\n a[i] = a[low_end];\n a[low_end] = element;\n low_end++;\n }\n }\n }\n if (to - high_start &lt; low_end - from) {\n QuickSort(a, high_start, to);\n to = low_end;\n } else {\n QuickSort(a, from, low_end);\n from = high_start;\n }\n }\n };\n</code></pre>\n\n<p><strong>Update</strong>\nAs of 2018 V8 uses TimSort, thanks @celwell. <a href=\"https://github.com/v8/v8/blob/78f2610345fdd14ca401d920c140f8f461b631d1/third_party/v8/builtins/array-sort.tq#L5\" rel=\"noreferrer\">Source</a></p>\n" }, { "answer_id": 53878055, "author": "Boris Verkhovskiy", "author_id": 3064538, "author_profile": "https://Stackoverflow.com/users/3064538", "pm_score": 3, "selected": false, "text": "<p>Google Chrome uses <a href=\"https://en.wikipedia.org/wiki/Timsort\" rel=\"nofollow noreferrer\">TimSort</a>, Python's sorting algorithm, as of version 70 released on September 13, 2018.</p>\n<p>See the <a href=\"https://v8.dev/blog/array-sort\" rel=\"nofollow noreferrer\">the post on the V8 dev blog</a> (<a href=\"https://en.wikipedia.org/wiki/V8_(JavaScript_engine)\" rel=\"nofollow noreferrer\">V8</a> is Chrome's JavaScript engine) for details about this change. You can read the <a href=\"https://chromium.googlesource.com/v8/v8.git/+/master/third_party/v8/builtins/array-sort.tq\" rel=\"nofollow noreferrer\">source code</a> or <a href=\"https://chromium-review.googlesource.com/c/v8/v8/+/1186801\" rel=\"nofollow noreferrer\">patch 1186801</a> specifically.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11042/" ]
Which algorithm does the JavaScript `Array#sort()` function use? I understand that it can take all manner of arguments and functions to perform different kinds of sorts, I'm simply interested in which algorithm the vanilla sort uses.
I've just had a look at the WebKit (Chrome, Safari …) [source](http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/ArrayPrototype.cpp?rev=138530#L647). Depending on the type of array, different sort methods are used: [Numeric arrays](http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/JSArray.cpp?rev=138530#L972) (or arrays of primitive type) are sorted using the C++ standard library function [`std::qsort`](http://en.cppreference.com/w/cpp/algorithm/qsort) which implements some variation of quicksort (usually [introsort](https://en.wikipedia.org/wiki/Introsort)). [Contiguous arrays of non-numeric type](http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/JSArray.cpp?rev=138530#L1065) are stringified and sorted using mergesort, if available (to obtain a stable sorting) or `qsort` if no merge sort is available. For other types (non-contiguous arrays and presumably for associative arrays) WebKit uses either [selection sort](http://en.wikipedia.org/wiki/Selection_Sort) (which they call [“min” sort](http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/ArrayPrototype.cpp?rev=138530#L668)) or, in some cases, it sorts via an AVL tree. Unfortunately, the documentation here is rather vague so you’d have to trace the code paths to actually see for which types which sort method is used. And then there are gems like [this comment](http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/runtime/JSArray.cpp?rev=138530#L1124): ``` // FIXME: Since we sort by string value, a fast algorithm might be to use a // radix sort. That would be O(N) rather than O(N log N). ``` – Let’s just hope that whoever actually “fixes” this has a better understanding of asymptotic runtime than the writer of this comment, and realises that [radix sort has a slightly more complex runtime description](https://stackoverflow.com/a/474040/1968) than simply O(N). (Thanks to phsource for pointing out the error in the original answer.)
234,695
<p>Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django?</p> <pre><code> urlpatterns = patterns('',(r'^test/(?P&lt;name&gt;.*)?$','myview.displayName')) #myview.py def displayName(request,name): # write name to response or something </code></pre> <p>I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving the name parameter a default value on the method, none of which worked. the name parameter always seems to be None. I really dont want to code a check for None if i could set a default value.</p> <p>Clarification: here is an example of what i was changing it to.</p> <pre><code> def displayName(request,name='Steve'): return HttpResponse(name) #i also tried urlpatterns = patterns('', (r'^test/(?P&lt;name&gt;.*)?$', 'myview.displayName', dict(name='Test') ) ) </code></pre> <p>when i point my browser at the view it displays the text 'None'</p> <p>Any ideas?</p>
[ { "answer_id": 234741, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 0, "selected": false, "text": "<p>I <em>thought</em> you could <code>def displayName(request, name=defaultObj)</code>; that's what I've done in the past, at least. What were you setting the default value to?</p>\n" }, { "answer_id": 234995, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 4, "selected": true, "text": "<p>The problem is that when the pattern is matched against 'test/' the groupdict captured by the regex contains the mapping 'name' => None:</p>\n\n<pre><code>&gt;&gt;&gt; url.match(\"test/\").groupdict()\n{'name': None}\n</code></pre>\n\n<p>This means that when the view is invoked, using something I expect that is similar to below:</p>\n\n<pre><code>view(request, *groups, **groupdict)\n</code></pre>\n\n<p>which is equivalent to:</p>\n\n<pre><code>view(request, name = None)\n</code></pre>\n\n<p>for 'test/', meaning that name is assigned None rather than not assigned.</p>\n\n<p>This leaves you with two options. You can:</p>\n\n<ol>\n<li>Explicitly check for None in the view code which is kind of hackish.</li>\n<li>Rewrite the url dispatch rule to make the name capture non-optional and introduce a second rule to capture when no name is provided. </li>\n</ol>\n\n<p>For example:</p>\n\n<pre><code>urlpatterns = patterns('',\n (r'^test/(?P&lt;name&gt;.+)$','myview.displayName'), # note the '+' instead of the '*'\n (r'^test/$','myview.displayName'),\n)\n</code></pre>\n\n<p>When taking the second approach, you can simply call the method without the capture pattern, and let python handle the default parameter or you can call a different view which delegates.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24730/" ]
Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django? ``` urlpatterns = patterns('',(r'^test/(?P<name>.*)?$','myview.displayName')) #myview.py def displayName(request,name): # write name to response or something ``` I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving the name parameter a default value on the method, none of which worked. the name parameter always seems to be None. I really dont want to code a check for None if i could set a default value. Clarification: here is an example of what i was changing it to. ``` def displayName(request,name='Steve'): return HttpResponse(name) #i also tried urlpatterns = patterns('', (r'^test/(?P<name>.*)?$', 'myview.displayName', dict(name='Test') ) ) ``` when i point my browser at the view it displays the text 'None' Any ideas?
The problem is that when the pattern is matched against 'test/' the groupdict captured by the regex contains the mapping 'name' => None: ``` >>> url.match("test/").groupdict() {'name': None} ``` This means that when the view is invoked, using something I expect that is similar to below: ``` view(request, *groups, **groupdict) ``` which is equivalent to: ``` view(request, name = None) ``` for 'test/', meaning that name is assigned None rather than not assigned. This leaves you with two options. You can: 1. Explicitly check for None in the view code which is kind of hackish. 2. Rewrite the url dispatch rule to make the name capture non-optional and introduce a second rule to capture when no name is provided. For example: ``` urlpatterns = patterns('', (r'^test/(?P<name>.+)$','myview.displayName'), # note the '+' instead of the '*' (r'^test/$','myview.displayName'), ) ``` When taking the second approach, you can simply call the method without the capture pattern, and let python handle the default parameter or you can call a different view which delegates.
234,723
<p>I would like to redirect <code>www.example.com</code> to <code>example.com</code>. The following htaccess code makes this happen:</p> <pre><code>RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] </code></pre> <p>But, is there a way to do this in a generic fashion without hardcoding the domain name?</p>
[ { "answer_id": 234745, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^www\\. [NC]\nRewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]\nRewriteRule ^www\\.(.*)$ http://$1 [L,R=301]\n</code></pre>\n\n<p>If the host starts with www, we stick the whole host onto the start of the URL, then take off the \"www.\"</p>\n" }, { "answer_id": 235064, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 4, "selected": false, "text": "<pre><code>RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^/(.*)$ https://%1/$1 [R]\n</code></pre>\n\n<p>The <code>RewriteCond</code> captures everything in the <code>HTTP_HOST</code> variable <em>after</em> the <code>www.</code> and saves it in <code>%1</code>.</p>\n\n<p>The <code>RewriteRule</code> captures the URL without the leading <code>/</code> and saves it in <code>$1</code>.</p>\n" }, { "answer_id": 1270281, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "<pre><code>RewriteEngine On\nRewriteBase /\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ https://%1/$1 [R=301,L]\n</code></pre>\n\n<p>Same as <a href=\"https://stackoverflow.com/a/235064/662581\">Michael's</a> except this one works :P</p>\n" }, { "answer_id": 2475982, "author": "Andron", "author_id": 284602, "author_profile": "https://Stackoverflow.com/users/284602", "pm_score": 7, "selected": false, "text": "<p>But if we need to do this for separate http and https:</p>\n\n<pre><code>RewriteCond %{HTTPS} off\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n\nRewriteCond %{HTTPS} on\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ https://%1/$1 [R=301,L]\n</code></pre>\n" }, { "answer_id": 4715215, "author": "Htaccess Redirect", "author_id": 578750, "author_profile": "https://Stackoverflow.com/users/578750", "pm_score": 3, "selected": false, "text": "<p>There can be a lot of misinformation out there about htaccess redirects, I find. First off, make sure your site is running on Unix using Apache and not on a Windows host if you expect this code to work. </p>\n\n<pre><code>RewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^www\\.(.+)$ [NC]\n\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L] \n</code></pre>\n\n<p>(Make sure there are no line spaces between each line of text, though; I have added an extra space between lines so it renders okay in this window.)</p>\n\n<p>This is one snippet of code that can be used to direct the www version of your site to the http:// version. There are other similar codes that can be used, too.</p>\n" }, { "answer_id": 5145927, "author": "sulfy", "author_id": 638181, "author_profile": "https://Stackoverflow.com/users/638181", "pm_score": 1, "selected": false, "text": "<p>The only way I got it to work...</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^site\\.ro\nRewriteRule (.*) http://www.site.ro/$1 [R=301,L]\n</code></pre>\n" }, { "answer_id": 5254797, "author": "William Denniss", "author_id": 72176, "author_profile": "https://Stackoverflow.com/users/72176", "pm_score": 6, "selected": false, "text": "<p>If you want to do this in the httpd.conf file, you can do it without mod_rewrite (and apparently it's better for performance).</p>\n\n<pre><code>&lt;VirtualHost *&gt;\n ServerName www.example.com\n Redirect 301 / http://example.com/\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>I got that answer here: <a href=\"https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost/120507#120507\">https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost/120507#120507</a></p>\n" }, { "answer_id": 5262044, "author": "Dmytro", "author_id": 541961, "author_profile": "https://Stackoverflow.com/users/541961", "pm_score": 6, "selected": false, "text": "<p>Redirect <strong>non-www</strong> to <strong>www</strong> (both: http + https)</p>\n\n<pre><code>RewriteCond %{HTTPS} off\nRewriteCond %{HTTP_HOST} !^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]\n\nRewriteCond %{HTTPS} on\nRewriteCond %{HTTP_HOST} !^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]\n</code></pre>\n" }, { "answer_id": 7822978, "author": "pelajar", "author_id": 908647, "author_profile": "https://Stackoverflow.com/users/908647", "pm_score": 2, "selected": false, "text": "<pre><code>RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1/subfolder/$1 [R=301,L]\n</code></pre>\n\n<p>For subfolder</p>\n" }, { "answer_id": 8538284, "author": "local", "author_id": 1028069, "author_profile": "https://Stackoverflow.com/users/1028069", "pm_score": 0, "selected": false, "text": "<p>I am not sure why u want to remove www.\nBut reverse version would be:</p>\n\n<pre><code># non-www.* -&gt; www.*, if subdomain exist, wont work\nRewriteCond %{HTTP_HOST} ^whattimein\\.com\nRewriteRule ^(.*)$ http://www.whattimein.com/$1 [R=permanent,L]\n</code></pre>\n\n<p>And advantage of this script is: \nif u have something like test.whattimein.com or any other (enviroments for developing/testing) \nit wont redirect U to the original enviroment.</p>\n" }, { "answer_id": 10362615, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 5, "selected": false, "text": "<p>Here are the rules to redirect a www URL to no-www:</p>\n\n<pre><code>#########################\n# redirect www to no-www\n#########################\n\nRewriteCond %{HTTP_HOST} ^www\\.(.+) [NC]\nRewriteRule ^(.*) http://%1/$1 [R=301,NE,L]\n</code></pre>\n\n<p>Here are the rules to redirect a no-www URL to www:</p>\n\n<pre><code>#########################\n# redirect no-www to www\n#########################\n\nRewriteCond %{HTTP_HOST} ^(?!www\\.)(.+) [NC]\nRewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]\n</code></pre>\n\n<p>Note that I used <code>NE</code> flag to prevent apache from escaping the query string. Without this flag, apache will change the requested URL <code>http://www.example.com/?foo%20bar</code> to <code>http://www.example.com/?foo%2250bar</code></p>\n" }, { "answer_id": 10698176, "author": "Luke", "author_id": 1409662, "author_profile": "https://Stackoverflow.com/users/1409662", "pm_score": 2, "selected": false, "text": "<p>I used the above rule to fwd www to no www and it works fine for the homepage, however on the internal pages they are forwarding to /index.php</p>\n\n<p>I found this other rule in my .htaccess file which is causing this but not sure what to do about it. Any suggestions would be great: </p>\n\n<pre><code>############################################\n## always send 404 on missing files in these folders\n\n RewriteCond %{REQUEST_URI} !^/(media|skin|js)/\n\n############################################\n## never rewrite for existing files, directories and links\n\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteCond %{REQUEST_FILENAME} !-l\n\n############################################\n## rewrite everything else to index.php\n\n RewriteRule .* index.php [L]\n</code></pre>\n" }, { "answer_id": 23273563, "author": "mystique", "author_id": 3568781, "author_profile": "https://Stackoverflow.com/users/3568781", "pm_score": 1, "selected": false, "text": "<p>If you are forcing www. in url or forcing ssl prototcol, then try to use possible variations in htaccess file, such as:</p>\n\n<pre>\nRewriteEngine On\nRewriteBase /\n\n### Force WWW ###\n\nRewriteCond %{HTTP_HOST} ^example\\.com\nRewriteRule (.*) http://www.example.com/$1 [R=301,L]\n\n## Force SSL ###\n\nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://example.com/$1 [R,L]\n\n## Block IP's ###\nOrder Deny,Allow\nDeny from 256.251.0.139\nDeny from 199.127.0.259\n</pre>\n" }, { "answer_id": 25672535, "author": "Rick", "author_id": 1827424, "author_profile": "https://Stackoverflow.com/users/1827424", "pm_score": 2, "selected": false, "text": "<p>For those that need to able to access the entire site <strong>WITHOUT</strong> the 'www' prefix.</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^www\\.(.+)$ [NC]\nRewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Mare sure you add this to the following file</p>\n\n<pre><code>/site/location/.htaccess \n</code></pre>\n" }, { "answer_id": 28831108, "author": "Rajith Ramachandran", "author_id": 2881568, "author_profile": "https://Stackoverflow.com/users/2881568", "pm_score": 2, "selected": false, "text": "<p>www to non www with https</p>\n\n<pre><code>RewriteEngine on\n\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n\nRewriteCond %{HTTPS} !on\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n</code></pre>\n" }, { "answer_id": 30052977, "author": "Chirag Parekh", "author_id": 2389637, "author_profile": "https://Stackoverflow.com/users/2389637", "pm_score": -1, "selected": false, "text": "<p>Hi you can use following rules on your htaccess file:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^example.com\nRewriteRule (.*) http://www.example.com/$1 [R=301,L]\n</code></pre>\n" }, { "answer_id": 35297464, "author": "Gregor Macgregor", "author_id": 5711788, "author_profile": "https://Stackoverflow.com/users/5711788", "pm_score": 3, "selected": false, "text": "<p>Complete Generic WWW handler, http/https</p>\n\n<p>I didn't see a complete answer. I use this to handle WWW inclusion.</p>\n\n<ol>\n<li>Generic. Doesn't require domain info.</li>\n<li>Forces WWW on primary domain: www.domain.com</li>\n<li>Removes WWW on subdomains: sub.domain.com</li>\n<li>Preserves HTTP/HTTPS status.</li>\n<li>Allows individual cookies for domain / sub-domains</li>\n</ol>\n\n<p>Please let me know how this works or if I left a loophole.</p>\n\n<pre><code>RewriteEngine On\nRewriteBase /\n\n# Force WWW. when no subdomain in host\nRewriteCond %{HTTP_HOST} ^[^.]+\\.[^.]+$ [NC]\nRewriteCond %{HTTPS}s ^on(s)|off [NC]\nRewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n\n# Remove WWW. when subdomain(s) in host \nRewriteCond %{HTTP_HOST} ^www\\. [NC]\nRewriteCond %{HTTPS}s ^on(s)|off [NC]\nRewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\\.)(.+\\.)(.+\\.)(.+)$ [NC]\nRewriteRule ^ %1%3%4%5%{REQUEST_URI} [R=301,L]\n</code></pre>\n" }, { "answer_id": 37055252, "author": "William Entriken", "author_id": 300224, "author_profile": "https://Stackoverflow.com/users/300224", "pm_score": 1, "selected": false, "text": "<p>This is updated to work on Apache 2.4:</p>\n\n<pre><code>RewriteEngine On\nRewriteBase /\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n</code></pre>\n\n<p>The only change vs <a href=\"https://stackoverflow.com/a/235064/662581\">Michael's</a> is to remove the <code>[NC]</code>, which produces the \"AH00665\" error:</p>\n\n<blockquote>\n <p>NoCase option for non-regex pattern '-f' is not supported and will be ignored</p>\n</blockquote>\n" }, { "answer_id": 38289947, "author": "Amit Verma", "author_id": 3160747, "author_profile": "https://Stackoverflow.com/users/3160747", "pm_score": 2, "selected": false, "text": "<pre><code>RewriteEngine on\n# if host value starts with \"www.\"\nRewriteCond %{HTTP_HOST} ^www\\.\n# redirect the request to \"non-www\"\nRewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]\n</code></pre>\n\n<p>If you want to remove <code>www</code> on both <code>http</code> and <code>https</code> , use the following :</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTP_HOST} ^www\\.\nRewriteCond %{HTTPS}s ^on(s)|offs\nRewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]\n</code></pre>\n\n<p>This redirects \nNon ssl</p>\n\n<ul>\n<li><a href=\"http://www.example.com\" rel=\"nofollow\">http://www.example.com</a></li>\n</ul>\n\n<p>to</p>\n\n<ul>\n<li><a href=\"http://example.com\" rel=\"nofollow\">http://example.com</a></li>\n</ul>\n\n<p>And\nSSL</p>\n\n<ul>\n<li><a href=\"https://www.example.com\" rel=\"nofollow\">https://www.example.com</a></li>\n</ul>\n\n<p>to</p>\n\n<ul>\n<li><a href=\"https://example.com\" rel=\"nofollow\">https://example.com</a></li>\n</ul>\n\n<p>on apache <code>2.4.*</code> you can accomplish this using a <code>Redirect</code> with <code>if</code> directive,</p>\n\n<pre><code>&lt;if \"%{HTTP_HOST} =='www.example.com'\"&gt;\nRedirect / http://example.com/\n&lt;/if&gt;\n</code></pre>\n" }, { "answer_id": 41662722, "author": "luky", "author_id": 4870273, "author_profile": "https://Stackoverflow.com/users/4870273", "pm_score": 1, "selected": false, "text": "<p>The selected answer and many other solutions here dropped the the part of the url after /, so basically it always redirected to main domain, at least for me.. So i am adding working sample respecting full path after slash..</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1%{REQUEST_URI} [L,R=301]\n</code></pre>\n" }, { "answer_id": 45453201, "author": "Universal Omega", "author_id": 7039493, "author_profile": "https://Stackoverflow.com/users/7039493", "pm_score": 2, "selected": false, "text": "<p>use: Javascript / jQuery</p>\n\n<pre><code>// similar behavior as an HTTP redirect\nwindow.location.replace(\"http://www.stackoverflow.com\");\n// similar behavior as clicking on a link\nwindow.location.href = \"http://stackoverflow.com\";\n</code></pre>\n\n<p>Or .htaccess:</p>\n\n<pre><code>RewriteEngine On\nRewriteBase /\nRewritecond %{HTTP_HOST} ^www\\.yoursite\\.com$ [NC]\nRewriteRule ^(.*)$ https://yoursite.com/$1 [R=301,L]\n</code></pre>\n\n<p>and The PHP method:</p>\n\n<pre><code>$protocol = (@$_SERVER[\"HTTPS\"] == \"on\") ? \"https://\" : \"http://\";\n\nif (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {\n header('Location: '.$protocol.'www.'.$_SERVER ['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);\n exit;\n}\n</code></pre>\n\n<p>Ajax</p>\n\n<pre><code>$.ajax({\n type: \"POST\",\n url: reqUrl,\n data: reqBody,\n dataType: \"json\",\n success: function(data, textStatus) {\n if (data.redirect) {\n // data.redirect contains the string URL to redirect to\n window.location.href = data.redirect;\n }\n else {\n // data.form contains the HTML for the replacement form\n $(\"#myform\").replaceWith(data.form);\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 55741915, "author": "Rohallah Hatami", "author_id": 6901246, "author_profile": "https://Stackoverflow.com/users/6901246", "pm_score": 2, "selected": false, "text": "<p>Using .htaccess to Redirect to www or non-www:</p>\n<p>Simply put the following lines of code into your main, root .htaccess file.\nIn both cases, just change out domain.com to your own hostname.</p>\n<p>Redirect to www</p>\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine on\n RewriteCond %{HTTP_HOST} ^domain\\.tld [NC]\n RewriteRule ^(.*)$ http://www.domain.tld/$1 [L,R=301]\n&lt;/IfModule&gt;\n</code></pre>\n<p>Redirect to non-www</p>\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine on\n RewriteCond %{HTTP_HOST} ^www\\.domain\\.tld [NC]\n RewriteRule ^(.*)$ http://domain.tld/$1 [L,R=301]\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 58458780, "author": "Bobík", "author_id": 1594000, "author_profile": "https://Stackoverflow.com/users/1594000", "pm_score": 1, "selected": false, "text": "<p>Alternative approach if .htaccess customization is not ideal option:</p>\n\n<p>I've created simple redirect server for public use. Just add A or CNAME record:</p>\n\n<pre><code>CNAME r.simpleredirect.net\nA 89.221.218.22\n</code></pre>\n\n<p>More info: <a href=\"https://simpleredirect.net\" rel=\"nofollow noreferrer\">https://simpleredirect.net</a></p>\n" }, { "answer_id": 59319072, "author": "Jeaf Gilbert", "author_id": 351564, "author_profile": "https://Stackoverflow.com/users/351564", "pm_score": 0, "selected": false, "text": "<p>Added if localhost, ignore redirection (for development purpose in local environment). If not localhost AND (not https OR it’s www), redirect to https and non-www.</p>\n\n<pre><code>RewriteEngine On\n\nRewriteBase /\nRewriteCond %{HTTP_HOST} !localhost [NC]\nRewriteCond %{HTTPS} off [OR]\nRewriteCond %{HTTP_HOST} ^www\\. [NC]\nRewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21473/" ]
I would like to redirect `www.example.com` to `example.com`. The following htaccess code makes this happen: ``` RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] ``` But, is there a way to do this in a generic fashion without hardcoding the domain name?
``` RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] ``` Same as [Michael's](https://stackoverflow.com/a/235064/662581) except this one works :P
234,742
<p>In <code>tcsh</code>, I have the following script working:</p> <pre><code>#!/bin/tcsh setenv X_ROOT /some/specified/path setenv XDB ${X_ROOT}/db setenv PATH ${X_ROOT}/bin:${PATH} xrun -d xdb1 -i $1 &gt; $2 </code></pre> <p>What is the equivalent to the <code>tcsh setenv</code> function in Bash? </p> <p>Is there a direct analog? The environment variables are for locating the executable.</p>
[ { "answer_id": 234753, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "<p>I think you're looking for <code>export</code> - though I could be wrong.. I've never played with tcsh before. Use the following syntax:</p>\n\n<pre><code>export VARIABLE=value\n</code></pre>\n" }, { "answer_id": 234756, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 8, "selected": true, "text": "<p><code>export VAR=value</code> will set VAR to value. Enclose it in single quotes if you want spaces, like <code>export VAR='my val'</code>. If you want the variable to be interpolated, use double quotes, like <code>export VAR=\"$MY_OTHER_VAR\"</code>.</p>\n" }, { "answer_id": 234828, "author": "iny", "author_id": 27067, "author_profile": "https://Stackoverflow.com/users/27067", "pm_score": 4, "selected": false, "text": "<p><code>VAR=value</code> sets VAR to value.</p>\n\n<p>After that <code>export VAR</code> will give it to child processes too.</p>\n\n<p><code>export VAR=value</code> is a shorthand doing both.</p>\n" }, { "answer_id": 235368, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 5, "selected": false, "text": "<p>The reason people often suggest writing</p>\n\n<pre><code>VAR=value\nexport VAR\n</code></pre>\n\n<p>instead of the shorter</p>\n\n<pre><code>export VAR=value\n</code></pre>\n\n<p>is that the longer form works in more different shells than the short form. If you know you're dealing with <code>bash</code>, either works fine, of course.</p>\n" }, { "answer_id": 25408907, "author": "Eric Leschinski", "author_id": 445131, "author_profile": "https://Stackoverflow.com/users/445131", "pm_score": 5, "selected": false, "text": "<h2>Set a local and environment variable using Bash on Linux</h2>\n\n<p><strong>Check for a local or environment variables for a variable called LOL in Bash:</strong></p>\n\n<pre><code>el@server /home/el $ set | grep LOL\nel@server /home/el $\nel@server /home/el $ env | grep LOL\nel@server /home/el $\n</code></pre>\n\n<p>Sanity check, no local or environment variable called LOL.</p>\n\n<p><strong>Set a local variable called LOL in local, but not environment. So set it:</strong></p>\n\n<pre><code>el@server /home/el $ LOL=\"so wow much code\"\nel@server /home/el $ set | grep LOL\nLOL='so wow much code'\nel@server /home/el $ env | grep LOL\nel@server /home/el $\n</code></pre>\n\n<p>Variable 'LOL' exists in local variables, but not environment variables. LOL will disappear if you restart the terminal, logout/login or run <code>exec bash</code>.</p>\n\n<p><strong>Set a local variable, and then clear out all local variables in Bash</strong></p>\n\n<pre><code>el@server /home/el $ LOL=\"so wow much code\"\nel@server /home/el $ set | grep LOL\nLOL='so wow much code'\nel@server /home/el $ exec bash\nel@server /home/el $ set | grep LOL\nel@server /home/el $\n</code></pre>\n\n<p><strong>You could also just unset the one variable:</strong></p>\n\n<pre><code>el@server /home/el $ LOL=\"so wow much code\"\nel@server /home/el $ set | grep LOL\nLOL='so wow much code'\nel@server /home/el $ unset LOL\nel@server /home/el $ set | grep LOL\nel@server /home/el $\n</code></pre>\n\n<p>Local variable LOL is gone.</p>\n\n<p><strong>Promote a local variable to an environment variable:</strong></p>\n\n<pre><code>el@server /home/el $ DOGE=\"such variable\"\nel@server /home/el $ export DOGE\nel@server /home/el $ set | grep DOGE\nDOGE='such variable'\nel@server /home/el $ env | grep DOGE\nDOGE=such variable\n</code></pre>\n\n<p>Note that exporting makes it show up as both a local variable and an environment variable.</p>\n\n<p>Exported variable DOGE above survives a Bash reset:</p>\n\n<pre><code>el@server /home/el $ exec bash\nel@server /home/el $ env | grep DOGE\nDOGE=such variable\nel@server /home/el $ set | grep DOGE\nDOGE='such variable'\n</code></pre>\n\n<p><strong>Unset all environment variables:</strong></p>\n\n<p>You have to pull out a can of Chuck Norris to reset all environment variables without a logout/login:</p>\n\n<pre><code>el@server /home/el $ export CAN=\"chuck norris\"\nel@server /home/el $ env | grep CAN\nCAN=chuck norris\nel@server /home/el $ set | grep CAN\nCAN='chuck norris'\nel@server /home/el $ env -i bash\nel@server /home/el $ set | grep CAN\nel@server /home/el $ env | grep CAN\n</code></pre>\n\n<p>You created an environment variable, and then reset the terminal to get rid of them.</p>\n\n<p><strong>Or you could set and unset an environment variable manually like this:</strong></p>\n\n<pre><code>el@server /home/el $ export FOO=\"bar\"\nel@server /home/el $ env | grep FOO\nFOO=bar\nel@server /home/el $ unset FOO\nel@server /home/el $ env | grep FOO\nel@server /home/el $\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
In `tcsh`, I have the following script working: ``` #!/bin/tcsh setenv X_ROOT /some/specified/path setenv XDB ${X_ROOT}/db setenv PATH ${X_ROOT}/bin:${PATH} xrun -d xdb1 -i $1 > $2 ``` What is the equivalent to the `tcsh setenv` function in Bash? Is there a direct analog? The environment variables are for locating the executable.
`export VAR=value` will set VAR to value. Enclose it in single quotes if you want spaces, like `export VAR='my val'`. If you want the variable to be interpolated, use double quotes, like `export VAR="$MY_OTHER_VAR"`.
234,776
<p>I was reading some 3rd party code and I found this:</p> <pre><code>x.Flags = x.Flags ^ Flags.Hidden; </code></pre> <p>What does it do?</p> <p>I've used '&amp;' and '|' for bitwise 'and' and 'or' with enums, but it's the first time I see the that symbol...</p>
[ { "answer_id": 234788, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 6, "selected": true, "text": "<p>^ is the bitwise XOR operator in C#. </p>\n\n<p>EDIT: a ^ b returns true if a is true and b is false or if a is false and b is true, but not both.</p>\n" }, { "answer_id": 234793, "author": "Ryan Duffield", "author_id": 2696, "author_profile": "https://Stackoverflow.com/users/2696", "pm_score": 2, "selected": false, "text": "<p>Taken from <a href=\"http://msdn.microsoft.com/en-us/library/zkacc7k1(VS.71).aspx\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<blockquote>\n <p>For integral types, ^ computes the\n bitwise exclusive-OR of its operands.\n For bool operands, ^ computes the\n logical exclusive-or of its operands;\n that is, the result is true if and\n only if <strong>an odd number</strong> of its operands is\n true.</p>\n</blockquote>\n" }, { "answer_id": 234795, "author": "PhilGriffin", "author_id": 29294, "author_profile": "https://Stackoverflow.com/users/29294", "pm_score": 2, "selected": false, "text": "<p>It's the exclusive OR (XOR) operator, this link has example usage</p>\n\n<p><a href=\"http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx</a> </p>\n" }, { "answer_id": 234802, "author": "Jeromy Irvine", "author_id": 8223, "author_profile": "https://Stackoverflow.com/users/8223", "pm_score": 4, "selected": false, "text": "<p>That would be the 'xor' operator. In your example code, it would toggle the Flags.Hidden either on or off, depending on the current value of x.Flags.</p>\n\n<p>The benefit of doing it this way is that it allows you to change the setting for Flags.Hidden without affecting any other flags that have been set.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
I was reading some 3rd party code and I found this: ``` x.Flags = x.Flags ^ Flags.Hidden; ``` What does it do? I've used '&' and '|' for bitwise 'and' and 'or' with enums, but it's the first time I see the that symbol...
^ is the bitwise XOR operator in C#. EDIT: a ^ b returns true if a is true and b is false or if a is false and b is true, but not both.
234,785
<p>The situation is as follows: I've got 2 models: 'Action' and 'User'. These models refer to the tables 'actions' and 'users', respectively.</p> <p>My action table contains a column <code>user_id</code>. At this moment, I need an overview of all actions, and the users to which they are assigned to. When i use <code>$action-&gt;fetchAll()</code>, I only have the user ID, so I want to be able to join the data from the user model, preferably without making a call to <code>findDependentRowset()</code>.</p> <p>I thought about creating custom <code>fetchAll()</code>, <code>fetchRow()</code> and <code>find()</code> methods in my model, but this would break default behaviour.</p> <p>What is the best way to solve this issue? Any help would be greatly appreciated.</p>
[ { "answer_id": 235267, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "<p>You could always make a view in your database that does the join for you.</p>\n\n<pre><code>CREATE OR REPLACE VIEW VwAction AS\nSELECT [columns]\n FROM action\n LEFT JOIN user\n ON user.id = action.user_id\n</code></pre>\n\n<p>Then just use</p>\n\n<pre><code>$vwAction-&gt;fetchAll();\n</code></pre>\n\n<p>Just remember that views in MySQL are read-only (assuming this is MySQL)</p>\n" }, { "answer_id": 237323, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "<p>I designed and implemented the table-relationships feature in Zend Framework.</p>\n\n<p>My first comment is that you wouldn't use <code>findDependentRowset()</code> anyway -- you'd use <code>findParentRow()</code> if the Action has a foreign key reference to User.</p>\n\n<pre><code>$actionTable = new Action();\n$actionRowset = $actionTable-&gt;fetchAll();\nforeach ($actionRowset as $actionRow) {\n $userRow = $actionRow-&gt;findParentRow('User');\n}\n</code></pre>\n\n<p><strong>Edit:</strong> In the loop, you now have an $actionRow and a $userRow object. You can write changes back to the database through either object by changing object fields and calling <code>save()</code> on the object.</p>\n\n<p>You can also use the Zend_Db_Table_Select class (which was implemented after I left the project) to retrieve a Rowset based on a join between Action and User.</p>\n\n<pre><code>$actionTable = new Action();\n$actionQuery = $actionTable-&gt;select()\n -&gt;setIntegrityCheck(false) // allows joins\n -&gt;from($actionTable)\n -&gt;join('user', 'user.id = action.user_id');\n$joinedRowset = $actionTable-&gt;fetchAll($actionQuery);\nforeach ($joinedRowset as $joinedRow) {\n print_r($joinedRow-&gt;toArray());\n}\n</code></pre>\n\n<p>Note that such a Rowset based on a join query is read-only. You cannot set field values in the Row objects and call <code>save()</code> to post changes back to the database.</p>\n\n<p><strong>Edit:</strong> There is no way to make an arbitrary joined result set writable. Consider a simple example based on the joined result set above:</p>\n\n<pre><code>action_id action_type user_id user_name\n 1 Buy 1 Bill\n 2 Sell 1 Bill\n 3 Buy 2 Aron\n 4 Sell 2 Aron\n</code></pre>\n\n<p>Next for the row with action_id=1, I change one of the fields that came from the User object:</p>\n\n<pre><code>$joinedRow-&gt;user_name = 'William';\n$joinedRow-&gt;save();\n</code></pre>\n\n<p>Questions: when I view the next row with action_id=2, should I see 'Bill' or 'William'? If 'William', does this mean that saving row 1 has to automatically update 'Bill' to 'William' in all other rows in this result set? Or does it mean that <code>save()</code> automatically re-runs the SQL query to get a refreshed result set from the database? What if the query is time-consuming? </p>\n\n<p>Also consider the object-oriented design. Each Row is a separate object. Is it appropriate that calling <code>save()</code> on one object has the side effect of changing values in a separate object (even if they are part of the same collection of objects)? That seems like a form of <a href=\"http://en.wikipedia.org/wiki/Coupling_(computer_science)\" rel=\"noreferrer\">Content Coupling</a> to me.</p>\n\n<p>The example above is a relatively simple query, but much more complex queries are also permitted. Zend_Db cannot analyze queries with the intention to tell writable results from read-only results. That's also why MySQL views are not updateable.</p>\n" }, { "answer_id": 1631052, "author": "dave", "author_id": 197378, "author_profile": "https://Stackoverflow.com/users/197378", "pm_score": 1, "selected": false, "text": "<p>isn't creating a view sql table a good solution to make joint ?\nand after a simple table class to access it</p>\n\n<p>I would think it's better if your logic is in sql than in php </p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11568/" ]
The situation is as follows: I've got 2 models: 'Action' and 'User'. These models refer to the tables 'actions' and 'users', respectively. My action table contains a column `user_id`. At this moment, I need an overview of all actions, and the users to which they are assigned to. When i use `$action->fetchAll()`, I only have the user ID, so I want to be able to join the data from the user model, preferably without making a call to `findDependentRowset()`. I thought about creating custom `fetchAll()`, `fetchRow()` and `find()` methods in my model, but this would break default behaviour. What is the best way to solve this issue? Any help would be greatly appreciated.
I designed and implemented the table-relationships feature in Zend Framework. My first comment is that you wouldn't use `findDependentRowset()` anyway -- you'd use `findParentRow()` if the Action has a foreign key reference to User. ``` $actionTable = new Action(); $actionRowset = $actionTable->fetchAll(); foreach ($actionRowset as $actionRow) { $userRow = $actionRow->findParentRow('User'); } ``` **Edit:** In the loop, you now have an $actionRow and a $userRow object. You can write changes back to the database through either object by changing object fields and calling `save()` on the object. You can also use the Zend\_Db\_Table\_Select class (which was implemented after I left the project) to retrieve a Rowset based on a join between Action and User. ``` $actionTable = new Action(); $actionQuery = $actionTable->select() ->setIntegrityCheck(false) // allows joins ->from($actionTable) ->join('user', 'user.id = action.user_id'); $joinedRowset = $actionTable->fetchAll($actionQuery); foreach ($joinedRowset as $joinedRow) { print_r($joinedRow->toArray()); } ``` Note that such a Rowset based on a join query is read-only. You cannot set field values in the Row objects and call `save()` to post changes back to the database. **Edit:** There is no way to make an arbitrary joined result set writable. Consider a simple example based on the joined result set above: ``` action_id action_type user_id user_name 1 Buy 1 Bill 2 Sell 1 Bill 3 Buy 2 Aron 4 Sell 2 Aron ``` Next for the row with action\_id=1, I change one of the fields that came from the User object: ``` $joinedRow->user_name = 'William'; $joinedRow->save(); ``` Questions: when I view the next row with action\_id=2, should I see 'Bill' or 'William'? If 'William', does this mean that saving row 1 has to automatically update 'Bill' to 'William' in all other rows in this result set? Or does it mean that `save()` automatically re-runs the SQL query to get a refreshed result set from the database? What if the query is time-consuming? Also consider the object-oriented design. Each Row is a separate object. Is it appropriate that calling `save()` on one object has the side effect of changing values in a separate object (even if they are part of the same collection of objects)? That seems like a form of [Content Coupling](http://en.wikipedia.org/wiki/Coupling_(computer_science)) to me. The example above is a relatively simple query, but much more complex queries are also permitted. Zend\_Db cannot analyze queries with the intention to tell writable results from read-only results. That's also why MySQL views are not updateable.
234,797
<p>I need to use sed to convert all occurences of <code>##XXX##</code> to <code>${XXX}</code>. X could be any alphabetic character or '_'. I know that I need to use something like:</p> <pre><code>'s/##/\${/g' </code></pre> <p>But of course that won't work properly, as it will convert <code>##FOO##</code> to <code>${FOO${</code></p>
[ { "answer_id": 234806, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 1, "selected": false, "text": "<p>Use this:</p>\n\n<pre><code>s/##\\([^#]*\\)##/${\\1}/\n</code></pre>\n\n<p>BTW, there is no need to escape $ in the right side of the \"s\" operator.</p>\n" }, { "answer_id": 234818, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<pre><code>sed 's/##\\([a-zA-Z_][a-zA-Z_][a-zA-Z_]\\)##/${\\1}/'\n</code></pre>\n\n<p>The <code>\\(...\\)</code> remembers...and is referenced as <code>\\1</code> in the expansion. Use single quotes to save your sanity.</p>\n\n<p>As noted in the comments below this, this can also be contracted to:</p>\n\n<pre><code>sed 's/##\\([a-zA-Z_]\\{3\\}\\)##/${\\1}/'\n</code></pre>\n\n<p>This answer assumes that the example wanted exactly three characters matched. There are multiple variations depending on what is in between the hash marks. The key part is remembering part of the matched string.</p>\n" }, { "answer_id": 234823, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 5, "selected": true, "text": "<p>Here's a shot at a better replacement regex:</p>\n\n<pre><code>'s/##\\([a-zA-Z_]\\+\\)##/${\\1}/g'\n</code></pre>\n\n<p>Or if you assume exactly three characters :</p>\n\n<pre><code>'s/##\\([a-zA-Z_]\\{3\\}\\)##/${\\1}/g'\n</code></pre>\n" }, { "answer_id": 234831, "author": "user24881", "author_id": 24881, "author_profile": "https://Stackoverflow.com/users/24881", "pm_score": 2, "selected": false, "text": "<ul>\n<li>Encapsulate the alpha and '_' within '\\(' and '\\)' and then in the right side reference that with '\\1'.\n<li>'+' to match one or more alpha and '_' (in case you see ####).</li>\n<li>Add the 'g' option to the end to replace all matches (which I'm guessing is what you want to do in this case).\n</ul>\n\n<pre>'s/##\\([a-zA-Z_]\\+\\)##/${\\1}/g'</pre>\n" }, { "answer_id": 655312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>echo '##XXX##' | sed &quot;s/^##\\([^#]*\\)/##$\\{\\1\\}/g&quot;\n</code></pre>\n" }, { "answer_id": 12617668, "author": "Sabarish", "author_id": 1700108, "author_profile": "https://Stackoverflow.com/users/1700108", "pm_score": -1, "selected": false, "text": "<pre class=\"lang-none prettyprint-override\"><code>sed 's/\\([^a-z]*[^A-Z]*[^0-9]*\\)/(&amp;)/pg\n</code></pre>\n" }, { "answer_id": 26356786, "author": "NeronLeVelu", "author_id": 2885763, "author_profile": "https://Stackoverflow.com/users/2885763", "pm_score": 1, "selected": false, "text": "<pre><code>echo \"##foo##\" | sed 's/##/${/;s//}/'\n</code></pre>\n\n<ul>\n<li><code>s</code> change only 1 occurence by default</li>\n<li><code>s//</code>take last search pattern used so second s take also <code>##</code> and only the second occurence still exist</li>\n</ul>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I need to use sed to convert all occurences of `##XXX##` to `${XXX}`. X could be any alphabetic character or '\_'. I know that I need to use something like: ``` 's/##/\${/g' ``` But of course that won't work properly, as it will convert `##FOO##` to `${FOO${`
Here's a shot at a better replacement regex: ``` 's/##\([a-zA-Z_]\+\)##/${\1}/g' ``` Or if you assume exactly three characters : ``` 's/##\([a-zA-Z_]\{3\}\)##/${\1}/g' ```
234,845
<p>I am looking for a way to change the password of a local user account (local Administrator) on a Windows (XP in this case) machine. I have read the <a href="http://www.codeproject.com/KB/threads/Reset-Administrator-Pass.aspx" rel="noreferrer">CodeProject article</a> about one way to do this, but this just doesn't seem 'clean'. </p> <p>I can see that this is <a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/oct04/hey1015.mspx" rel="noreferrer">possible to do with WMI</a>, so that might be the answer, but I can't figure out how to use the WinNT WMI namespace with ManagementObject. When I try the following code it throws an "Invalid Parameter" exception.</p> <pre><code>public static void ResetPassword(string computerName, string username, string newPassword){ ManagementObject managementObject = new ManagementObject("WinNT://" + computerName + "/" + username); // Throws Exception object[] newpasswordObj = {newPassword}; managementObject.InvokeMethod("SetPassword", newpasswordObj); } </code></pre> <p>Is there a better way to do this? (I'm using .NET 3.5)</p> <p><strong>Edit:</strong> Thanks Ely for pointing me in the right direction. Here is the code I ended up using:</p> <pre><code>public static void ResetPassword(string computerName, string username, string newPassword) { DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username)); directoryEntry.Invoke("SetPassword", newPassword); } </code></pre>
[ { "answer_id": 235085, "author": "Ely", "author_id": 30488, "author_profile": "https://Stackoverflow.com/users/30488", "pm_score": 3, "selected": true, "text": "<p>Try the <code>DirectoryEntry</code> class instead of <code>ManagementObject</code> class.</p>\n" }, { "answer_id": 238975, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>As Ely noted, you can use the System.DirectoryServices code to accomplish this per <a href=\"http://msdn\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<pre><code>String myADSPath = \"LDAP://onecity/CN=Users,\n DC=onecity,DC=corp,DC=fabrikam,DC=com\";\n\n// Create an Instance of DirectoryEntry.\nDirectoryEntry myDirectoryEntry = new DirectoryEntry(myADSPath);\nmyDirectoryEntry.Username = UserName;\nmyDirectoryEntry.Password = SecurelyStoredPassword;\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12367/" ]
I am looking for a way to change the password of a local user account (local Administrator) on a Windows (XP in this case) machine. I have read the [CodeProject article](http://www.codeproject.com/KB/threads/Reset-Administrator-Pass.aspx) about one way to do this, but this just doesn't seem 'clean'. I can see that this is [possible to do with WMI](http://www.microsoft.com/technet/scriptcenter/resources/qanda/oct04/hey1015.mspx), so that might be the answer, but I can't figure out how to use the WinNT WMI namespace with ManagementObject. When I try the following code it throws an "Invalid Parameter" exception. ``` public static void ResetPassword(string computerName, string username, string newPassword){ ManagementObject managementObject = new ManagementObject("WinNT://" + computerName + "/" + username); // Throws Exception object[] newpasswordObj = {newPassword}; managementObject.InvokeMethod("SetPassword", newpasswordObj); } ``` Is there a better way to do this? (I'm using .NET 3.5) **Edit:** Thanks Ely for pointing me in the right direction. Here is the code I ended up using: ``` public static void ResetPassword(string computerName, string username, string newPassword) { DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username)); directoryEntry.Invoke("SetPassword", newPassword); } ```
Try the `DirectoryEntry` class instead of `ManagementObject` class.
234,848
<p>I found in MYSQL and apparently other database engines that there is a "greatest" function that can be used like: greatest(1, 2, 3, 4), and it would return 4. I need this, but I am using IBM's DB2. Does anybody know of such an equivalent function, even if it only accepts 2 parameters?</p> <p>I found somewhere that MAX should do it, but it doesn't work... it only works on selecting the MAX of a column.</p> <p>If there is no such function, does anybody have an idea what a stored procedure to do this might look like? (I have no stored procedure experience, so I have no clue what DB2 would be capable of).</p>
[ { "answer_id": 234875, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 1, "selected": false, "text": "<p>Two options:</p>\n\n<ol>\n<li><p>What about sorting the column in descending and grabbing the top 1 row?</p></li>\n<li><p>According to my \"SQL Pocket Guide\", MAX(x) returns the greatest value in a set.</p></li>\n</ol>\n\n<p>UPDATE: Apparently #1 won't work if you are looking at columns.</p>\n" }, { "answer_id": 234898, "author": "Dave", "author_id": 21294, "author_profile": "https://Stackoverflow.com/users/21294", "pm_score": 3, "selected": false, "text": "<p>Why does MAX not work for you?</p>\n\n<p>select max(1,2,8,3,1,7) from sysibm.sysdummy1</p>\n\n<p>gives me</p>\n\n<pre><code> 1\n ---------------\n 8\n\n 1 record(s) selected.\n</code></pre>\n" }, { "answer_id": 247480, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>As Dave points out, MAX should work as it's overloaded as both a scalar and a column function (the scalar takes 2 or more arguments). This is the case in DB2 for LUW, DB2 for z/OS and DB2 for i5/OS. What exact version and platform of DB2 are you using, and what is the exact statement you are using? One of the requirements of the scalar version of MAX is that all the arguments are \"compatible\" - I suspect there may be a subtle type difference in one or more of the arguments you're passing to the function.</p>\n" }, { "answer_id": 403104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>On Linux V9.1, the \"select max (1,2,3) ...\" gives -</p>\n\n<p>SQL0440N No authorized routine named \"MAX\" of type \"FUNCTION\" having \ncompatible arguments was found. SQLSTATE=42884</p>\n\n<p>It is a scalar function requiring either a single value or a single column name. On z/os, it behaves differently.</p>\n\n<p>However, It does work as expected on Linux 9.5.</p>\n" }, { "answer_id": 632369, "author": "weiyin", "author_id": 14870, "author_profile": "https://Stackoverflow.com/users/14870", "pm_score": 1, "selected": false, "text": "<p>It sounds crazy, but no such function exists in DB2, at least not in version 9.1. If you want to select the greater of two columns, it would be best to use a case expression.</p>\n\n<p>You can also define your own max function. For example:</p>\n\n<pre><code>create function importgenius.max2(x double, y double)\nreturns double\nlanguage sql\ncontains sql\ndeterministic\nno external action\nbegin atomic\n if y is null or x &gt;= y then return x;\n else return y;\n end if;\nend\n</code></pre>\n\n<p>Defining the inputs and outputs as doubles lets you take advantage of type promotion, so this function will also work for integers. The \"deterministic\" and \"no external action\" statements help the database engine optimize use of the function.</p>\n\n<p>If you want another max function to work for character inputs, you'll have to give it another name.</p>\n" }, { "answer_id": 48660590, "author": "srinath", "author_id": 9326702, "author_profile": "https://Stackoverflow.com/users/9326702", "pm_score": 0, "selected": false, "text": "<p>Please check with following query:</p>\n\n<pre><code>select * from table1 a,\n(select appno as sub_appno,max(sno) as sub_maxsno from table1 group by appno) as tab2\nwhere a.appno =tab2.sub_appno and a.sno=tab2.sub_maxsno\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I found in MYSQL and apparently other database engines that there is a "greatest" function that can be used like: greatest(1, 2, 3, 4), and it would return 4. I need this, but I am using IBM's DB2. Does anybody know of such an equivalent function, even if it only accepts 2 parameters? I found somewhere that MAX should do it, but it doesn't work... it only works on selecting the MAX of a column. If there is no such function, does anybody have an idea what a stored procedure to do this might look like? (I have no stored procedure experience, so I have no clue what DB2 would be capable of).
Why does MAX not work for you? select max(1,2,8,3,1,7) from sysibm.sysdummy1 gives me ``` 1 --------------- 8 1 record(s) selected. ```
234,849
<p>I am using activemq to pass requests between different processes. In some cases, I have multiple, duplicate message (which are requests) in the queue. I would like to have only one. Is there a way to send a message in a way that it will replace an older message with similar attributes? If there isn't, is there a way to inspect the queue and check for a message with specific attributes (in this case I will not send the new message if an older one exists).</p> <p>Clarrification (based on Dave's answer): I am actually trying to make sure that there aren't any duplicate messages on the queue to reduce the amount of processing that is happening whenever the consumer gets the message. Hence I would like either to replace a message or not even put it on the queue.</p> <p>Thanks.</p>
[ { "answer_id": 234884, "author": "Dave", "author_id": 3095, "author_profile": "https://Stackoverflow.com/users/3095", "pm_score": 1, "selected": false, "text": "<p>You could browse the queue and use selectors to identify the message. However, unless you have a small amount of messages this won't scale very well. Instead, you message should just be a pointer to a database-record (or set of records). That way you can update the record and whoever gets the message will then access the latest version of the record.</p>\n" }, { "answer_id": 239318, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 2, "selected": false, "text": "<p>This sounds like an ideal use case for the <a href=\"http://activemq.apache.org/camel/idempotent-consumer.html\" rel=\"nofollow noreferrer\">Idempotent Consumer</a> which removes duplicates from a queue or topic. </p>\n\n<p>The following example shows how to do this with <a href=\"http://activemq.apache.org/camel/\" rel=\"nofollow noreferrer\">Apache Camel</a> which is the easiest way to implement any of the <a href=\"http://activemq.apache.org/camel/enterprise-integration-patterns.html\" rel=\"nofollow noreferrer\">Enterprise Integration Patterns</a>, particularly if you are using <a href=\"http://activemq.apache.org/\" rel=\"nofollow noreferrer\">ActiveMQ</a> which <a href=\"http://activemq.apache.org/enterprise-integration-patterns.html\" rel=\"nofollow noreferrer\">comes with Camel integrated</a> out of the box</p>\n\n<pre><code>from(\"activemq:queueA\").\n idempotentConsumer(memoryMessageIdRepository(200)).\n header(\"myHeader\").\n to(\"activemq:queueB\");\n</code></pre>\n\n<p>The only trick to this is making sure there's an easy way to calculate a unique ID expression on each message - such as pulling out an XPath from the document or using as in the above example some unique message header</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31289/" ]
I am using activemq to pass requests between different processes. In some cases, I have multiple, duplicate message (which are requests) in the queue. I would like to have only one. Is there a way to send a message in a way that it will replace an older message with similar attributes? If there isn't, is there a way to inspect the queue and check for a message with specific attributes (in this case I will not send the new message if an older one exists). Clarrification (based on Dave's answer): I am actually trying to make sure that there aren't any duplicate messages on the queue to reduce the amount of processing that is happening whenever the consumer gets the message. Hence I would like either to replace a message or not even put it on the queue. Thanks.
This sounds like an ideal use case for the [Idempotent Consumer](http://activemq.apache.org/camel/idempotent-consumer.html) which removes duplicates from a queue or topic. The following example shows how to do this with [Apache Camel](http://activemq.apache.org/camel/) which is the easiest way to implement any of the [Enterprise Integration Patterns](http://activemq.apache.org/camel/enterprise-integration-patterns.html), particularly if you are using [ActiveMQ](http://activemq.apache.org/) which [comes with Camel integrated](http://activemq.apache.org/enterprise-integration-patterns.html) out of the box ``` from("activemq:queueA"). idempotentConsumer(memoryMessageIdRepository(200)). header("myHeader"). to("activemq:queueB"); ``` The only trick to this is making sure there's an easy way to calculate a unique ID expression on each message - such as pulling out an XPath from the document or using as in the above example some unique message header
234,866
<p>I come from a .NET world and I'm new to writting C++. I'm just wondering what are the preferred naming conventions when it comes to naming local variables and struct members.</p> <p>For example, the legacy code that I've inheritted has alot of these:</p> <pre><code>struct MyStruct { TCHAR szMyChar[STRING_SIZE]; bool bMyBool; unsigned long ulMyLong; void* pMyPointer; MyObject** ppMyObjects; } </code></pre> <p>Coming from a C# background I was shocked to see the variables with hungarian notation (I couldn't stop laughing at the pp prefix the first time I saw it).</p> <p>I would much rather name my variables this way instead (although I'm not sure if capitalizing the first letter is a good convention. I've seen other ways (see links below)):</p> <pre><code>struct MyStruct { TCHAR MyChar[STRING_SIZE]; bool MyBool; unsigned long MyLong; void* MyPointer; MyObject** MyObjects; } </code></pre> <p>My question: Is this (the former way) still a preferred way to name variables in C++?</p> <p>References:</p> <p><a href="http://geosoft.no/development/cppstyle.html" rel="noreferrer">http://geosoft.no/development/cppstyle.html</a></p> <p><a href="http://www.syntext.com/books/syntext-cpp-conventions.htm" rel="noreferrer">http://www.syntext.com/books/syntext-cpp-conventions.htm</a></p> <p><a href="http://ootips.org/hungarian-notation.html" rel="noreferrer">http://ootips.org/hungarian-notation.html</a></p> <p>Thanks!</p>
[ { "answer_id": 234877, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 1, "selected": false, "text": "<p>Hungarian notation was common among users of the Win32 and MFC APIs. If your predecessors were using that, you can probably best continue using it (even though it sucks). The rest of the C++ world never had this brain-dead convention, so don't use it if you're using something other than those APIs.</p>\n" }, { "answer_id": 234879, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 7, "selected": true, "text": "<p>That kind of Hungarian Notation is fairly useless, and possibly worse than useless if you have to change the type of something. (<a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"noreferrer\">The <em>proper</em> kind of Hungarian Notation</a> is a different story.)</p>\n\n<p>I suggest you use whatever your group does. If you're the only person working on the program, name them whatever way makes the most sense to you.</p>\n" }, { "answer_id": 234881, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 1, "selected": false, "text": "<p>I think that you will still find that most shops that program in Visual C++ stick with hungarian notation or at least a watered down version of it. In our shop, half of our app is legacy C++ with a shiny new C# layer on top (with a managed C++ layer in the middle.) Our C++ code continues to use hungarian notation but our C# code uses notation like you presented. I think it is ugly, but it is consistent.</p>\n\n<p>I say, use whatever your team wants for your project. But if you are working on legacy code or joining a team, stick with the style that is present for consistency.</p>\n" }, { "answer_id": 234883, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "<p>The most important thing is to be consistent. If you're working with a legacy code base, name your variables and functions <em>consistently</em> with the naming convention of the legacy code. If you're writing new code that is only interfacing with old code, use your naming convention in the new code, but be consistent with yourself too.</p>\n" }, { "answer_id": 234915, "author": "Marcin", "author_id": 22724, "author_profile": "https://Stackoverflow.com/users/22724", "pm_score": 2, "selected": false, "text": "<p>I agree with the other answers here. Either continue using the style that you are given from the handed down for consistency's sake, or come up with a new convention that works for your team. It's important that the team is in agreement, as it's almost guaranteed that you will be changing the same files. Having said that, some things that I found very intuitive in the past:<br><br>\nClass / struct member variables should stand out - I usually prefix them all with m&#95;<br>\nGlobal variables should stand out - usuall prefix with g&#95;<br>\nVariables in general should start with lower case<br>\nFunction names in general should start with upper case<br>\nMacros and possibly enums should be all upper case<br>\nAll names should describe what the function/variable does, and should never describe its type or value.</p>\n" }, { "answer_id": 234942, "author": "xyz", "author_id": 82, "author_profile": "https://Stackoverflow.com/users/82", "pm_score": 3, "selected": false, "text": "<p>What's to dislike or mock about \"ppMyObjects\" in this example apart from it being somewhat ugly? I don't have strong opinions either way, but it does communicate useful information at a glance that \"MyObjects\" does not.</p>\n" }, { "answer_id": 235012, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 2, "selected": false, "text": "<p>I'm a hungarian notation person myself, because I find that it lends readability to the code, and I much prefer self-documenting code to comments and lookups.</p>\n\n<p>That said, I think you can make a case for sacrificing your preferred style and some additional maintainability for team unity. I don't buy the argument of consistency for the sake of uniform code readability, especially if your reducing readability for consistency... it just doesn't make sense. Getting along with the people you work with, though, might be worth a bit more confusion on types looking at variables.</p>\n" }, { "answer_id": 235013, "author": "DavidG", "author_id": 25893, "author_profile": "https://Stackoverflow.com/users/25893", "pm_score": 1, "selected": false, "text": "<p>Its all down to personal preference. I've worked for 2 companies both with similar schemes, where member vars are named as m_varName. I've never seen Hungarian notation in use at work, and really don't like it, but again down to preference. My general feel is that IDE's should take care of telling u what type it is, so as long as the name is descriptive enough of what it does ( m_color, m_shouldBeRenamed ), then thats ok. The other thing i do like is a difference between member variable, local var and constant naming, so its easy to see what is happening in a function and where the vars come from.\nMember: m_varName\nConst: c_varName\nlocal: varName</p>\n" }, { "answer_id": 235397, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 4, "selected": false, "text": "<p>No. \nThe \"wrong hungarian notation\" - especially the pp for double indirection - made some sense for early C compilers where you could write </p>\n\n<pre><code>int * i = 17;\nint j = ***i;\n</code></pre>\n\n<p>without even a warning from the compiler (and that might even be valid code on the right hardware...).</p>\n\n<p>The \"true hungarian notation\" (as linked by head Geek) is IMO still a valid option, but not necessarily preferred. A modern C++ application usually has dozens or hundreds of types, for which you won't find suitable prefixes. </p>\n\n<p>I still use it locally in a few cases where I have to mix e.g. integer and float variables that have very similar or even identical names in the problem domain, e.g.</p>\n\n<pre><code>float fXmin, fXmax, fXpeak; // x values of range and where y=max\nint iXmin, iXMax, iXpeak; // respective indices in x axis vector\n</code></pre>\n\n<hr>\n\n<p>However, when maintaining legacy code that does follow some conventions consistently (even if loosely), you should stick to the conventions used there - at least in the existing modules / compilation units to be maintained.</p>\n\n<p>My reasoning: The purpose of coding standards is to comply with the principle of least surprise. Using one style consistently is more important than which style you use. </p>\n" }, { "answer_id": 383747, "author": "Roger Nelson", "author_id": 14964, "author_profile": "https://Stackoverflow.com/users/14964", "pm_score": 0, "selected": false, "text": "<p>If you use CamelCase the convention is to Capitalize the first letter\nfor classes structs and non primitive type names, and lower case the first letter for data members.\nCapitalization of methods tends to be a mixed bag, my methods tend to be verbs and are already distingished by parens so I don't capitalize methods.</p>\n\n<p>Personally I don't like to read CamelCase code and prefer underscores lower case for\ndata and method identifiers, capitalizing types and reserving uppercase for acronyms\nand the rare case where I use a macro (warning this is a MACRO).</p>\n" }, { "answer_id": 10601138, "author": "bkausbk", "author_id": 575491, "author_profile": "https://Stackoverflow.com/users/575491", "pm_score": 1, "selected": false, "text": "<p>I also prefer CamelCase, indeed mostly I've seen people using CamelCase in C++. Personaly I don't use any prefixes expect for private/protected members and interfaces:</p>\n\n<pre><code>class MyClass : public IMyInterface {\npublic:\n unsigned int PublicMember;\n MyClass() : PublicMember(1), _PrivateMember(0), _ProtectedMember(2) {}\n unsigned int PrivateMember() {\n return _PrivateMember * 1234; // some senseless calculation here\n }\nprotected:\n unsigned int _ProtectedMember;\nprivate:\n unsigned int _PrivateMember;\n};\n// ...\nMyClass My;\nMy.PublicMember = 12345678;\n</code></pre>\n\n<p><strong>Why I decided to omit prefixes for public members:</strong>\nBecause public members could be accessed directly like in structs and not clash with private names. Instead using underscores I've also seen people using first lower case letter for members.</p>\n\n<pre><code>struct IMyInterface {\n virtual void MyVirtualMethod() = 0;\n};\n</code></pre>\n\n<p>Interfaces contains per definition only pure virtual methods that needs to be implemented later. However in most situation I prefer abstract classes, but this is another story.</p>\n\n<pre><code>struct IMyInterfaceAsAbstract abstract {\n virtual void MyVirtualMethod() = 0;\n virtual void MyImplementedMethod() {}\n unsigned int EvenAnPublicMember;\n};\n</code></pre>\n\n<p>See <a href=\"http://www.codingstandard.com/HICPPCM/\" rel=\"nofollow\">High Integrity C++ Coding Standard Manual</a> for some more inspiration.</p>\n" }, { "answer_id": 21226726, "author": "Tho", "author_id": 875775, "author_profile": "https://Stackoverflow.com/users/875775", "pm_score": 2, "selected": false, "text": "<p>My team follows this <a href=\"https://google.github.io/styleguide/cppguide.html#Variable_Names\" rel=\"nofollow noreferrer\">Google C++ code convention</a>:</p>\n\n<p>This is a sample of variable name:</p>\n\n<pre><code>string table_name; // OK - uses underscore.\nstring tablename; // OK - all lowercase.\n\nstring tableName; // Bad - mixed case.\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18170/" ]
I come from a .NET world and I'm new to writting C++. I'm just wondering what are the preferred naming conventions when it comes to naming local variables and struct members. For example, the legacy code that I've inheritted has alot of these: ``` struct MyStruct { TCHAR szMyChar[STRING_SIZE]; bool bMyBool; unsigned long ulMyLong; void* pMyPointer; MyObject** ppMyObjects; } ``` Coming from a C# background I was shocked to see the variables with hungarian notation (I couldn't stop laughing at the pp prefix the first time I saw it). I would much rather name my variables this way instead (although I'm not sure if capitalizing the first letter is a good convention. I've seen other ways (see links below)): ``` struct MyStruct { TCHAR MyChar[STRING_SIZE]; bool MyBool; unsigned long MyLong; void* MyPointer; MyObject** MyObjects; } ``` My question: Is this (the former way) still a preferred way to name variables in C++? References: <http://geosoft.no/development/cppstyle.html> <http://www.syntext.com/books/syntext-cpp-conventions.htm> <http://ootips.org/hungarian-notation.html> Thanks!
That kind of Hungarian Notation is fairly useless, and possibly worse than useless if you have to change the type of something. ([The *proper* kind of Hungarian Notation](http://www.joelonsoftware.com/articles/Wrong.html) is a different story.) I suggest you use whatever your group does. If you're the only person working on the program, name them whatever way makes the most sense to you.
234,930
<p>Here's a quicky question. Which method name makes the most sense for an Objective-C Cocoa application?</p> <pre><code>-(void) doSomethingWithAnimation:(BOOL)animated </code></pre> <p>or:</p> <pre><code>-(void) doSomething:(BOOL)animated </code></pre> <p>or even:</p> <pre><code>-(void) doSomethingAnimated:(BOOL)animated </code></pre>
[ { "answer_id": 234954, "author": "Noah Witherspoon", "author_id": 30618, "author_profile": "https://Stackoverflow.com/users/30618", "pm_score": 2, "selected": false, "text": "<p>-(void)doSomethingAnimated:(BOOL)animated seems most consistent with Apple's naming style. For reference, check the iPhone UIKit docs - UINavigationController's -popToRootViewControllerAnimated: method, for instance.</p>\n" }, { "answer_id": 235039, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 4, "selected": true, "text": "<p>I think the Cocoa convention would give your examples the following semmantics (ignoring the BOOL type for the argument, obviously):</p>\n\n<pre><code>-(void) doSomethingWithAnimation:(BOOL)animated\n</code></pre>\n\n<p>would actually expect an Animation as the parameter (i.e. something that represents the animation.</p>\n\n<pre><code>-(void) doSomething:(BOOL)animated\n</code></pre>\n\n<p>would expect the Something to do.</p>\n\n<pre><code>-(void) doSomethingAnimated:(BOOL)animated\n</code></pre>\n\n<p>would, as Noah answered, do something with optional animation.</p>\n" }, { "answer_id": 235467, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 0, "selected": false, "text": "<p>Here's another option to consider: make two methods, <code>-doSomething</code> and <code>-doSomethingWithAnimation</code>.</p>\n\n<p>Then, if you want, you can have them both tail-call a third, private method, and give that method any name you want. :)</p>\n" }, { "answer_id": 2915164, "author": "Iggy", "author_id": 216354, "author_profile": "https://Stackoverflow.com/users/216354", "pm_score": 0, "selected": false, "text": "<p>write your comment clearly and tersely for example :\n//do Something with the Animation</p>\n\n<p>Then write your method name based on this comment, like below\ndoSomethingwithAnimation:(BOOL)animated</p>\n\n<p>Objective-C and Cocoa are designed to read well, so if your method cannot be a clear narrative of your code, it might not be well named.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17188/" ]
Here's a quicky question. Which method name makes the most sense for an Objective-C Cocoa application? ``` -(void) doSomethingWithAnimation:(BOOL)animated ``` or: ``` -(void) doSomething:(BOOL)animated ``` or even: ``` -(void) doSomethingAnimated:(BOOL)animated ```
I think the Cocoa convention would give your examples the following semmantics (ignoring the BOOL type for the argument, obviously): ``` -(void) doSomethingWithAnimation:(BOOL)animated ``` would actually expect an Animation as the parameter (i.e. something that represents the animation. ``` -(void) doSomething:(BOOL)animated ``` would expect the Something to do. ``` -(void) doSomethingAnimated:(BOOL)animated ``` would, as Noah answered, do something with optional animation.
234,935
<p>I'm having a problem dynamically adding columns to a GridView. I need to change the layout -- i.e. the included columns -- based on the value in a DropDownList. When the user changes the selection in this list, I need to remove all but the first column and dynamically add additional columns based on the selection.</p> <p>I have only one column defined in my markup -- column 0, a template column, in which I declare a Select link and another application specific LinkButton. That column needs to always be there. When the ListBoxSelection is made, I remove all but the first column and then re-add the desired columns (in this sample, I've simplified it to always add a "Title" column). Here is a portion of the code:</p> <pre><code>RemoveVariableColumnsFromGrid(); BoundField b = new BoundField(); b.DataField = "Title"; this.gvPrimaryListView.Columns.Add(b); this.gvPrimaryListView.DataBind(); private void RemoveVariableColumnsFromGrid() { int ColCount = this.gvPrimaryListView.Columns.Count; //Leave column 0 -- our select and view template column while (ColCount &gt; 1) { this.gvPrimaryListView.Columns.RemoveAt(ColCount - 1); --ColCount; } } </code></pre> <p>The first time this code runs through, I see both the static column and the dynamically added "Title" column. However, the next time a selection is made, the first column is generated empty (nothing in it). I see the title column, and I see the first column to its left -- but there's nothing generated within it. In the debugger, I can see that gvPrimaryListView does indeed still have two columns and the first one (index 0) is indeed a template column. In fact, the column even retains it's width which is set as 165px in the markup below (for debugging purposes).</p> <p>Any ideas?</p> <pre><code>&lt;asp:GridView ID="gvPrimaryListView" runat="server" Width="100%" AutoGenerateColumns="false" DataKeyNames="Document_ID" EnableViewState="true" DataSourceID="odsPrimaryDataSource" AllowPaging="true" AllowSorting="true" PageSize="10" OnPageIndexChanging="activeListView_PageIndexChanging" AutoGenerateSelectButton="False" OnSelectedIndexChanged="activeListView_SelectedIndexChanged" Visible="true" OnRowDataBound="CtlDocList_RowDataBound" Font-Size="8pt" Font-Names="Helvetica"&gt; &lt;Columns&gt; &lt;asp:TemplateField ShowHeader="false"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton EnableTheming="false" ID="CtlSelectDocRowBtn" runat="server" Text="Select" CommandName="Select" CssClass="gridbutton" OnClick="RowSelectBtn_Click" /&gt; &lt;asp:ImageButton EnableTheming="false" ID="DocViewBtn" runat="server" ImageUrl="../../images/ViewDoc3.png" CssClass="gridbutton" CommandName="Select" OnClick="DocViewBtn_Click" /&gt; &lt;/ItemTemplate&gt; &lt;ItemStyle Width="165px" /&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;EmptyDataTemplate&gt; &lt;asp:Label ID="Label6" runat="server" Text="No rows found." SkinID="LabelHeader"&gt;&lt;/asp:Label&gt; &lt;/EmptyDataTemplate&gt; &lt;/asp:GridView&gt; </code></pre> <hr> <p>Just some additional information.</p> <p>It has nothing to do with the fact that it is the first column but everything to do with the fact that it is a TemplateField. If I put a normal column to the left (in the markup) and shift the TemplateField column to the right, the first column renders fine, and the (now second) TemplateField column disappears.</p> <p>Another strange thing -- the problem doesn't happen the first postback -- OR THE SECOND -- but it starts on the third postback and then continues for subsequent postbacks. I'm stumped.</p>
[ { "answer_id": 235268, "author": "Ken Pespisa", "author_id": 30812, "author_profile": "https://Stackoverflow.com/users/30812", "pm_score": 0, "selected": false, "text": "<p>I found this little nugget in the documentation, under the DataControlFieldCollection Class. </p>\n\n<p><em>If you are using the GridView or DetailsView control, the DataControlField objects that are automatically created (for example, when the AutoGenerateColumns property is true) are not stored in the publicly accessible fields collection. You can only access and manipulate DataControlField objects that are not automatically generated.</em></p>\n\n<p>I guess the answer is to do all of your column manipulation in code, and then your approach should work fine.</p>\n" }, { "answer_id": 247235, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 0, "selected": false, "text": "<p>Instead of dynamically adding columns, could you define them at the outset and hide/show them as needed (either with Visible=\"false\" or setting the CssClass of the control/header/footer to a class with \"display: none;\")? I use this method in some of my code, including template columns, with no issues.</p>\n" }, { "answer_id": 250708, "author": "Ken Pespisa", "author_id": 30812, "author_profile": "https://Stackoverflow.com/users/30812", "pm_score": 0, "selected": false, "text": "<p>Sorry, Decker. I missed a few key points obviously.. :)</p>\n\n<p>If this is still a problem for you, I wonder if it makes a difference what you have in your item template? If you just put some text in there, then refresh the page a few times, does the text appear on the first load, then not on the second? </p>\n\n<p>Also, when the problem arises is there any html markup at all in the cells or are they completely empty?</p>\n" }, { "answer_id": 250791, "author": "DiningPhilanderer", "author_id": 30934, "author_profile": "https://Stackoverflow.com/users/30934", "pm_score": 3, "selected": false, "text": "<p>I recently conquered silmilar issues with dynamic columns in gridviews, perhaps this will help. </p>\n\n<p>First turn the viewstate off<br>\nSecond add the columns programatically in a function fired in the oninit event<br>\nLastly I used the following helper class to cause the checkboxes to instantiate when the RowDataBound event kicked off. Yes some of it is hard coded.</p>\n\n<p>Heck here is all the code. Have at it :) Warrenty as is, blah blah blah...</p>\n\n<p>Finally since I am just getting my feet wet DotNet any tips would be appreciated [IE don't rip me too much :) ]. And yes 'borrowed' the initial code from the web somewhere, sorry I cant remember off the top of my head :(</p>\n\n<p>-- Fire this off in protected override void OnInit</p>\n\n<pre><code> private void GridViewProject_AddColumns()\n {\n DataSet dsDataSet = new DataSet();\n TemplateField templateField = null;\n\n try\n {\n StoredProcedure sp = new StoredProcedure(\"ExpenseReportItemType_GetList\", \"INTRANETWEBDB\", Context.User.Identity.Name);\n dsDataSet = sp.GetDataSet();\n\n if (sp.RC != 0 &amp;&amp; sp.RC != 3000)\n {\n labelMessage.Text = sp.ErrorMessage;\n }\n\n int iIndex = 0;\n int iCount = dsDataSet.Tables[0].Rows.Count;\n string strCategoryID = \"\";\n string strCategoryName = \"\";\n iStaticColumnCount = GridViewProject.Columns.Count;\n\n // Insert all columns immediatly to the left of the LAST column\n while (iIndex &lt; iCount)\n {\n strCategoryName = dsDataSet.Tables[0].Rows[iIndex][\"CategoryName\"].ToString();\n strCategoryID = dsDataSet.Tables[0].Rows[iIndex][\"CategoryID\"].ToString();\n\n templateField = new TemplateField();\n templateField.HeaderTemplate = new GridViewTemplateExternal(DataControlRowType.Header, strCategoryName, strCategoryID);\n templateField.ItemTemplate = new GridViewTemplateExternal(DataControlRowType.DataRow, strCategoryName, strCategoryID);\n templateField.FooterTemplate = new GridViewTemplateExternal(DataControlRowType.Footer, strCategoryName, strCategoryID);\n\n // Have to decriment iStaticColumnCount to insert dynamic columns BEFORE the edit row\n GridViewProject.Columns.Insert((iIndex + (iStaticColumnCount-1)), templateField);\n iIndex++;\n }\n iFinalColumnCount = GridViewProject.Columns.Count;\n iERPEditColumnIndex = (iFinalColumnCount - 1); // iIndex is zero based, Count is not\n }\n catch (Exception exception)\n {\n labelMessage.Text = exception.Message;\n }\n }\n</code></pre>\n\n<p>-- Helper Class</p>\n\n<pre><code>public class GridViewTemplateExternal : System.Web.UI.ITemplate\n{\n #region Fields\n public DataControlRowType DataRowType;\n private string strCategoryID;\n private string strColumnName;\n #endregion\n\n #region Constructor\n public GridViewTemplateExternal(DataControlRowType type, string ColumnName, string CategoryID)\n {\n DataRowType = type; // Header, DataRow,\n strColumnName = ColumnName; // Header name\n strCategoryID = CategoryID;\n }\n #endregion\n\n #region Methods\n public void InstantiateIn(System.Web.UI.Control container)\n {\n switch (DataRowType)\n {\n case DataControlRowType.Header:\n // build the header for this column\n Label labelHeader = new Label();\n labelHeader.Text = \"&lt;b&gt;\" + strColumnName + \"&lt;/b&gt;\";\n // All CheckBoxes \"Look Up\" to the header row for this information\n labelHeader.Attributes[\"ERICategoryID\"] = strCategoryID;\n labelHeader.Style[\"writing-mode\"] = \"tb-rl\";\n labelHeader.Style[\"filter\"] = \"flipv fliph\";\n container.Controls.Add(labelHeader);\n break;\n case DataControlRowType.DataRow:\n CheckBox checkboxAllowedRow = new CheckBox();\n checkboxAllowedRow.Enabled = false;\n checkboxAllowedRow.DataBinding += new EventHandler(this.CheckBox_DataBinding);\n container.Controls.Add(checkboxAllowedRow);\n break;\n case DataControlRowType.Footer:\n // No data handling for the footer addition row\n CheckBox checkboxAllowedFooter = new CheckBox();\n container.Controls.Add(checkboxAllowedFooter);\n break;\n default:\n break;\n }\n }\n public void CheckBox_DataBinding(Object sender, EventArgs e)\n {\n CheckBox checkboxAllowed = (CheckBox)sender;// get the control that raised this event\n GridViewRow row = (GridViewRow)checkboxAllowed.NamingContainer;// get the containing row\n string RawValue = DataBinder.Eval(row.DataItem, strColumnName).ToString();\n if (RawValue.ToUpper() == \"TRUE\")\n {\n checkboxAllowed.Checked = true;\n }\n else\n {\n checkboxAllowed.Checked = false;\n }\n }\n #endregion\n}\n</code></pre>\n" }, { "answer_id": 250821, "author": "Marcus King", "author_id": 19840, "author_profile": "https://Stackoverflow.com/users/19840", "pm_score": 1, "selected": false, "text": "<p>diningphilanderer.myopenid.com has a similar approach to what I would recommend.</p>\n\n<p>The problem is that you have to rebind the grid each time a postback occurs and consequently you have to rebuild the columns. I like to have a method called BindGrid() that first clears the Columns GridView1.Columns.Clear(); then adds them programatically, then sets the datasource and calls databind. Make sure you have viewstate disabled for the grid and you have autogeneratecolumns = false;</p>\n" }, { "answer_id": 357194, "author": "Gyuri", "author_id": 45097, "author_profile": "https://Stackoverflow.com/users/45097", "pm_score": 1, "selected": false, "text": "<p>I found this earlier today: <a href=\"http://connect.microsoft.com/VisualStudio/feedback/details/104994/templatefield-in-a-gridview-doesnt-have-its-viewstate-restored-when-boundfields-are-inserted\" rel=\"nofollow noreferrer\">TemplateField in a GridView doesn't have its ViewState restored when BoundFields are inserted</a>.</p>\n\n<p>Looks like a bug that Microsoft doesn't plan on fixing, so you'll have to try one of the solutions above. I'm having the same problem -- I have some DataBoundFields and some TemplateFields, and after a postback, the TemplateField based columns lose their controls and data.</p>\n" }, { "answer_id": 6319816, "author": "Sheo Narayan", "author_id": 790348, "author_profile": "https://Stackoverflow.com/users/790348", "pm_score": 1, "selected": false, "text": "<p>I have written a short article on the similar topic that deal with dynamically populating GridView column based on the columns selected by the user in the CheckBoxList control. Hope this will help to those looking for simple demonstration <a href=\"http://www.dotnetfunda.com/articles/article1400-how-to-generate-gridview-columns-dynamically-based-on-user-selection-.aspx\" rel=\"nofollow\">How to generate GridView columns dynamically based on user selection?</a>.</p>\n" }, { "answer_id": 9005642, "author": "helper", "author_id": 1169568, "author_profile": "https://Stackoverflow.com/users/1169568", "pm_score": 1, "selected": false, "text": "<pre><code> void Page_PreRenderComplete(object sender, EventArgs e)\n {\n // TemplateField reorder bug: if there is a TemplateField based column (or derived therefrom), GridView may blank out\n // the column (plus possibly others) during any postback, if the user has moved it from its original markup position.\n // This is probably a viewstate bug, as it happens only if a TemplateField based column has been moved. The workaround is\n // to force a databind before each response. See https://connect.microsoft.com/VisualStudio/feedback/details/104994/templatefield-in-a-gridview-doesnt-have-its-viewstate-restored-when-boundfields-are-inserted\n //\n // This problem is also happening for grid views inside a TabPanel, even if the TemplateField based columns have not\n // been moved. Also do a databind in that case.\n //\n // We also force a databind right after the user has submitted the column chooser dialog.\n // (This is because the user could have moved TemplateField based column(s) but ColChooserHasMovedTemplateFields()\n // returns false -- ie when the user has moved all TemplateField based columns back to their original positions.\n if ((!_DataBindingDone &amp;&amp; (ColChooserHasMovedTemplateFields() || _InTabPanel)) || _ColChooserPanelSubmitted || _ColChooserPanelCancelled)\n DataBind();\n\n // There is a problem with the GridView in case of custom paging (which is true here) that if we are on the last page,\n // and we delete all row(s) of that page, GridView is not aware of the deletion during the subsequent data binding,\n // will ask the ODS for the last page of data, and will display a blank. By PreRenderComplete, it will somehow have\n // realized that its PageIndex, PageCount, etc. are too big and updated them properly, but this is too late\n // as the data binding has already occurred with oudated page variables. So, if we were on the last page just before\n // the last data binding (_LastPageIndex == _LastPageCount - 1) and PageIndex was decremented after the data binding,\n // we know this scenario has happened and we redo the data binding. See http://scottonwriting.net/sowblog/archive/2006/05/30/163173.aspx\n // for a discussion of the problem when the GridView uses the ODS to delete data. The discussion also applies when we\n // delete data directly through ClassBuilder objects.\n if (_LastPageIndex == _LastPageCount - 1 &amp;&amp; PageIndex &lt; _LastPageIndex)\n DataBind();\n\n if (EnableColChooser)\n {\n if (!_IsColChooserApplied)\n ApplyColChooser(null, false, false);\n else\n {\n // The purpose of calling ApplyColChooser() here is to order the column headers properly. The GridView\n // at this point will have reverted the column headers to their original order regardless of ViewState,\n // so we need to apply our own ordering. (This is not true of data cells, so we don't have to apply\n // ordering to them, as reflected by the parameters of the call.)\n\n // If we have already processed column reordering upon the column chooser panel being submitted,\n // don't repeat the operation.\n if (!_ColChooserPanelSubmitted)\n ApplyColChooser(null, false, true);\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 14642293, "author": "Harry Sarshogh", "author_id": 2031820, "author_profile": "https://Stackoverflow.com/users/2031820", "pm_score": 2, "selected": false, "text": "<p>best solution for add dynamic column to grid view (ASP) placed on code project by below address : \nplease check it out :\n<a href=\"http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view\" rel=\"nofollow\">http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view</a></p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7961/" ]
I'm having a problem dynamically adding columns to a GridView. I need to change the layout -- i.e. the included columns -- based on the value in a DropDownList. When the user changes the selection in this list, I need to remove all but the first column and dynamically add additional columns based on the selection. I have only one column defined in my markup -- column 0, a template column, in which I declare a Select link and another application specific LinkButton. That column needs to always be there. When the ListBoxSelection is made, I remove all but the first column and then re-add the desired columns (in this sample, I've simplified it to always add a "Title" column). Here is a portion of the code: ``` RemoveVariableColumnsFromGrid(); BoundField b = new BoundField(); b.DataField = "Title"; this.gvPrimaryListView.Columns.Add(b); this.gvPrimaryListView.DataBind(); private void RemoveVariableColumnsFromGrid() { int ColCount = this.gvPrimaryListView.Columns.Count; //Leave column 0 -- our select and view template column while (ColCount > 1) { this.gvPrimaryListView.Columns.RemoveAt(ColCount - 1); --ColCount; } } ``` The first time this code runs through, I see both the static column and the dynamically added "Title" column. However, the next time a selection is made, the first column is generated empty (nothing in it). I see the title column, and I see the first column to its left -- but there's nothing generated within it. In the debugger, I can see that gvPrimaryListView does indeed still have two columns and the first one (index 0) is indeed a template column. In fact, the column even retains it's width which is set as 165px in the markup below (for debugging purposes). Any ideas? ``` <asp:GridView ID="gvPrimaryListView" runat="server" Width="100%" AutoGenerateColumns="false" DataKeyNames="Document_ID" EnableViewState="true" DataSourceID="odsPrimaryDataSource" AllowPaging="true" AllowSorting="true" PageSize="10" OnPageIndexChanging="activeListView_PageIndexChanging" AutoGenerateSelectButton="False" OnSelectedIndexChanged="activeListView_SelectedIndexChanged" Visible="true" OnRowDataBound="CtlDocList_RowDataBound" Font-Size="8pt" Font-Names="Helvetica"> <Columns> <asp:TemplateField ShowHeader="false"> <ItemTemplate> <asp:LinkButton EnableTheming="false" ID="CtlSelectDocRowBtn" runat="server" Text="Select" CommandName="Select" CssClass="gridbutton" OnClick="RowSelectBtn_Click" /> <asp:ImageButton EnableTheming="false" ID="DocViewBtn" runat="server" ImageUrl="../../images/ViewDoc3.png" CssClass="gridbutton" CommandName="Select" OnClick="DocViewBtn_Click" /> </ItemTemplate> <ItemStyle Width="165px" /> </asp:TemplateField> </Columns> <EmptyDataTemplate> <asp:Label ID="Label6" runat="server" Text="No rows found." SkinID="LabelHeader"></asp:Label> </EmptyDataTemplate> </asp:GridView> ``` --- Just some additional information. It has nothing to do with the fact that it is the first column but everything to do with the fact that it is a TemplateField. If I put a normal column to the left (in the markup) and shift the TemplateField column to the right, the first column renders fine, and the (now second) TemplateField column disappears. Another strange thing -- the problem doesn't happen the first postback -- OR THE SECOND -- but it starts on the third postback and then continues for subsequent postbacks. I'm stumped.
I recently conquered silmilar issues with dynamic columns in gridviews, perhaps this will help. First turn the viewstate off Second add the columns programatically in a function fired in the oninit event Lastly I used the following helper class to cause the checkboxes to instantiate when the RowDataBound event kicked off. Yes some of it is hard coded. Heck here is all the code. Have at it :) Warrenty as is, blah blah blah... Finally since I am just getting my feet wet DotNet any tips would be appreciated [IE don't rip me too much :) ]. And yes 'borrowed' the initial code from the web somewhere, sorry I cant remember off the top of my head :( -- Fire this off in protected override void OnInit ``` private void GridViewProject_AddColumns() { DataSet dsDataSet = new DataSet(); TemplateField templateField = null; try { StoredProcedure sp = new StoredProcedure("ExpenseReportItemType_GetList", "INTRANETWEBDB", Context.User.Identity.Name); dsDataSet = sp.GetDataSet(); if (sp.RC != 0 && sp.RC != 3000) { labelMessage.Text = sp.ErrorMessage; } int iIndex = 0; int iCount = dsDataSet.Tables[0].Rows.Count; string strCategoryID = ""; string strCategoryName = ""; iStaticColumnCount = GridViewProject.Columns.Count; // Insert all columns immediatly to the left of the LAST column while (iIndex < iCount) { strCategoryName = dsDataSet.Tables[0].Rows[iIndex]["CategoryName"].ToString(); strCategoryID = dsDataSet.Tables[0].Rows[iIndex]["CategoryID"].ToString(); templateField = new TemplateField(); templateField.HeaderTemplate = new GridViewTemplateExternal(DataControlRowType.Header, strCategoryName, strCategoryID); templateField.ItemTemplate = new GridViewTemplateExternal(DataControlRowType.DataRow, strCategoryName, strCategoryID); templateField.FooterTemplate = new GridViewTemplateExternal(DataControlRowType.Footer, strCategoryName, strCategoryID); // Have to decriment iStaticColumnCount to insert dynamic columns BEFORE the edit row GridViewProject.Columns.Insert((iIndex + (iStaticColumnCount-1)), templateField); iIndex++; } iFinalColumnCount = GridViewProject.Columns.Count; iERPEditColumnIndex = (iFinalColumnCount - 1); // iIndex is zero based, Count is not } catch (Exception exception) { labelMessage.Text = exception.Message; } } ``` -- Helper Class ``` public class GridViewTemplateExternal : System.Web.UI.ITemplate { #region Fields public DataControlRowType DataRowType; private string strCategoryID; private string strColumnName; #endregion #region Constructor public GridViewTemplateExternal(DataControlRowType type, string ColumnName, string CategoryID) { DataRowType = type; // Header, DataRow, strColumnName = ColumnName; // Header name strCategoryID = CategoryID; } #endregion #region Methods public void InstantiateIn(System.Web.UI.Control container) { switch (DataRowType) { case DataControlRowType.Header: // build the header for this column Label labelHeader = new Label(); labelHeader.Text = "<b>" + strColumnName + "</b>"; // All CheckBoxes "Look Up" to the header row for this information labelHeader.Attributes["ERICategoryID"] = strCategoryID; labelHeader.Style["writing-mode"] = "tb-rl"; labelHeader.Style["filter"] = "flipv fliph"; container.Controls.Add(labelHeader); break; case DataControlRowType.DataRow: CheckBox checkboxAllowedRow = new CheckBox(); checkboxAllowedRow.Enabled = false; checkboxAllowedRow.DataBinding += new EventHandler(this.CheckBox_DataBinding); container.Controls.Add(checkboxAllowedRow); break; case DataControlRowType.Footer: // No data handling for the footer addition row CheckBox checkboxAllowedFooter = new CheckBox(); container.Controls.Add(checkboxAllowedFooter); break; default: break; } } public void CheckBox_DataBinding(Object sender, EventArgs e) { CheckBox checkboxAllowed = (CheckBox)sender;// get the control that raised this event GridViewRow row = (GridViewRow)checkboxAllowed.NamingContainer;// get the containing row string RawValue = DataBinder.Eval(row.DataItem, strColumnName).ToString(); if (RawValue.ToUpper() == "TRUE") { checkboxAllowed.Checked = true; } else { checkboxAllowed.Checked = false; } } #endregion } ```
234,945
<p>I've inherited a WSDL file for a web service on a system that I don't have access to for development and testing.</p> <p>I need to generate a web service that adheres to that WSDL. The wrapper is .NET, but if there's an easy way to do this with another platform, we might be able to look at that. The production web service is Java-based.</p> <p>What's the best way to go about doing this?</p> <p>Note: The inherited wsdl doesn't appear to be compatible with <b>wsdl.exe</b> because it doesn't conform to WS-I Basic Profile v1.1. In particular, the group that passed it on mentioned it uses another standard that the Microsoft tool doesn't support, but they didn't clarify. The error is related to a required 'name' field:</p> <pre>Error: Element Reference '{namespace}/:viewDocumentResponse' declared in schema type '' from namespace '' - the required attribute 'name' is missing</pre> <p>For clarity's sake, I understand that I can easily create a .NET wrapper class from the WSDL file, but that's not what I need. It's like this:</p> <p>Update: The original web service was created using Axis.</p> <p><a href="http://paulw.us/blog/uploads/SO-WSDL-Question2.gif" rel="nofollow noreferrer">Diagram of system showing unavailable web service and mock web service http://paulw.us/blog/uploads/SO-WSDL-Question2.gif</a></p>
[ { "answer_id": 235005, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "<p>You may find useful the <a href=\"http://msdn.microsoft.com/en-us/library/7h3ystb6(VS.80).aspx\" rel=\"noreferrer\">command line utility <code>wsdl.exe</code></a> of .NET by using the <code>/serverInterface</code> option. According to the documentation:</p>\n\n<blockquote>\n <p>Generates interfaces for server-side\n implementation of an ASP.NET Web\n Service. An interface is generated for\n each binding in the WSDL document(s).\n The WSDL alone implements the WSDL\n contract (classes that implement the\n interface should not include either of\n the following on the class methods:\n Web Service attributes or\n Serialization attributes that change\n the WSDL contract). Short form is\n '/si'.</p>\n</blockquote>\n" }, { "answer_id": 235016, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try mock the wrapper interface using <a href=\"http://ayende.com/projects/rhino-mocks.aspx\" rel=\"nofollow noreferrer\">RhinoMocks</a> and <a href=\"http://structuremap.sourceforge.net/Default.htm\" rel=\"nofollow noreferrer\">StructureMap</a> .</p>\n" }, { "answer_id": 235043, "author": "danswain", "author_id": 30861, "author_profile": "https://Stackoverflow.com/users/30861", "pm_score": 0, "selected": false, "text": "<p>Not sure if this will help,</p>\n\n<p>what i've done recently is:</p>\n\n<ul>\n<li>Generate .cs file using the wsdl tool or visual studio</li>\n<li>I've changed it to be a partial class</li>\n<li>I've created another partial class, in which all it does is add a line to say that the class implements IWhatEver </li>\n<li>I've created an interface that is the same as the generated proxy class (Therefore the the proxy fully implements the interface)</li>\n</ul>\n\n<p>Then i've used a Mocking framework (Moq) in my case, to mock the WebService, I've then used poor mans dependancy injection (pass the mock into a constructor of the class under test) .. which can handle an instance of IWhatever</p>\n\n<p>Test away..</p>\n\n<p>Hope that helps</p>\n" }, { "answer_id": 235722, "author": "Vlad N", "author_id": 28472, "author_profile": "https://Stackoverflow.com/users/28472", "pm_score": 2, "selected": true, "text": "<p>We are using <a href=\"http://www.thinktecture.com/resourcearchive/tools-and-software/wscf\" rel=\"nofollow noreferrer\">WSCF - Web Services Contract First</a> tool from Thinktecture to do web service development creating XSD schema first and then generating service interfaces using this tool. It may be useful to generate service interfaces from WSDL but I have not tried this yet myself.</p>\n" }, { "answer_id": 244914, "author": "rbrayb", "author_id": 9922, "author_profile": "https://Stackoverflow.com/users/9922", "pm_score": 1, "selected": false, "text": "<p>Yes - you can use WSCF (as per above) to generate server side code. The actual URL can then be overwritten to point to the test URL that you want to use.</p>\n\n<p>However, this just generates a stub. You still have to code the actual e.g. GetCustomers() method which is somewhat suspect because you have no idea how the actual implementation works.</p>\n\n<p>Then you can either mock this or create a simple ASP web server to run it.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7301/" ]
I've inherited a WSDL file for a web service on a system that I don't have access to for development and testing. I need to generate a web service that adheres to that WSDL. The wrapper is .NET, but if there's an easy way to do this with another platform, we might be able to look at that. The production web service is Java-based. What's the best way to go about doing this? Note: The inherited wsdl doesn't appear to be compatible with **wsdl.exe** because it doesn't conform to WS-I Basic Profile v1.1. In particular, the group that passed it on mentioned it uses another standard that the Microsoft tool doesn't support, but they didn't clarify. The error is related to a required 'name' field: ``` Error: Element Reference '{namespace}/:viewDocumentResponse' declared in schema type '' from namespace '' - the required attribute 'name' is missing ``` For clarity's sake, I understand that I can easily create a .NET wrapper class from the WSDL file, but that's not what I need. It's like this: Update: The original web service was created using Axis. [Diagram of system showing unavailable web service and mock web service http://paulw.us/blog/uploads/SO-WSDL-Question2.gif](http://paulw.us/blog/uploads/SO-WSDL-Question2.gif)
We are using [WSCF - Web Services Contract First](http://www.thinktecture.com/resourcearchive/tools-and-software/wscf) tool from Thinktecture to do web service development creating XSD schema first and then generating service interfaces using this tool. It may be useful to generate service interfaces from WSDL but I have not tried this yet myself.
234,949
<p>I'm new to CakePHP but I've been though their FAQs and guides to no avail. This is so simple that I just must not be thinking straight:</p> <p>How can I access a parameter sent through the URL within my view files? </p> <p>Example: <a href="http://example.com/view/6" rel="nofollow noreferrer">http://example.com/view/6</a></p> <p>How would I take that parameter ("6") and cycle it through the controller to another view page?</p> <p>If that's too complex for a quick answer, how can I reference the 6 within the view page itself? The 6 in this situation is the "Id" value in my database, and I need to set it as the "parent" -</p> <p>Thanks</p>
[ { "answer_id": 235017, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 3, "selected": true, "text": "<p>The URL, as you have it, will call the 6() method of your ViewController, which is not a valid method name. You may have to play with your routes to make that work.</p>\n\n<p>If you don't want to configure your routes, you'll need the controller in the URL, like so:</p>\n\n<pre><code>http://example.com/thinger/view/6\n</code></pre>\n\n<p>which will call <code>thingerControllerObject-&gt;view(\"6\")</code>. If you want \"/view/\" to go to a different method, edit the routes. See:</p>\n\n<ul>\n<li><a href=\"http://book.cakephp.org/2.0/en/controllers.html\" rel=\"nofollow noreferrer\">Cake controllers</a></li>\n<li><a href=\"http://book.cakephp.org/2.0/en/development/routing.html#routes-configuration\" rel=\"nofollow noreferrer\">Cake routes</a></li>\n</ul>\n" }, { "answer_id": 235054, "author": "neilcrookes", "author_id": 9968, "author_profile": "https://Stackoverflow.com/users/9968", "pm_score": 3, "selected": false, "text": "<p>To access the parameter in your <em>view</em> look in <code>$this-&gt;params</code></p>\n" }, { "answer_id": 2349166, "author": "Nikolay Ruban", "author_id": 1821012, "author_profile": "https://Stackoverflow.com/users/1821012", "pm_score": 4, "selected": false, "text": "<p>Parameters can be retrieved like this</p>\n\n<pre><code>$this-&gt;params['pass']\n</code></pre>\n\n<p>Returns an array (numerically indexed) of URL parameters after the Action.</p>\n\n<pre><code>// URL: /posts/view/12/print/narrow\nArray\n(\n [0] =&gt; 12\n [1] =&gt; print\n [2] =&gt; narrow\n)\n</code></pre>\n" }, { "answer_id": 29944097, "author": "sabin", "author_id": 3427661, "author_profile": "https://Stackoverflow.com/users/3427661", "pm_score": 0, "selected": false, "text": "<p>Use the code below in the view file :</p>\n\n<pre><code>$url=Router::url($this-&gt;here, true);\n$url_arr=explode(\"/\",$url);\n</code></pre>\n\n<p>To see the content of <code>$url</code> been exploded simply print it using pr() as below :</p>\n\n<pre><code>pr($url_arr);\n</code></pre>\n\n<p>It will print associative array, thus you can access any particular number of parameter sent via url.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24565/" ]
I'm new to CakePHP but I've been though their FAQs and guides to no avail. This is so simple that I just must not be thinking straight: How can I access a parameter sent through the URL within my view files? Example: <http://example.com/view/6> How would I take that parameter ("6") and cycle it through the controller to another view page? If that's too complex for a quick answer, how can I reference the 6 within the view page itself? The 6 in this situation is the "Id" value in my database, and I need to set it as the "parent" - Thanks
The URL, as you have it, will call the 6() method of your ViewController, which is not a valid method name. You may have to play with your routes to make that work. If you don't want to configure your routes, you'll need the controller in the URL, like so: ``` http://example.com/thinger/view/6 ``` which will call `thingerControllerObject->view("6")`. If you want "/view/" to go to a different method, edit the routes. See: * [Cake controllers](http://book.cakephp.org/2.0/en/controllers.html) * [Cake routes](http://book.cakephp.org/2.0/en/development/routing.html#routes-configuration)
234,973
<p>What is the best way to check for the existence of a session variable in ASP.NET C#? </p> <p>I like to use <code>String.IsNullOrEmpty()</code> works for strings and wondered if there was a similar method for <code>Session</code>. Currently the only way I know of is:</p> <pre><code> var session; if (Session["variable"] != null) { session = Session["variable"].ToString(); } else { session = "set this"; Session["variable"] = session; } </code></pre>
[ { "answer_id": 234991, "author": "Ely", "author_id": 30488, "author_profile": "https://Stackoverflow.com/users/30488", "pm_score": 4, "selected": false, "text": "<p>That is pretty much how you do it. However, there is a shorter syntax you can use.</p>\n\n<pre><code>sSession = (string)Session[\"variable\"] ?? \"set this\";\n</code></pre>\n\n<p>This is saying if the session variables is null, set sSession to \"set this\"</p>\n" }, { "answer_id": 234997, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>Checking for nothing/Null is the way to do it. </p>\n\n<p>Dealing with object types is not the way to go. Declare a strict type and try to cast the object to the correct type. (And use cast hint or Convert)</p>\n\n<pre><code> private const string SESSION_VAR = \"myString\";\n string sSession;\n if (Session[SESSION_VAR] != null)\n {\n sSession = (string)Session[SESSION_VAR];\n }\n else\n {\n sSession = \"set this\";\n Session[SESSION_VAR] = sSession;\n }\n</code></pre>\n\n<p>Sorry for any syntax violations, I am a daily VB'er</p>\n" }, { "answer_id": 235024, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 0, "selected": false, "text": "<p>Are you using .NET 3.5? Create an IsNull extension method:</p>\n\n<pre><code>public static bool IsNull(this object input)\n{\n input == null ? return true : return false;\n}\n\npublic void Main()\n{\n object x = new object();\n if(x.IsNull)\n {\n //do your thing\n }\n}\n</code></pre>\n" }, { "answer_id": 235038, "author": "Kevin Pang", "author_id": 1574, "author_profile": "https://Stackoverflow.com/users/1574", "pm_score": 0, "selected": false, "text": "<p>If you know it's a string, you can use the String.IsEmptyOrNull() function.</p>\n" }, { "answer_id": 235062, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 4, "selected": false, "text": "<p>It may make things more elegant to wrap it in a property.</p>\n\n<pre><code>string MySessionVar\n{\n get{\n return Session[\"MySessionVar\"] ?? String.Empty;\n }\n set{\n Session[\"MySessionVar\"] = value;\n }\n}\n</code></pre>\n\n<p>then you can treat it as a string.</p>\n\n<pre><code>if( String.IsNullOrEmpty( MySessionVar ) )\n{\n // do something\n}\n</code></pre>\n" }, { "answer_id": 235131, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>Typically I create SessionProxy with strongly typed properties for items in the session. The code that accesses these properties checks for nullity and does the casting to the proper type. The nice thing about this is that all of my session related items are kept in one place. I don't have to worry about using different keys in different parts of the code (and wondering why it doesn't work). And with dependency injection and mocking I can fully test it with unit tests. If follows DRY principles and also lets me define reasonable defaults.</p>\n\n<pre><code>public class SessionProxy\n{\n private HttpSessionState session; // use dependency injection for testability\n public SessionProxy( HttpSessionState session )\n {\n this.session = session; //might need to throw an exception here if session is null\n }\n\n public DateTime LastUpdate\n {\n get { return this.session[\"LastUpdate\"] != null\n ? (DateTime)this.session[\"LastUpdate\"] \n : DateTime.MinValue; }\n set { this.session[\"LastUpdate\"] = value; }\n }\n\n public string UserLastName\n {\n get { return (string)this.session[\"UserLastName\"]; }\n set { this.session[\"UserLastName\"] = value; }\n }\n}\n</code></pre>\n" }, { "answer_id": 235142, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 8, "selected": true, "text": "<p>To follow on from what others have said. I tend to have two layers:</p>\n\n<p><strong>The core layer. This is within a DLL that is added to nearly all web app projects</strong>. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following:</p>\n\n<pre><code>public class SessionVar\n{\n static HttpSessionState Session\n {\n get\n {\n if (HttpContext.Current == null)\n throw new ApplicationException(\"No Http Context, No Session to Get!\");\n\n return HttpContext.Current.Session;\n }\n }\n\n public static T Get&lt;T&gt;(string key)\n {\n if (Session[key] == null)\n return default(T);\n else\n return (T)Session[key];\n }\n\n public static void Set&lt;T&gt;(string key, T value)\n {\n Session[key] = value;\n }\n}\n</code></pre>\n\n<p>Note the generics for getting any type.</p>\n\n<p>I then also add Getters/Setters for specific types, especially string since I often prefer to work with string.Empty rather than null for variables presented to Users.</p>\n\n<p>e.g:</p>\n\n<pre><code>public static string GetString(string key)\n{\n string s = Get&lt;string&gt;(key);\n return s == null ? string.Empty : s;\n}\n\npublic static void SetString(string key, string value)\n{\n Set&lt;string&gt;(key, value);\n}\n</code></pre>\n\n<p>And so on...</p>\n\n<p><strong>I then create wrappers to abstract that away and bring it up to the application model. For example, if we have customer details:</strong></p>\n\n<pre><code>public class CustomerInfo\n{\n public string Name\n {\n get\n {\n return SessionVar.GetString(\"CustomerInfo_Name\");\n }\n set\n {\n SessionVar.SetString(\"CustomerInfo_Name\", value);\n }\n }\n}\n</code></pre>\n\n<p>You get the idea right? :)</p>\n\n<p><strong>NOTE:</strong> Just had a thought when adding a comment to the accepted answer. Always ensure objects are serializable when storing them in Session when using a state server. It can be all too easy to try and save an object using the generics when on web farm and it go boom. I deploy on a web farm at work so added checks to my code in the core layer to see if the object is serializable, another benefit of encapsulating the Session Getters and Setters :)</p>\n" }, { "answer_id": 235245, "author": "Aaron Palmer", "author_id": 24908, "author_profile": "https://Stackoverflow.com/users/24908", "pm_score": 3, "selected": false, "text": "<p>The 'as' notation in c# 3.0 is very clean. Since all session variables are nullable objects, this lets you grab the value and put it into your own typed variable without worry of throwing an exception. Most objects can be handled this way.</p>\n\n<pre><code>string mySessionVar = Session[\"mySessionVar\"] as string;\n</code></pre>\n\n<p>My concept is that you should pull your Session variables into local variables and then handle them appropriately. Always assume your Session variables could be null and never cast them into a non-nullable type.</p>\n\n<p>If you need a non-nullable typed variable you can then use TryParse to get that.</p>\n\n<pre><code>int mySessionInt;\nif (!int.TryParse(mySessionVar, out mySessionInt)){\n // handle the case where your session variable did not parse into the expected type \n // e.g. mySessionInt = 0;\n}\n</code></pre>\n" }, { "answer_id": 236050, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 1, "selected": false, "text": "<p>I also like to wrap session variables in properties. The setters here are trivial, but I like to write the get methods so they have only one exit point. To do that I usually check for null and set it to a default value before returning the value of the session variable. \nSomething like this:</p>\n\n<pre><code>string Name\n{\n get \n {\n if(Session[\"Name\"] == Null)\n Session[\"Name\"] = \"Default value\";\n return (string)Session[\"Name\"];\n }\n set { Session[\"Name\"] = value; }\n}\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 7155396, "author": "Jon Falkner", "author_id": 906879, "author_profile": "https://Stackoverflow.com/users/906879", "pm_score": 2, "selected": false, "text": "<p>In my opinion, the easiest way to do this that is clear and easy to read is:</p>\n\n<pre><code> String sVar = (string)(Session[\"SessionVariable\"] ?? \"Default Value\");\n</code></pre>\n\n<p>It may not be the most efficient method, since it casts the default string value even in the case of the default (casting a string as string), but if you make it a standard coding practice, you find it works for all data types, and is easily readable.</p>\n\n<p>For example (a totally bogus example, but it shows the point):</p>\n\n<pre><code> DateTime sDateVar = (datetime)(Session[\"DateValue\"] ?? \"2010-01-01\");\n Int NextYear = sDateVar.Year + 1;\n String Message = \"The Procrastinators Club will open it's doors Jan. 1st, \" +\n (string)(Session[\"OpeningDate\"] ?? NextYear);\n</code></pre>\n\n<p>I like the Generics option, but it seems like overkill unless you expect to need this all over the place. The extensions method could be modified to specifically extend the Session object so that it has a \"safe\" get option like Session.StringIfNull(\"SessionVar\") and Session[\"SessionVar\"] = \"myval\"; It breaks the simplicity of accessing the variable via Session[\"SessionVar\"], but it is clean code, and still allows validating if null or if string if you need it.</p>\n" }, { "answer_id": 37277749, "author": "Sarfaraaz", "author_id": 4801298, "author_profile": "https://Stackoverflow.com/users/4801298", "pm_score": 2, "selected": false, "text": "<p>This method also does not assume that the object in the Session variable is a string</p>\n\n<pre><code>if((Session[\"MySessionVariable\"] ?? \"\").ToString() != \"\")\n //More code for the Code God\n</code></pre>\n\n<p>So basically replaces the null variable with an empty string before converting it to a string since <code>ToString</code> is part of the <code>Object</code> class</p>\n" }, { "answer_id": 52702507, "author": "Yakup Ad", "author_id": 7699822, "author_profile": "https://Stackoverflow.com/users/7699822", "pm_score": 1, "selected": false, "text": "<p>in this way it can be checked whether such a key is available </p>\n\n<pre><code>if (Session.Dictionary.ContainsKey(\"Sessionkey\")) --&gt; return Bool\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12252/" ]
What is the best way to check for the existence of a session variable in ASP.NET C#? I like to use `String.IsNullOrEmpty()` works for strings and wondered if there was a similar method for `Session`. Currently the only way I know of is: ``` var session; if (Session["variable"] != null) { session = Session["variable"].ToString(); } else { session = "set this"; Session["variable"] = session; } ```
To follow on from what others have said. I tend to have two layers: **The core layer. This is within a DLL that is added to nearly all web app projects**. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following: ``` public class SessionVar { static HttpSessionState Session { get { if (HttpContext.Current == null) throw new ApplicationException("No Http Context, No Session to Get!"); return HttpContext.Current.Session; } } public static T Get<T>(string key) { if (Session[key] == null) return default(T); else return (T)Session[key]; } public static void Set<T>(string key, T value) { Session[key] = value; } } ``` Note the generics for getting any type. I then also add Getters/Setters for specific types, especially string since I often prefer to work with string.Empty rather than null for variables presented to Users. e.g: ``` public static string GetString(string key) { string s = Get<string>(key); return s == null ? string.Empty : s; } public static void SetString(string key, string value) { Set<string>(key, value); } ``` And so on... **I then create wrappers to abstract that away and bring it up to the application model. For example, if we have customer details:** ``` public class CustomerInfo { public string Name { get { return SessionVar.GetString("CustomerInfo_Name"); } set { SessionVar.SetString("CustomerInfo_Name", value); } } } ``` You get the idea right? :) **NOTE:** Just had a thought when adding a comment to the accepted answer. Always ensure objects are serializable when storing them in Session when using a state server. It can be all too easy to try and save an object using the generics when on web farm and it go boom. I deploy on a web farm at work so added checks to my code in the core layer to see if the object is serializable, another benefit of encapsulating the Session Getters and Setters :)
234,976
<p>Scenario - I need to access an HTML template to generate a e-mail from my Business Logic Layer. It is a class library contains a sub folder that contains the file. When I tried the following code in a unit test:</p> <pre><code>string FilePath = string.Format(@"{0}\templates\MyFile.htm", Environment.CurrentDirectory); string FilePath1 = string.Format(@"{0}\templates\MyFile.htm", System.AppDomain.CurrentDomain.BaseDirectory); </code></pre> <p>It was using the C:\WINNT\system32\ or the ASP.NET Temporary Folder directory.</p> <p>What is the best to access this file without having to use an app.config or web.config file?</p> <p>[This is using a WCF Service]</p>
[ { "answer_id": 234984, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 3, "selected": false, "text": "<p>You're running this from an ASP.Net app right? Use <code>Server.MapPath()</code> instead.</p>\n\n<p>Also take a look at <code>System.IO.Path.Combine()</code> for concatenating paths.</p>\n\n<p>[Edit]\nSince you can't use <code>System.Web</code>, try this:</p>\n\n<pre><code>System.Reflection.Assembly.GetExecutingAssembly().Location\n</code></pre>\n\n<p>Or <code>GetEntryAssembly()</code>.</p>\n" }, { "answer_id": 234987, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 0, "selected": false, "text": "<p>Use</p>\n\n<pre><code>System.Web.HttpServerUtility.MapPath( \"~/templates/myfile.htm\" )\n</code></pre>\n" }, { "answer_id": 235122, "author": "Krzysztof Kozmic", "author_id": 13163, "author_profile": "https://Stackoverflow.com/users/13163", "pm_score": 1, "selected": false, "text": "<p>I belive you are looking for</p>\n\n<pre><code>System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n</code></pre>\n" }, { "answer_id": 4121313, "author": "woaksie", "author_id": 39567, "author_profile": "https://Stackoverflow.com/users/39567", "pm_score": 1, "selected": false, "text": "<p>I got this working on my site! I haven't been working on just this for the last 2 years!!!</p>\n\n<p>I added this inside my system.serviceModel block of the web.config. It seems to make all the paths relative to where your service is installed.</p>\n\n<pre><code> &lt;system.serviceModel&gt;\n&lt;serviceHostingEnvironment aspNetCompatibilityEnabled=\"true\"&gt;\n</code></pre>\n\n<p>better late than never?</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
Scenario - I need to access an HTML template to generate a e-mail from my Business Logic Layer. It is a class library contains a sub folder that contains the file. When I tried the following code in a unit test: ``` string FilePath = string.Format(@"{0}\templates\MyFile.htm", Environment.CurrentDirectory); string FilePath1 = string.Format(@"{0}\templates\MyFile.htm", System.AppDomain.CurrentDomain.BaseDirectory); ``` It was using the C:\WINNT\system32\ or the ASP.NET Temporary Folder directory. What is the best to access this file without having to use an app.config or web.config file? [This is using a WCF Service]
You're running this from an ASP.Net app right? Use `Server.MapPath()` instead. Also take a look at `System.IO.Path.Combine()` for concatenating paths. [Edit] Since you can't use `System.Web`, try this: ``` System.Reflection.Assembly.GetExecutingAssembly().Location ``` Or `GetEntryAssembly()`.
235,033
<p>In Delphi, why does the Assigned() function still return True after I call the destructor?</p> <p>The below example code will write "sl is still assigned" to the console.</p> <p>However, I can call FreeAndNil(sl); and it won't be assigned.</p> <p>I've been programming in Delphi for a while, but this never made sense to me.</p> <p>Can someone explain?</p> <pre><code>program Project1; {$APPTYPE CONSOLE} uses SysUtils, Classes; var sl : TStringList; begin sl := TStringList.Create; sl.Free; if Assigned(sl) then WriteLn('sl is still assigned') else WriteLn('sl is not assigned'); end. </code></pre> <p>I tried comparing the VCL operations... FreeAndNil is short and sweet and makes sense:</p> <pre><code>procedure FreeAndNil(var Obj); var P: TObject; begin P := TObject(Obj); TObject(Obj) := nil; // clear the reference before destroying the object P.Free; end; </code></pre> <p>But TObject.Free is in mysterious assembler, which I don't understand:</p> <pre><code>procedure TObject.Free; asm TEST EAX,EAX JE @@exit MOV ECX,[EAX] MOV DL,1 CALL dword ptr [ECX].vmtDestroy @@exit: end; </code></pre>
[ { "answer_id": 235041, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 6, "selected": true, "text": "<p>If you use sl.Free, the object is freed but the variable sl still points to the now invalid memory.</p>\n\n<p>Use FreeAndNil(sl) to both free the object and clear the pointer.</p>\n\n<p>By the way, if you do:</p>\n\n<pre><code>var\n sl1, sl2: TStringList;\nbegin\n sl1 := TStringList.Create;\n sl2 := sl1;\n FreeAndNil(sl1);\n // sl2 is still assigned and must be cleared separately (not with FreeAndNil because it points to the already freed object.)\nend;\n\n\n\n\nprocedure TObject.Free;\nasm\n TEST EAX,EAX\n JE @@exit // Jump to exit if pointer is nil.\n MOV ECX,[EAX] \n MOV DL,1\n CALL dword ptr [ECX].vmtDestroy // Call cleanup code (and destructor).\n@@exit:\nend;\n</code></pre>\n" }, { "answer_id": 235063, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 4, "selected": false, "text": "<p>Delphi VCL 'objects' are actually always pointers to objects, but this aspect is typically hidden from you. Just freeing the object leaves the pointer dangling around, so you should use FreeAndNil instead.</p>\n\n<p>The \"Mysterious Assembler\" translates roughly to:</p>\n\n<pre><code>if Obj != NIL then\n vmtDestroy(obj); // which is basically the destructor/deallocator.\n</code></pre>\n\n<p>Because Free checks for NIL first, it's safe to call FreeAndNil multiple times...</p>\n" }, { "answer_id": 12332779, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The Free method of TObject is like the \"delete operator\" in C++. Calling free will first call the Destroy function and then it will free the memory block that was allocated for the object. By default the pointer to the memory is not then set to zero because this will use up one instruction.</p>\n\n<p>The correct thing to do in most cases is not to set the pointer to zero because in most cases it does not matter. However, sometimes it is important and so you should only nil the pointer for those cases.</p>\n\n<p>For example. In a function where an object is created and then freed at the end of the function there is no point in setting the variable to zero since that is just wasting cpu time.</p>\n\n<p>But for a global object or field that might be referenced again later you should set it to zero. Use FreeAndNil or just set the pointer to nil yourself, does not matter. But stay away from zeroing variables that do not need to be zeroed by default.</p>\n" }, { "answer_id": 26045416, "author": "user1897277", "author_id": 1897277, "author_profile": "https://Stackoverflow.com/users/1897277", "pm_score": 1, "selected": false, "text": "<p>We have simple rules:</p>\n\n<ol>\n<li><p>If you want to use <code>Assigned()</code> to check if an object <code>Obj</code> is already created or not,\nthen make sure you use <code>FreeAndNil(Obj)</code> to free it.</p></li>\n<li><p><code>Assigned()</code> only says if an address is assigned or not.</p></li>\n<li><p>The local object reference is always assigned a garbage address (some random address), so it is good to set it to nil before using it.</p></li>\n</ol>\n\n<p>Example: (This is not the full code)</p>\n\n<pre><code>{Opened a new VCL application, placed a Button1, Memo1 on the form\nNext added a public reference GlobalButton of type TButton\nNext in OnClick handler of Button1 added a variable LocalButton \nNext in body, check if GlobalButton and LocalButton are assigned}\n\n TForm2 = class(TForm)\n Button1: TButton;\n Memo1: TMemo;\n procedure Button1Click(Sender: TObject);\n private\n { Private declarations }\n public\n { Public declarations }\n GlobalButton: TButton;\n end;\n\nprocedure TForm2.Button1Click(Sender: TObject);\nvar\n LocalButton: TButton;\nbegin\n if Assigned(GlobalButton) then \n Memo1.Lines.Add('GlobalButton assigned');\n if Assigned(LocalButton) then \n Memo1.Lines.Add('LocalButton assigned');\nend;\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
In Delphi, why does the Assigned() function still return True after I call the destructor? The below example code will write "sl is still assigned" to the console. However, I can call FreeAndNil(sl); and it won't be assigned. I've been programming in Delphi for a while, but this never made sense to me. Can someone explain? ``` program Project1; {$APPTYPE CONSOLE} uses SysUtils, Classes; var sl : TStringList; begin sl := TStringList.Create; sl.Free; if Assigned(sl) then WriteLn('sl is still assigned') else WriteLn('sl is not assigned'); end. ``` I tried comparing the VCL operations... FreeAndNil is short and sweet and makes sense: ``` procedure FreeAndNil(var Obj); var P: TObject; begin P := TObject(Obj); TObject(Obj) := nil; // clear the reference before destroying the object P.Free; end; ``` But TObject.Free is in mysterious assembler, which I don't understand: ``` procedure TObject.Free; asm TEST EAX,EAX JE @@exit MOV ECX,[EAX] MOV DL,1 CALL dword ptr [ECX].vmtDestroy @@exit: end; ```
If you use sl.Free, the object is freed but the variable sl still points to the now invalid memory. Use FreeAndNil(sl) to both free the object and clear the pointer. By the way, if you do: ``` var sl1, sl2: TStringList; begin sl1 := TStringList.Create; sl2 := sl1; FreeAndNil(sl1); // sl2 is still assigned and must be cleared separately (not with FreeAndNil because it points to the already freed object.) end; procedure TObject.Free; asm TEST EAX,EAX JE @@exit // Jump to exit if pointer is nil. MOV ECX,[EAX] MOV DL,1 CALL dword ptr [ECX].vmtDestroy // Call cleanup code (and destructor). @@exit: end; ```
235,047
<p>I am trying to insert about 50,000 objects (and therefore 50,000 keys) into a <code>java.util.HashMap&lt;java.awt.Point, Segment&gt;</code>. However, I keep getting an OutOfMemory exception. (<code>Segment</code> is my own class - very light weight - one <code>String</code> field, and 3 <code>int</code> fields).</p> <pre>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.HashMap.resize(HashMap.java:508) at java.util.HashMap.addEntry(HashMap.java:799) at java.util.HashMap.put(HashMap.java:431) at bus.tools.UpdateMap.putSegment(UpdateMap.java:168)</pre> <p>This seems quite ridiculous since I see that there is plenty of memory available on the machine - both in free RAM and HD space for virtual memory.</p> <p>Is it possible Java is running with some stringent memory requirements? Can I increase these?</p> <p>Is there some weird limitation with <code>HashMap</code>? Am I going to have to implement my own? Are there any other classes worth looking at?</p> <p>(I am running Java 5 under OS X 10.5 on an Intel machine with 2GB RAM.)</p>
[ { "answer_id": 235053, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 6, "selected": true, "text": "<p>You can increase the maximum heap size by passing -Xmx128m (where 128 is the number of megabytes) to java. I can't remember the default size, but it strikes me that it was something rather small.</p>\n\n<p>You can programmatically check how much memory is available by using the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html\" rel=\"noreferrer\">Runtime</a> class.</p>\n\n<pre><code>// Get current size of heap in bytes\nlong heapSize = Runtime.getRuntime().totalMemory();\n\n// Get maximum size of heap in bytes. The heap cannot grow beyond this size.\n// Any attempt will result in an OutOfMemoryException.\nlong heapMaxSize = Runtime.getRuntime().maxMemory();\n\n// Get amount of free memory within the heap in bytes. This size will increase\n// after garbage collection and decrease as new objects are created.\nlong heapFreeSize = Runtime.getRuntime().freeMemory();\n</code></pre>\n\n<p>(Example from <a href=\"http://www.exampledepot.com/egs/java.lang/GetHeapSize.html\" rel=\"noreferrer\">Java Developers Almanac</a>)</p>\n\n<p>This is also partially addressed in <a href=\"http://java.sun.com/docs/hotspot/HotSpotFAQ.html\" rel=\"noreferrer\">Frequently Asked Questions About the Java HotSpot VM</a>, and in the <a href=\"http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html\" rel=\"noreferrer\">Java 6 GC Tuning page</a>.</p>\n" }, { "answer_id": 235059, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 1, "selected": false, "text": "<p>Also might want to take a look at this:</p>\n\n<p><a href=\"http://java.sun.com/docs/hotspot/gc/\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/hotspot/gc/</a></p>\n" }, { "answer_id": 235078, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 2, "selected": false, "text": "<p>You probably need to set the flag -Xmx512m or some larger number when starting java. I think 64mb is the default.</p>\n\n<p>Edited to add:\nAfter you figure out how much memory your objects are actually using with a profiler, you may want to look into weak references or soft references to make sure you're not accidentally holding some of your memory hostage from the garbage collector when you're no longer using them.</p>\n" }, { "answer_id": 235098, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 1, "selected": false, "text": "<p>Implicit in these answers it that Java has a fixed size for memory and doesn't grow beyond the configured maximum heap size. This is unlike, say, C, where it's constrained only by the machine on which it's being run.</p>\n" }, { "answer_id": 235108, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 1, "selected": false, "text": "<p>By default, the JVM uses a limited heap space. The limit is JVM implementation-dependent, and it's not clear what JVM you are using. On OS's other than Windows, a 32-bit Sun JVM on a machine with 2 Gb or more will use a default maximum heap size of 1/4 of the physical memory, or 512 Mb in your case. However, the default for a \"client\" mode JVM is only 64 Mb maximum heap size, which may be what you've run into. Other vendor's JVM's may select different defaults.</p>\n\n<p>Of course, you can specify the heap limit explicitly with the <code>-Xmx&lt;NN&gt;m</code> option to <code>java</code>, where <code>&lt;NN&gt;</code> is the number of megabytes for the heap.</p>\n\n<p>As a rough guess, your hash table should only be using about 16 Mb, so there must be some other large objects on the heap. If you could use a <code>Comparable</code> key in a <code>TreeMap</code>, that would save some memory.</p>\n\n<p>See <a href=\"http://java.sun.com/docs/hotspot/gc5.0/ergo5.html#0.0.%20Garbage%20collector,%20heap,%20and%20runtime%20compiler|outline\" rel=\"nofollow noreferrer\">\"Ergonomics in the 5.0 JVM\"</a> for more details.</p>\n" }, { "answer_id": 235114, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 2, "selected": false, "text": "<p>Another thing to try if you know the number of objects beforehand is to use the HashMap(int capacity,double loadfactor) constructor instead of the default no-arg one which uses defaults of (16,0.75). If the number of elements in your HashMap exceeds (capacity * loadfactor) then the underlying array in the HashMap will be resized to the next power of 2 and the table will be rehashed. This array also requires a contiguous area of memory so for example if you're doubling from a 32768 to a 65536 size array you'll need a 256kB chunk of memory free. To avoid the extra allocation and rehashing penalties, just use a larger hash table from the start. It'll also decrease the chance that you won't have a contiguous area of memory large enough to fit the map.</p>\n" }, { "answer_id": 235116, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 2, "selected": false, "text": "<p>The implementations are backed by arrays usually. Arrays are fixed size blocks of memory. The hashmap implementation starts by storing data in one of these arrays at a given capacity, say 100 objects.</p>\n\n<p>If it fills up the array and you keep adding objects the map needs to secretly increase its array size. Since arrays are fixed, it does this by creating an entirely new array, in memory, along with the current array, that is slightly larger. This is referred to as growing the array. Then all the items from the old array are copied into the new array and the old array is dereferenced with the hope it will be garbage collected and the memory freed at some point.</p>\n\n<p>Usually the code that increases the capacity of the map by copying items into a larger array is the cause of such a problem. There are \"dumb\" implementations and smart ones that use a growth or load factor that determines the size of the new array based on the size of the old array. Some implementations hide these parameters and some do not so you cannot always set them. The problem is that when you cannot set it, it chooses some default load factor, like 2. So the new array is twice the size of the old. Now your supposedly 50k map has a backing array of 100k.</p>\n\n<p>Look to see if you can reduce the load factor down to 0.25 or something. this causes more hash map collisions which hurts performance but you are hitting a memory bottleneck and need to do so.</p>\n\n<p>Use this constructor:</p>\n\n<p>(<a href=\"http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#HashMap(int\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#HashMap(int</a>, float))</p>\n" }, { "answer_id": 235134, "author": "Uri", "author_id": 23072, "author_profile": "https://Stackoverflow.com/users/23072", "pm_score": 1, "selected": false, "text": "<p>The Java heap space is limited by default, but that still sounds extreme (though how big are your 50000 segments?)</p>\n\n<p>I am suspecting that you have some other problem, like the arrays in the set growing too big because everything gets assigned into the same \"slot\" (also affects performance, of course). However, that seems unlikely if your points are uniformly distributed.</p>\n\n<p>I'm wondering though why you're using a HashMap rather than a TreeMap? Even though points are two dimensional, you could subclass them with a compare function and then do log(n) lookups.</p>\n" }, { "answer_id": 235161, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 3, "selected": false, "text": "<p>Some people are suggesting changing the parameters of the HashMap to tighten up the memory requirements. I would suggest to <strong>measure instead of guessing</strong>; it might be something else causing the OOME. In particular, I'd suggest using either <a href=\"http://profiler.netbeans.org/\" rel=\"nofollow noreferrer\">NetBeans Profiler</a> or <a href=\"https://visualvm.dev.java.net/\" rel=\"nofollow noreferrer\">VisualVM</a> (which comes with Java 6, but I see you're stuck with Java 5).</p>\n" }, { "answer_id": 237498, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 1, "selected": false, "text": "<p>Random thought: The hash buckets associated with HashMap are not particularly memory efficient. You may want to try out TreeMap as an alternative and see if it still provide sufficient performance.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I am trying to insert about 50,000 objects (and therefore 50,000 keys) into a `java.util.HashMap<java.awt.Point, Segment>`. However, I keep getting an OutOfMemory exception. (`Segment` is my own class - very light weight - one `String` field, and 3 `int` fields). ``` Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.HashMap.resize(HashMap.java:508) at java.util.HashMap.addEntry(HashMap.java:799) at java.util.HashMap.put(HashMap.java:431) at bus.tools.UpdateMap.putSegment(UpdateMap.java:168) ``` This seems quite ridiculous since I see that there is plenty of memory available on the machine - both in free RAM and HD space for virtual memory. Is it possible Java is running with some stringent memory requirements? Can I increase these? Is there some weird limitation with `HashMap`? Am I going to have to implement my own? Are there any other classes worth looking at? (I am running Java 5 under OS X 10.5 on an Intel machine with 2GB RAM.)
You can increase the maximum heap size by passing -Xmx128m (where 128 is the number of megabytes) to java. I can't remember the default size, but it strikes me that it was something rather small. You can programmatically check how much memory is available by using the [Runtime](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html) class. ``` // Get current size of heap in bytes long heapSize = Runtime.getRuntime().totalMemory(); // Get maximum size of heap in bytes. The heap cannot grow beyond this size. // Any attempt will result in an OutOfMemoryException. long heapMaxSize = Runtime.getRuntime().maxMemory(); // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created. long heapFreeSize = Runtime.getRuntime().freeMemory(); ``` (Example from [Java Developers Almanac](http://www.exampledepot.com/egs/java.lang/GetHeapSize.html)) This is also partially addressed in [Frequently Asked Questions About the Java HotSpot VM](http://java.sun.com/docs/hotspot/HotSpotFAQ.html), and in the [Java 6 GC Tuning page](http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html).
235,072
<p>Does the C++ compiler optimize the multiply by two operation <code>x*2</code> to a bitshift operation <code>x&lt;&lt;1</code>?</p> <p>I would love to believe that yes.</p>
[ { "answer_id": 235077, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 4, "selected": false, "text": "<p>Not if x is a float it won't.</p>\n" }, { "answer_id": 235082, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>Yes, they will.</p>\n" }, { "answer_id": 235083, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>Yes. They also optimize other similar operations, such as multiplying by non-powers of two that can be rewritten as the sums of some shifts. They will also optimize divisions by powers of 2 into right-shifts, but beware that when working with signed integers, the two operations are different! The compiler has to emit some extra bit twiddling instructions to make sure the results are the same for positive and negative numbers, but it's still faster than doing a division. It also similarly optimizes moduli by powers of 2.</p>\n" }, { "answer_id": 235103, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 6, "selected": true, "text": "<p>Actually VS2008 optimizes this to x+x:</p>\n\n<pre><code>01391000 push ecx \n int x = 0;\n\n scanf(\"%d\", &amp;x);\n01391001 lea eax,[esp] \n01391004 push eax \n01391005 push offset string \"%d\" (13920F4h) \n0139100A mov dword ptr [esp+8],0 \n01391012 call dword ptr [__imp__scanf (13920A4h)] \n\n int y = x * 2;\n01391018 mov ecx,dword ptr [esp+8] \n0139101C lea edx,[ecx+ecx] \n</code></pre>\n\n<p>In an x64 build it is even more explicit and uses:</p>\n\n<pre><code> int y = x * 2;\n000000013FB9101E mov edx,dword ptr [x] \n\n printf(\"%d\", y);\n000000013FB91022 lea rcx,[string \"%d\" (13FB921B0h)] \n000000013FB91029 add edx,edx \n</code></pre>\n\n<p>This is will the optimization settings on 'Maximize speed' (/O2)</p>\n" }, { "answer_id": 235110, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 4, "selected": false, "text": "<p>VS 2008 optimized mine to x &lt;&lt; 1.</p>\n\n<pre><code> x = x * 2;\n004013E7 mov eax,dword ptr [x] \n004013EA shl eax,1 \n004013EC mov dword ptr [x],eax \n</code></pre>\n\n<p>EDIT: This was using VS default \"Debug\" configuration with optimization disabled (/Od). Using any of the optimization switches (/O1, /O2 (VS \"Retail\"), or /Ox) results in the the add self code Rob posted. Also, just for good measure, I verified <code>x = x &lt;&lt; 1</code> is indeed treated the same way as <code>x = x * 2</code> by the cl compiler in both /Od and /Ox. So, in summary, cl.exe version 15.00.30729.01 for x86 treats <code>* 2</code> and <code>&lt;&lt; 1</code> identically and I expect nearly all other recent compilers do the same.</p>\n" }, { "answer_id": 235162, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": -1, "selected": false, "text": "<p>It depends on what compiler you have. Visual C++ for example is notoriously poor in optimizing. If you edit your post to say what compiler you are using, it would be easier to answer. </p>\n" }, { "answer_id": 235178, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 3, "selected": false, "text": "<p>The answer is \"if it is faster\" (or smaller). This depends on the target architecture heavily as well as the register usage model for a given compiler. In general, the answer is \"yes, always\" as this is a very simple peephole optimization to implement and is usually a decent win.</p>\n" }, { "answer_id": 235203, "author": "dwj", "author_id": 346, "author_profile": "https://Stackoverflow.com/users/346", "pm_score": 0, "selected": false, "text": "<p>Unless something is specified in a languages standard you'll never get a guaranteed answer to such a question. When in doubt have your compiler spit out assemble code and check. That's going to be the only way to really know.</p>\n" }, { "answer_id": 235291, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": false, "text": "<p>This article from Raymond Chen could be interesting:</p>\n\n<p><strong>When is x/2 different from x>>1?</strong> :\n<a href=\"http://blogs.msdn.com/oldnewthing/archive/2005/05/27/422551.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2005/05/27/422551.aspx</a></p>\n\n<p>Quoting Raymond:</p>\n\n<blockquote>\n <blockquote>\n <p>Of course, the compiler is free to recognize this and rewrite your multiplication or shift operation. In fact, it is very likely to do this, because x+x is more easily pairable than a multiplication or shift. Your shift or multiply-by-two is probably going to be rewritten as something closer to an add eax, eax instruction.</p>\n \n <p>[...]</p>\n \n <p>Even if you assume that the shift fills with the sign bit, The result of the shift and the divide are different if x is negative.</p>\n \n <p>(-1) / 2 ≡ 0<br>\n (-1) >> 1 ≡ -1<br></p>\n \n <p>[...]</p>\n \n <p><strong>The moral of the story is to write what you mean. If you want to divide by two, then write \"/2\", not \">>1\".</strong></p>\n </blockquote>\n</blockquote>\n\n<p>We can only assume it is wise to tell the compiler what you want, not what you want him to do: <strong>The compiler is better than an human is at optimizing</strong> small scale code (thanks for Daemin to point this subtle point): If you really want optimization, use a profiler, and study your algorithms' efficiency.</p>\n" }, { "answer_id": 235316, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "<p>I'm sure they all do these kind of optimizations, but I wonder if they are still relevant. Older processors did multiplication by shifting and adding, which could take a number of cycles to complete. Modern processors, on the other hand, have a set of barrel-shifters which can do all the necessary shifts and additions simultaneously in one clock cycle or less. Has anyone actually benchmarked whether these optimizations really help?</p>\n" }, { "answer_id": 235699, "author": "MBCook", "author_id": 18189, "author_profile": "https://Stackoverflow.com/users/18189", "pm_score": 0, "selected": false, "text": "<p>@Ferruccio Barletta</p>\n\n<p>That's a good question. I went Googling to try to find the answer.</p>\n\n<p>I couldn't find answers for Intel processors directly, but <a href=\"https://www.openrce.org/blog/view/1128/Opcode_execution_cost\" rel=\"nofollow noreferrer\">this</a> page has someone who tried to time things. It shows shifts to be more than twice as fast as ads and multiplies. Bit shifts are so simple (where a multiply could be a shift and an addition) that this makes sense.</p>\n\n<p>So then I Googled AMD, and found an old optimization guide for the Athlon from 2002 that lists that lists the fastest ways to multiply numbers by contants between 2 and 32. Interestingly, it depends on the number. Some are ads, some shifts. It's on <a href=\"http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/22007.pdf\" rel=\"nofollow noreferrer\">page 122</a>.</p>\n\n<p>A guide for the <a href=\"http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/25112.PDF\" rel=\"nofollow noreferrer\">Athlon 64</a> shows the same thing (page 164 or so). It says multiplies are 3 (in 32-bit) or 4 (in 64-bit) cycle operations, where shifts are 1 and adds are 2.</p>\n\n<p>It seems it is still useful as an optimization.</p>\n\n<p>Ignoring cycle counts though, this kind of method would prevent you from tying up the multiplication execution units (possibly), so if you were doing lots of multiplications in a tight loop where some use constants and some don't the extra scheduling room might be useful.</p>\n\n<p>But that's speculation.</p>\n" }, { "answer_id": 261078, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 2, "selected": false, "text": "<p>That's only the start of what optimizers can do. To see what your compiler does, look for the switch that causes it to emit assembler source. For the Digital Mars compilers, the output assembler can be examined with the OBJ2ASM tool. If you want to learn how your compiler works, looking at the assembler output can be very illuminating.</p>\n" }, { "answer_id": 52289986, "author": "tobi_s", "author_id": 8680401, "author_profile": "https://Stackoverflow.com/users/8680401", "pm_score": 0, "selected": false, "text": "<p>Why do you think that's an optimization?</p>\n\n<p>Why not <code>2*x</code> → <code>x+x</code>? Or maybe the multiplication operation is as fast as the left-shift operation (maybe only if only one bit is set in the multiplicand)? If you never use the result, why not leave it out from the compiled output? If the compiler already loaded <code>2</code> to some register, maybe the multiplication instruction will be faster e.g. if we'd have to load the shift count first. Maybe the shift operation is larger, and your inner loop would no longer fit into the prefetch buffer of the CPU thus penalizing performance? Maybe the compiler can prove that the only time you call your function <code>x</code> will have the value 37 and <code>x*2</code> can be replaced by <code>74</code>? Maybe you're doing <code>2*x</code> where <code>x</code> is a loop count (very common, though implicit, when looping over two-byte objects)? Then the compiler can change the loop from</p>\n\n<pre><code> for(int x = 0; x &lt; count; ++x) ...2*x...\n</code></pre>\n\n<p>to the equivalent (leaving aside pathologies)</p>\n\n<pre><code> int count2 = count * 2\n for(int x = 0; x &lt; count2; x += 2) ...x...\n</code></pre>\n\n<p>which replaces <code>count</code> multiplications with a single multiplication, or it might be able to leverage the <code>lea</code> instruction which combines the multiplication with a memory read.</p>\n\n<p><strong>My point is</strong>: there are millions of factors deciding whether replacing <code>x*2</code> by <code>x&lt;&lt;1</code> yields a faster binary. An optimizing compiler will try to generate the fastest code for the program it is given, not for an isolated operation. Therefore optimization results for the same code can vary largely depending on the surrounding code, and they may not be trivial at all.</p>\n\n<p>Generally, there are very few benchmarks that show large differences between compilers. It is therefore a fair assumption that compilers are doing a good job because if there were cheap optimizations left, at least one of the compilers would implement them -- and all the others would follow in their next release.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
Does the C++ compiler optimize the multiply by two operation `x*2` to a bitshift operation `x<<1`? I would love to believe that yes.
Actually VS2008 optimizes this to x+x: ``` 01391000 push ecx int x = 0; scanf("%d", &x); 01391001 lea eax,[esp] 01391004 push eax 01391005 push offset string "%d" (13920F4h) 0139100A mov dword ptr [esp+8],0 01391012 call dword ptr [__imp__scanf (13920A4h)] int y = x * 2; 01391018 mov ecx,dword ptr [esp+8] 0139101C lea edx,[ecx+ecx] ``` In an x64 build it is even more explicit and uses: ``` int y = x * 2; 000000013FB9101E mov edx,dword ptr [x] printf("%d", y); 000000013FB91022 lea rcx,[string "%d" (13FB921B0h)] 000000013FB91029 add edx,edx ``` This is will the optimization settings on 'Maximize speed' (/O2)
235,081
<p>We primarily use an ASP.NET environment at work. Right now I'm building an application which uses "Modules", which is just a UserControl, with its' Javascript right in the control, and a link element to the stylesheet for that control. I want to keep it modular, and would like the style of this control to be independent from the markup/javascript.</p> <p>So I'm wondering what the preferred method of doing this is? Obviously if I didn't want the "theme" functionality I'm after, I could just use style tags at the top of the control. Right now I have a link element, as I said, and this isn't proper I don't think. </p> <p>Does anyone have any preferred methods, and if so, what and why?</p> <hr> <p>I considered ASP.NET themes briefly, but the idea of these controls are a little different, I think.</p> <p>It's basically a shopping cart system. I don't want to get into it all, but we are using a really neat security system, and we don't want to use a premade shopping cart. I'm developing a set of controls that can be dropped on a page, for instance in SiteFinity (which is the CMS system we use) or for any other project we might have. Normally I would compile these into a DLL so we get ACTUAL controls we can drag &amp; drop from the toolbox, then I could use internal "generic" styling and allow for any additive styling someone might want, as well as supplying a few fancier styles as well.</p> <p>This is the first time I've ever done this, or really the first time anyone in our shop has done this either so I'm kind of figuring it out as I go. I might be pretty far off-base, but hopefully I'm not.</p> <hr> <p>Right, the idea for this is to have a "theme", which is really just a CSS file and a jQuery template. I have them named the same, and have a Theme property on the usercontrol to set it. </p> <p>When these controls are finalized, I might refactor the javascript to a RegisterScriptBlock on the code-behind, but for now they just in script tags on the control itself.</p> <p>What prompted this question was DebugBar for IE, giving me warnings that link elements are not allowed inside a div. I don't much care, but after thinking about it, I had no idea how to link to the css file without doing that. I considered very briefly having an 'empty' link tag on the master and then setting THAT in the code behind on Page_Load of the UserControl, but that just seems like ass.</p> <p>I could use @import I guess but I think link tags are preferred, correct?</p>
[ { "answer_id": 235099, "author": "John Dunagan", "author_id": 28939, "author_profile": "https://Stackoverflow.com/users/28939", "pm_score": 1, "selected": false, "text": "<p>It depends on how big your app is, and whether or not it's dependent on Themes elsewhere, IMHO.</p>\n\n<p>If you're using a .skin file, or if the majority of the app is also plugged into the theme, you might as well go with the theme. </p>\n\n<p>But if it's just a few styles you need, you're better off to set the stylesheet manually, keep your css file external (inline styles are a PITA and defeat one of the core purposes of css).</p>\n\n<p>In either case, don't forget to set the CssClass attribute on your controls.</p>\n" }, { "answer_id": 235102, "author": "WillCodeForCoffee", "author_id": 31197, "author_profile": "https://Stackoverflow.com/users/31197", "pm_score": 2, "selected": false, "text": "<p>I think what you're supposed to do is use Page.RegisterScriptBlock to register your script blocks. Best-case you shouldn't have them inline in your ascx inside script blocks. This isn't always possible, but theoretically it's the best way.</p>\n\n<p>Ideally your styles should be separate from your markup as well. Your controls can have classes and IDs, but your style is based on your application and not your controls. Controls can theoretically be used in other applications where you might want a different style.</p>\n" }, { "answer_id": 237526, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 3, "selected": true, "text": "<p>It sounds like you're rolling your own theme engine... why not use ASP.NET Themes?</p>\n\n<p>If you're determined to do it yourself, here's some code from the <a href=\"http://www.codeplex.com/cssfriendly\" rel=\"nofollow noreferrer\">CssFriendly project</a> that may be of interest to you. (I think it should be ok to post the code as long as I cite where it's from.) The .css files are flagged as Embedded Resource and the code below is used to include them as needed.</p>\n\n<pre><code>string filePath = page.ClientScript.GetWebResourceUrl(type, css);\n\n// if filePath is not empty, embedded CSS exists -- register it\nif (!String.IsNullOrEmpty(filePath))\n{\n if (!Helpers.HeadContainsLinkHref(page, filePath))\n {\n HtmlLink link = new HtmlLink();\n link.Href = page.ResolveUrl(filePath);\n link.Attributes[\"type\"] = \"text/css\";\n link.Attributes[\"rel\"] = \"stylesheet\";\n page.Header.Controls.Add(link);\n }\n}\n</code></pre>\n" }, { "answer_id": 240450, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 1, "selected": false, "text": "<p>To be proper I would have an import.css file - structure the naming of the classes to follow your controls, and import the styles within the header of the document.</p>\n\n<p>If you have a module called \"30DayPricingCalc\" then you could name the classes/id's:</p>\n\n<p><strong>30DayPricingCalc.css</strong></p>\n\n<pre><code>.30daypricingcalc_main_content\n{\n ...\n}\n</code></pre>\n\n<p>Also if you haven't I would setup a list of generic reusable styles to save you room. Since elements will allow multiple classes per object.</p>\n\n<p>Also, link tags matter a lot less now than they used to. we're well past support for IE5 generation browsers and IE6 supports the @import tag.</p>\n\n<p>Cheers!</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31307/" ]
We primarily use an ASP.NET environment at work. Right now I'm building an application which uses "Modules", which is just a UserControl, with its' Javascript right in the control, and a link element to the stylesheet for that control. I want to keep it modular, and would like the style of this control to be independent from the markup/javascript. So I'm wondering what the preferred method of doing this is? Obviously if I didn't want the "theme" functionality I'm after, I could just use style tags at the top of the control. Right now I have a link element, as I said, and this isn't proper I don't think. Does anyone have any preferred methods, and if so, what and why? --- I considered ASP.NET themes briefly, but the idea of these controls are a little different, I think. It's basically a shopping cart system. I don't want to get into it all, but we are using a really neat security system, and we don't want to use a premade shopping cart. I'm developing a set of controls that can be dropped on a page, for instance in SiteFinity (which is the CMS system we use) or for any other project we might have. Normally I would compile these into a DLL so we get ACTUAL controls we can drag & drop from the toolbox, then I could use internal "generic" styling and allow for any additive styling someone might want, as well as supplying a few fancier styles as well. This is the first time I've ever done this, or really the first time anyone in our shop has done this either so I'm kind of figuring it out as I go. I might be pretty far off-base, but hopefully I'm not. --- Right, the idea for this is to have a "theme", which is really just a CSS file and a jQuery template. I have them named the same, and have a Theme property on the usercontrol to set it. When these controls are finalized, I might refactor the javascript to a RegisterScriptBlock on the code-behind, but for now they just in script tags on the control itself. What prompted this question was DebugBar for IE, giving me warnings that link elements are not allowed inside a div. I don't much care, but after thinking about it, I had no idea how to link to the css file without doing that. I considered very briefly having an 'empty' link tag on the master and then setting THAT in the code behind on Page\_Load of the UserControl, but that just seems like ass. I could use @import I guess but I think link tags are preferred, correct?
It sounds like you're rolling your own theme engine... why not use ASP.NET Themes? If you're determined to do it yourself, here's some code from the [CssFriendly project](http://www.codeplex.com/cssfriendly) that may be of interest to you. (I think it should be ok to post the code as long as I cite where it's from.) The .css files are flagged as Embedded Resource and the code below is used to include them as needed. ``` string filePath = page.ClientScript.GetWebResourceUrl(type, css); // if filePath is not empty, embedded CSS exists -- register it if (!String.IsNullOrEmpty(filePath)) { if (!Helpers.HeadContainsLinkHref(page, filePath)) { HtmlLink link = new HtmlLink(); link.Href = page.ResolveUrl(filePath); link.Attributes["type"] = "text/css"; link.Attributes["rel"] = "stylesheet"; page.Header.Controls.Add(link); } } ```
235,090
<p>How do you configure cruiseControl to send out emails that contains the error log whenever a build fails? I've gotten it to send out emails to users when the build fails, but it does not include the actual error that caused the build to fail. I know that if I only configure it to send out emails to the users that have made modifications, the error log is included in those emails. This is a sample of what I have:</p> <p>&lt; publishers><br/> &nbsp; &nbsp;&nbsp;&lt; rss/><br/> &nbsp; &nbsp;&nbsp;&lt; xmllogger/> <br/> &nbsp; &nbsp;&nbsp;&lt; email from="[email protected]" mailhost="abc.abc.com" includeDetails="TRUE"><br/>&nbsp; &nbsp;&nbsp; &lt; users><br/>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt; user name="Joe" group="devs" address="[email protected]"/><br/>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt; user name="Jim" group="devs" address="[email protected]"/><br/>&nbsp; &nbsp;&nbsp; &lt; /users><br/>&nbsp; &nbsp;&nbsp; &lt; groups><br/>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt; group name="devs" notification="Failed"/><br/>&nbsp; &nbsp;&nbsp; &lt; /groups><br/>&nbsp; &nbsp;&nbsp; &lt; /email><br/> &lt; /publishers></p>
[ { "answer_id": 235124, "author": "Alex", "author_id": 26564, "author_profile": "https://Stackoverflow.com/users/26564", "pm_score": 1, "selected": false, "text": "<p>Your email publisher will take the buildlog.xml and transorm it against whatever XSL's are configured either in your console or service config depending on which you use. There should be no difference in the content of the email though no matter on who you have it configured to be sent to and when. As long as you have the merge before the email publiseher and the email in the publishers section. I don't see how it could be different Are you sure the same failure produces different emails? My guess would be you are failing somewhere bad and the build log is not being genereted one way. </p>\n" }, { "answer_id": 235210, "author": "stung", "author_id": 18170, "author_profile": "https://Stackoverflow.com/users/18170", "pm_score": 2, "selected": false, "text": "<p>You can check if \\cruisecontrol.net\\server\\xsl\\compile.xsl is the same as \\cruisecontrol.net\\webdashboard\\xsl\\compile.xsl.</p>\n\n<p>Compile.xsl is the default file used to print the error messages from your error log. The one in \\webdashboard\\ is used for the web dashboard (as the name implies) and the one under \\server\\ is used for emails.</p>\n\n<p>You can also check ccnet.exe.config whether or not \\cruisecontrol.net\\server\\xsl\\compile.xsl is used for emails.</p>\n\n<p>Mine's for example points to compile.xsl on \\server:</p>\n\n<pre><code>&lt;!-- Specifies the stylesheets that are used to transform the build results when using the EmailPublisher --&gt;\n&lt;xslFiles&gt;\n &lt;file name=\"xsl\\header.xsl\" /&gt;\n &lt;file name=\"xsl\\compile.xsl\" /&gt;\n &lt;file name=\"xsl\\unittests.xsl\" /&gt;\n &lt;file name=\"xsl\\fit.xsl\" /&gt;\n &lt;file name=\"xsl\\modifications.xsl\" /&gt;\n &lt;file name=\"xsl\\fxcop-summary.xsl\" /&gt;\n&lt;/xslFiles&gt;\n</code></pre>\n" }, { "answer_id": 235213, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The build log is getting generated. I can see the error. It's just not included in the email.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do you configure cruiseControl to send out emails that contains the error log whenever a build fails? I've gotten it to send out emails to users when the build fails, but it does not include the actual error that caused the build to fail. I know that if I only configure it to send out emails to the users that have made modifications, the error log is included in those emails. This is a sample of what I have: < publishers>     < rss/>     < xmllogger/>     < email from="[email protected]" mailhost="abc.abc.com" includeDetails="TRUE"> < users> < user name="Joe" group="devs" address="[email protected]"/> < user name="Jim" group="devs" address="[email protected]"/> < /users> < groups> < group name="devs" notification="Failed"/> < /groups> < /email> < /publishers>
You can check if \cruisecontrol.net\server\xsl\compile.xsl is the same as \cruisecontrol.net\webdashboard\xsl\compile.xsl. Compile.xsl is the default file used to print the error messages from your error log. The one in \webdashboard\ is used for the web dashboard (as the name implies) and the one under \server\ is used for emails. You can also check ccnet.exe.config whether or not \cruisecontrol.net\server\xsl\compile.xsl is used for emails. Mine's for example points to compile.xsl on \server: ``` <!-- Specifies the stylesheets that are used to transform the build results when using the EmailPublisher --> <xslFiles> <file name="xsl\header.xsl" /> <file name="xsl\compile.xsl" /> <file name="xsl\unittests.xsl" /> <file name="xsl\fit.xsl" /> <file name="xsl\modifications.xsl" /> <file name="xsl\fxcop-summary.xsl" /> </xslFiles> ```
235,118
<p>I am trying to create a route with a Username...</p> <p>So the URL would be mydomain.com/abrudtkhul (abrudtkhul being the username)</p> <p>My application will have public profiles based on usernames (Ex: <a href="http://delicious.com/abrudtkuhl" rel="noreferrer">http://delicious.com/abrudtkuhl</a>). I want to replicate this URL scheme.</p> <p>How can I structure this in ASP.Net MVC? I am using Membership/Roles Providers too.</p>
[ { "answer_id": 235128, "author": "Jason Whitehorn", "author_id": 27860, "author_profile": "https://Stackoverflow.com/users/27860", "pm_score": 1, "selected": false, "text": "<p>You could have a route that looks like:</p>\n\n<pre><code>{username}\n</code></pre>\n\n<p>with the defaults of</p>\n\n<pre><code>Controller = \"Users\"\n</code></pre>\n\n<p>For the finished product of:</p>\n\n<pre><code> routes.MapRoute(\n \"Users\",\n \"{username}\",\n new { controller = \"Users\" }\n</code></pre>\n\n<p>So that the Username is the only url parameter, the MVC assumes it passes it to the users controller.</p>\n" }, { "answer_id": 235130, "author": "WillCodeForCoffee", "author_id": 31197, "author_profile": "https://Stackoverflow.com/users/31197", "pm_score": 1, "selected": false, "text": "<p>Are you trying to pass it as a parameter to a Controller?</p>\n\n<p>Theoretically you could do something like this:</p>\n\n<p>routes.MapRoute(\"name\", \"{user}/{controller}/{action}\", new { controller = \"blah\", action = \"blah\", user = \"\" })</p>\n\n<p>I'm not too experienced with ASP.NET routing, but I figure that <em>should</em> work.</p>\n" }, { "answer_id": 235276, "author": "danswain", "author_id": 30861, "author_profile": "https://Stackoverflow.com/users/30861", "pm_score": 1, "selected": false, "text": "<pre><code>routes.MapRoute(\n \"Users\",\n \"{username}\", \n new { controller = \"Users\", action=\"ShowUser\", username=\"\"});\n</code></pre>\n\n<p>Ok, what this will do is default the username parameter to the value of {username}</p>\n\n<p>so even though you've written username=\"\" it'll know to pass the value of {username} .. by virtue of the strings match.</p>\n\n<p>This would expect</p>\n\n<p>for the url form</p>\n\n<p><a href=\"http://website.com/username\" rel=\"nofollow noreferrer\">http://website.com/username</a></p>\n\n<ul>\n<li>Users Contoller</li>\n<li>ShowUser Action (method in controller)</li>\n<li>username parameter on the ShowUser action (method)</li>\n</ul>\n" }, { "answer_id": 235347, "author": "Javier Lozano", "author_id": 16016, "author_profile": "https://Stackoverflow.com/users/16016", "pm_score": 6, "selected": true, "text": "<p>Here's what you want to do, first define your route map:</p>\n\n<pre><code>routes.MapRoute(\n \"Users\",\n \"{username}\", \n new { controller = \"User\", action=\"index\", username=\"\"});\n</code></pre>\n\n<p>What this allows you to do is to setup the following convention:</p>\n\n<ul>\n<li>Controller: User (the UserController type)</li>\n<li>Action: Index (this is mapped to the Index method of UserController)</li>\n<li>Username: This is the parameter for the Index method</li>\n</ul>\n\n<p>So when you request the url <strong>http://mydomain.com/javier</strong> this will be translated to the call for <strong>UserController.Index(string username)</strong> where <strong>username</strong> is set to the value of <em>javier</em>.</p>\n\n<p>Now since you're planning on using the MembershipProvider classes, you want to something more like this:</p>\n\n<pre><code> public ActionResult Index(MembershipUser usr)\n {\n ViewData[\"Welcome\"] = \"Viewing \" + usr.UserName;\n\n return View();\n }\n</code></pre>\n\n<p>In order to do this, you will need to use a ModelBinder to do the work of, well, binding from a username to a MembershipUser type. To do this, you will need to create your own ModelBinder type and apply it to the user parameter of the Index method. Your class can look something like this:</p>\n\n<pre><code>public class UserBinder : IModelBinder\n{\n public ModelBinderResult BindModel(ModelBindingContext bindingContext)\n {\n var request = bindingContext.HttpContext.Request;\n var username = request[\"username\"];\n MembershipUser user = Membership.GetUser(username);\n\n return new ModelBinderResult(user);\n }\n}\n</code></pre>\n\n<p>This allows you to change the declaration of the Index method to be:</p>\n\n<pre><code>public ActionResult Index([ModelBinder(typeof(UserBinder))] \n MembershipUser usr)\n{\n ViewData[\"Welcome\"] = \"Viewing \" + usr.Username;\n return View();\n}\n</code></pre>\n\n<p>As you can see, we've applied the <strong>[ModelBinder(typeof(UserBinder))]</strong> attribute to the method's parameter. This means that before your method is called the logic of your <strong>UserBinder</strong> type will be called so by the time the method gets called you will have a valid instance of your MembershipUser type.</p>\n" }, { "answer_id": 575692, "author": "Steve T", "author_id": 415, "author_profile": "https://Stackoverflow.com/users/415", "pm_score": 4, "selected": false, "text": "<p>You might want to consider not allowing usernames of certain types if you want to have some other functional controllers like Account, Admin, Profile, Settings, etc. Also you might want your static content not to trigger the \"username\" route. In order to achieve that kind of functionality (similar to how twitter urls are processed) you could use the following Routes:</p>\n\n<pre><code>// do not route the following\nroutes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\nroutes.IgnoreRoute(\"content/{*pathInfo}\"); \nroutes.IgnoreRoute(\"images/{*pathInfo}\");\n\n// route the following based on the controller constraints\nroutes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n , new { controller = @\"(admin|help|profile|settings)\" } // Constraints\n);\n\n// this will catch the remaining allowed usernames\nroutes.MapRoute(\n \"Users\",\n \"{username}\",\n new { controller = \"Users\", action = \"View\", username = \"\" }\n);\n</code></pre>\n\n<p>Then you will need to have a controller for each of the tokens in the constraint string (e.g. admin, help, profile, settings), as well as a controller named Users, and of course the default controller of Home in this example.</p>\n\n<p>If you have a lot of usernames you don't want to allow, then you might consider a more dynamic approach by creating a custom route handler.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12442/" ]
I am trying to create a route with a Username... So the URL would be mydomain.com/abrudtkhul (abrudtkhul being the username) My application will have public profiles based on usernames (Ex: <http://delicious.com/abrudtkuhl>). I want to replicate this URL scheme. How can I structure this in ASP.Net MVC? I am using Membership/Roles Providers too.
Here's what you want to do, first define your route map: ``` routes.MapRoute( "Users", "{username}", new { controller = "User", action="index", username=""}); ``` What this allows you to do is to setup the following convention: * Controller: User (the UserController type) * Action: Index (this is mapped to the Index method of UserController) * Username: This is the parameter for the Index method So when you request the url **http://mydomain.com/javier** this will be translated to the call for **UserController.Index(string username)** where **username** is set to the value of *javier*. Now since you're planning on using the MembershipProvider classes, you want to something more like this: ``` public ActionResult Index(MembershipUser usr) { ViewData["Welcome"] = "Viewing " + usr.UserName; return View(); } ``` In order to do this, you will need to use a ModelBinder to do the work of, well, binding from a username to a MembershipUser type. To do this, you will need to create your own ModelBinder type and apply it to the user parameter of the Index method. Your class can look something like this: ``` public class UserBinder : IModelBinder { public ModelBinderResult BindModel(ModelBindingContext bindingContext) { var request = bindingContext.HttpContext.Request; var username = request["username"]; MembershipUser user = Membership.GetUser(username); return new ModelBinderResult(user); } } ``` This allows you to change the declaration of the Index method to be: ``` public ActionResult Index([ModelBinder(typeof(UserBinder))] MembershipUser usr) { ViewData["Welcome"] = "Viewing " + usr.Username; return View(); } ``` As you can see, we've applied the **[ModelBinder(typeof(UserBinder))]** attribute to the method's parameter. This means that before your method is called the logic of your **UserBinder** type will be called so by the time the method gets called you will have a valid instance of your MembershipUser type.
235,146
<p>I need to replace the standard Overflow function in a ToolStrip to a "More..." button which would then pop up a menu with the overflowed items. Does anyone have any ideas about how to accomplish this?</p>
[ { "answer_id": 235277, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "<p>You can trap the paint event on the button by calling</p>\n\n<pre><code>toolStrip1.OverflowButton.Paint += new PaintEventHandler(OverflowButton_Paint);\n</code></pre>\n\n<p>Which in theory should allow you to make it say \"More...\", but I was unable to set the width of the Overflow Button to be anything but the (narrow) default width.</p>\n\n<p>Also, another idea was that you can trap <code>VisibleChanged</code> on the OverflowButton then manually inject a split button into the toolstrip. The tricky part is figuring out where to put that button.</p>\n" }, { "answer_id": 254364, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 3, "selected": true, "text": "<p>I wrote something very similar to this awhile ago. The code I used is pasted below, and you are free to modify it to suit your needs. </p>\n\n<p>The ToolStripCustomiseMenuItem is basically your \"More\" button that populates a DropDown Context Menu when clicked. Hope this helps you, at the very least this should be a good starting point…</p>\n\n<pre><code> public class ToolStripCustomiseMenuItem : ToolStripDropDownButton {\n public ToolStripCustomiseMenuItem()\n : base(\"Add Remove Buttons\") {\n this.Overflow = ToolStripItemOverflow.Always;\n DropDown = CreateCheckImageContextMenuStrip();\n }\n\n ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip();\n internal ContextMenuStrip CreateCheckImageContextMenuStrip() {\n ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip();\n checkImageContextMenuStrip.ShowCheckMargin = true;\n checkImageContextMenuStrip.ShowImageMargin = true;\n checkImageContextMenuStrip.Closing += new ToolStripDropDownClosingEventHandler(checkImageContextMenuStrip_Closing);\n checkImageContextMenuStrip.Opening += new CancelEventHandler(checkImageContextMenuStrip_Opening);\n DropDownOpening += new EventHandler(ToolStripAddRemoveMenuItem_DropDownOpening);\n return checkImageContextMenuStrip;\n }\n\n void checkImageContextMenuStrip_Opening(object sender, CancelEventArgs e) {\n\n }\n\n void ToolStripAddRemoveMenuItem_DropDownOpening(object sender, EventArgs e) {\n DropDownItems.Clear();\n if (this.Owner == null) return;\n foreach (ToolStripItem ti in Owner.Items) {\n if (ti is ToolStripSeparator) continue;\n if (ti == this) continue;\n MyToolStripCheckedMenuItem itm = new MyToolStripCheckedMenuItem(ti);\n itm.Checked = ti.Visible;\n DropDownItems.Add(itm);\n }\n }\n\n void checkImageContextMenuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e) {\n if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) {\n e.Cancel = true;\n }\n }\n}\n\ninternal class MyToolStripCheckedMenuItem : ToolStripMenuItem {\n ToolStripItem tsi;\n public MyToolStripCheckedMenuItem(ToolStripItem tsi)\n : base(tsi.Text) {\n this.tsi = tsi;\n this.Image = tsi.Image;\n this.CheckOnClick = true;\n this.CheckState = CheckState.Checked;\n CheckedChanged += new EventHandler(MyToolStripCheckedMenuItem_CheckedChanged);\n }\n\n void MyToolStripCheckedMenuItem_CheckedChanged(object sender, EventArgs e) {\n tsi.Visible = this.Checked;\n }\n\n}\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
I need to replace the standard Overflow function in a ToolStrip to a "More..." button which would then pop up a menu with the overflowed items. Does anyone have any ideas about how to accomplish this?
I wrote something very similar to this awhile ago. The code I used is pasted below, and you are free to modify it to suit your needs. The ToolStripCustomiseMenuItem is basically your "More" button that populates a DropDown Context Menu when clicked. Hope this helps you, at the very least this should be a good starting point… ``` public class ToolStripCustomiseMenuItem : ToolStripDropDownButton { public ToolStripCustomiseMenuItem() : base("Add Remove Buttons") { this.Overflow = ToolStripItemOverflow.Always; DropDown = CreateCheckImageContextMenuStrip(); } ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip(); internal ContextMenuStrip CreateCheckImageContextMenuStrip() { ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip(); checkImageContextMenuStrip.ShowCheckMargin = true; checkImageContextMenuStrip.ShowImageMargin = true; checkImageContextMenuStrip.Closing += new ToolStripDropDownClosingEventHandler(checkImageContextMenuStrip_Closing); checkImageContextMenuStrip.Opening += new CancelEventHandler(checkImageContextMenuStrip_Opening); DropDownOpening += new EventHandler(ToolStripAddRemoveMenuItem_DropDownOpening); return checkImageContextMenuStrip; } void checkImageContextMenuStrip_Opening(object sender, CancelEventArgs e) { } void ToolStripAddRemoveMenuItem_DropDownOpening(object sender, EventArgs e) { DropDownItems.Clear(); if (this.Owner == null) return; foreach (ToolStripItem ti in Owner.Items) { if (ti is ToolStripSeparator) continue; if (ti == this) continue; MyToolStripCheckedMenuItem itm = new MyToolStripCheckedMenuItem(ti); itm.Checked = ti.Visible; DropDownItems.Add(itm); } } void checkImageContextMenuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e) { if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) { e.Cancel = true; } } } internal class MyToolStripCheckedMenuItem : ToolStripMenuItem { ToolStripItem tsi; public MyToolStripCheckedMenuItem(ToolStripItem tsi) : base(tsi.Text) { this.tsi = tsi; this.Image = tsi.Image; this.CheckOnClick = true; this.CheckState = CheckState.Checked; CheckedChanged += new EventHandler(MyToolStripCheckedMenuItem_CheckedChanged); } void MyToolStripCheckedMenuItem_CheckedChanged(object sender, EventArgs e) { tsi.Visible = this.Checked; } } ```
235,148
<p>I'm currently on chapter 4 of Real World Haskell, and I'm trying to wrap my head around <a href="http://book.realworldhaskell.org/read/functional-programming.html#x_E9" rel="noreferrer">implementing foldl in terms of foldr</a>.</p> <p>(Here's their code:)</p> <pre><code>myFoldl :: (a -&gt; b -&gt; a) -&gt; a -&gt; [b] -&gt; a myFoldl f z xs = foldr step id xs z where step x g a = g (f a x) </code></pre> <p>I thought I'd try to implement <code>zip</code> using the same technique, but I don't seem to be making any progress. Is it even possible?</p>
[ { "answer_id": 235207, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 3, "selected": false, "text": "<p>I found a way using quite similar method to yours:</p>\n\n<pre><code>myzip = foldr step (const []) :: [a] -&gt; [b] -&gt; [(a,b)]\n where step a f (b:bs) = (a,b):(f bs)\n step a f [] = []\n</code></pre>\n" }, { "answer_id": 235208, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 5, "selected": true, "text": "<pre><code>zip2 xs ys = foldr step done xs ys\n where done ys = []\n step x zipsfn [] = []\n step x zipsfn (y:ys) = (x, y) : (zipsfn ys)\n</code></pre>\n\n<p>How this works: (foldr step done xs) returns a function that consumes\nys; so we go down the xs list building up a nested composition of\nfunctions that will each be applied to the corresponding part of ys.</p>\n\n<p>How to come up with it: I started with the general idea (from similar\nexamples seen before), wrote</p>\n\n<pre><code>zip2 xs ys = foldr step done xs ys\n</code></pre>\n\n<p>then filled in each of the following lines in turn with what it had to\nbe to make the types and values come out right. It was easiest to\nconsider the simplest cases first before the harder ones.</p>\n\n<p>The first line could be written more simply as</p>\n\n<pre><code>zip2 = foldr step done\n</code></pre>\n\n<p>as mattiast showed.</p>\n" }, { "answer_id": 235242, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 3, "selected": false, "text": "<p>For the non-native Haskellers here, I've written a Scheme version of this algorithm to make it clearer what's actually happening:</p>\n\n<pre><code>&gt; (define (zip lista listb)\n ((foldr (lambda (el func)\n (lambda (a)\n (if (empty? a)\n empty\n (cons (cons el (first a)) (func (rest a))))))\n (lambda (a) empty)\n lista) listb))\n&gt; (zip '(1 2 3 4) '(5 6 7 8))\n(list (cons 1 5) (cons 2 6) (cons 3 7) (cons 4 8))\n</code></pre>\n\n<p>The <code>foldr</code> results in a function which, when applied to a list, will return the zip of the list folded over with the list given to the function. The Haskell hides the inner <code>lambda</code> because of lazy evaluation.</p>\n\n<hr>\n\n<p>To break it down further:</p>\n\n<p>Take zip on input: '(1 2 3)\nThe foldr func gets called with</p>\n\n<pre><code>el-&gt;3, func-&gt;(lambda (a) empty)\n</code></pre>\n\n<p>This expands to:</p>\n\n<pre><code>(lambda (a) (cons (cons el (first a)) (func (rest a))))\n(lambda (a) (cons (cons 3 (first a)) ((lambda (a) empty) (rest a))))\n</code></pre>\n\n<p>If we were to return this now, we'd have a function which takes a list of one element\nand returns the pair (3 element):</p>\n\n<pre><code>&gt; (define f (lambda (a) (cons (cons 3 (first a)) ((lambda (a) empty) (rest a)))))\n&gt; (f (list 9))\n(list (cons 3 9))\n</code></pre>\n\n<p>Continuing, foldr now calls func with</p>\n\n<pre><code>el-&gt;3, func-&gt;f ;using f for shorthand\n(lambda (a) (cons (cons el (first a)) (func (rest a))))\n(lambda (a) (cons (cons 2 (first a)) (f (rest a))))\n</code></pre>\n\n<p>This is a func which takes a list with two elements, now, and zips them with <code>(list 2 3)</code>:</p>\n\n<pre><code>&gt; (define g (lambda (a) (cons (cons 2 (first a)) (f (rest a)))))\n&gt; (g (list 9 1))\n(list (cons 2 9) (cons 3 1))\n</code></pre>\n\n<p>What's happening? </p>\n\n<pre><code>(lambda (a) (cons (cons 2 (first a)) (f (rest a))))\n</code></pre>\n\n<p><code>a</code>, in this case, is <code>(list 9 1)</code></p>\n\n<pre><code>(cons (cons 2 (first (list 9 1))) (f (rest (list 9 1))))\n(cons (cons 2 9) (f (list 1)))\n</code></pre>\n\n<p>And, as you recall, <code>f</code> zips its argument with <code>3</code>.</p>\n\n<p>And this continues etc...</p>\n" }, { "answer_id": 26285107, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 4, "selected": false, "text": "<p>The answer had already been given here, but not an (illustrative) derivation. So even after all these years, perhaps it's worth adding it. </p>\n\n<p>It is actually quite simple. First,</p>\n\n<pre>\nfoldr f z xs \n = foldr f z [x1,x2,x3,...,xn] = f x1 <b>(foldr f z [x2,x3,...,xn])</b>\n = ... = f x1 <b>(f x2 (f x3 (... (f xn z) ...)))</b>\n</pre>\n\n<p>hence by eta-expansion,</p>\n\n<pre>\nfoldr f z xs ys\n = foldr f z [x1,x2,x3,...,xn] ys = f x1 (foldr f z [x2,x3,...,xn]) ys\n = ... = f x1 <b>(f x2 (f x3 (... (f xn z) ...)))</b> ys\n</pre>\n\n<p>As is apparent here, <em>if <code>f</code> is non-forcing in its 2nd argument</em>, it gets to work <em>first</em> on <code>x1</code> and <code>ys</code>, <code>f x1</code><strong><code>r1</code></strong><code>ys</code> where <code>r1 =</code><strong><code>(f x2 (f x3 (... (f xn z) ...)))</code></strong><code>= foldr f z [x2,x3,...,xn]</code>.</p>\n\n<p>So, using </p>\n\n<pre>\nf x1 <b>r1</b> [] = []\nf x1 <b>r1</b> (y1:ys1) = (x1,y1) : <b>r1</b> ys1\n</pre>\n\n<p>we arrange for passage of information <em>left-to-right</em> along the list, by <em>calling</em> <strong><code>r1</code></strong> with the <em>rest</em> of the input list <code>ys1</code>, <strong><code>foldr f z [x2,x3,...,xn]</code></strong><code>ys1 = f x2</code><strong><code>r2</code></strong><code>ys1</code>, as the next step. And that's that.</p>\n\n<hr>\n\n<p>When <code>ys</code> is shorter than <code>xs</code> (or the same length), the <code>[]</code> case for <code>f</code> fires and the processing stops. But if <code>ys</code> is longer than <code>xs</code> then <code>f</code>'s <code>[]</code> case won't fire and we'll get to the final <code>f xn</code><strong><code>z</code></strong><code>(yn:ysn)</code> application,</p>\n\n<pre>\nf xn <b>z</b> (yn:ysn) = (xn,yn) : <b>z</b> ysn\n</pre>\n\n<p>Since we've reached the end of <code>xs</code>, the <em><code>zip</code></em> processing must stop:</p>\n\n<pre>\n<b>z</b> _ = []\n</pre>\n\n<p>And this means the definition <code>z = const []</code> should be used:</p>\n\n<pre><code>zip xs ys = foldr f (const []) xs ys\n where\n f x r [] = []\n f x r (y:ys) = (x,y) : r ys\n</code></pre>\n\n<p>From the standpoint of <code>f</code>, <code>r</code> plays the role of a <em>success continuation</em>, which <code>f</code> calls when the processing is to continue, after having emitted the pair <code>(x,y)</code>. </p>\n\n<p>So <code>r</code> is <em>\"what is done with more <code>ys</code> when there are more <code>x</code>s\"</em>, and <code>z = const []</code>, the <em><code>nil</code></em>-case in <code>foldr</code>, is <em>\"what is done with <code>ys</code> when there are no more <code>x</code>s\"</em>. Or <code>f</code> can stop by itself, returning <code>[]</code> when <code>ys</code> is exhausted.</p>\n\n<hr>\n\n<p>Notice how <code>ys</code> is used as a kind of accumulating value, which is passed from left to right along the list <code>xs</code>, from one invocation of <code>f</code> to the next (\"accumulating\" step being, here, stripping a head element from it). </p>\n\n<p><a href=\"https://wiki.haskell.org/Foldl_as_foldr_alternative\" rel=\"noreferrer\">Naturally</a> this corresponds to the left fold, where an accumulating step is \"applying the function\", with <code>z = id</code> returning the final accumulated value when \"there are no more <code>x</code>s\":</p>\n\n<pre><code>foldl f a xs =~ foldr (\\x r a-&gt; r (f a x)) id xs a\n</code></pre>\n\n<p>Similarly, for finite lists,</p>\n\n<pre><code>foldr f a xs =~ foldl (\\r x a-&gt; r (f x a)) id xs a\n</code></pre>\n\n<p>And since the combining function gets to decide whether to continue or not, it is now possible to have left fold that can stop early:</p>\n\n<pre><code>foldlWhile t f a xs = foldr cons id xs a\n where \n cons x r a = if t x then r (f a x) else a\n</code></pre>\n\n<p>or a skipping left fold, <code>foldlWhen t ...</code>, with </p>\n\n<pre><code> cons x r a = if t x then r (f a x) else r a\n</code></pre>\n\n<p>etc.</p>\n" }, { "answer_id": 34744061, "author": "Mirzhan Irkegulov", "author_id": 596361, "author_profile": "https://Stackoverflow.com/users/596361", "pm_score": 2, "selected": false, "text": "<p>I tried to understand this elegant solution myself, so I tried to derive the types and evaluation myself. So, we need to write a function:</p>\n\n<pre><code>zip xs ys = foldr step done xs ys\n</code></pre>\n\n<p>Here we need to derive <code>step</code> and <code>done</code>, whatever they are. Recall <a href=\"http://hackage.haskell.org/package/base-4.8.1.0/docs/Data-List.html#v:foldr\" rel=\"nofollow noreferrer\"><code>foldr</code></a>'s type, instantiated to lists:</p>\n\n<pre><code>foldr :: (a -&gt; state -&gt; state) -&gt; state -&gt; [a] -&gt; state\n</code></pre>\n\n<p>However our <code>foldr</code> invocation must be instantiated to something like below, because we must accept not one, but two list arguments:</p>\n\n<pre><code>foldr :: (a -&gt; ? -&gt; ?) -&gt; ? -&gt; [a] -&gt; [b] -&gt; [(a,b)]\n</code></pre>\n\n<p>Because <code>-&gt;</code> is <a href=\"https://stackoverflow.com/q/34720928/596361\">right-associative</a>, this is equivalent to:</p>\n\n<pre><code>foldr :: (a -&gt; ? -&gt; ?) -&gt; ? -&gt; [a] -&gt; ([b] -&gt; [(a,b)])\n</code></pre>\n\n<p>Our <code>([b] -&gt; [(a,b)])</code> corresponds to <code>state</code> type variable in the original <code>foldr</code> type signature, therefore we must replace every occurrence of <code>state</code> with it:</p>\n\n<pre><code>foldr :: (a -&gt; ([b] -&gt; [(a,b)]) -&gt; ([b] -&gt; [(a,b)]))\n -&gt; ([b] -&gt; [(a,b)])\n -&gt; [a]\n -&gt; ([b] -&gt; [(a,b)])\n</code></pre>\n\n<p>This means that arguments that we pass to <code>foldr</code> must have the following types:</p>\n\n<pre><code>step :: a -&gt; ([b] -&gt; [(a,b)]) -&gt; [b] -&gt; [(a,b)]\ndone :: [b] -&gt; [(a,b)]\nxs :: [a]\nys :: [b]\n</code></pre>\n\n<p>Recall that <code>foldr (+) 0 [1,2,3]</code> expands to:</p>\n\n<pre><code>1 + (2 + (3 + 0))\n</code></pre>\n\n<p>Therefore if <code>xs = [1,2,3]</code> and <code>ys = [4,5,6,7]</code>, our <code>foldr</code> invocation would expand to:</p>\n\n<pre><code>1 `step` (2 `step` (3 `step` done)) $ [4,5,6,7]\n</code></pre>\n\n<p>This means that our <code>1 `step` (2 `step` (3 `step` done))</code> construct must create a recursive function that would go through <code>[4,5,6,7]</code> and zip up the elements. (Keep in mind, that if one of the original lists is longer, the excess values are thrown away). IOW, our construct must have the type <code>[b] -&gt; [(a,b)]</code>.</p>\n\n<p><code>3 `step` done</code> is our base case, where <code>done</code> is an initial value, like <code>0</code> in <code>foldr (+) 0 [1..3]</code>. We don't want to zip anything after 3, because 3 is the final value of <code>xs</code>, so we must terminate the recursion. How do you terminate the recursion over list in the base case? You return empty list <code>[]</code>. But recall <code>done</code> type signature:</p>\n\n<pre><code>done :: [b] -&gt; [(a,b)]\n</code></pre>\n\n<p>Therefore we can't return just <code>[]</code>, we must return a function that would ignore whatever it receives. Therefore use <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:const\" rel=\"nofollow noreferrer\"><code>const</code></a>:</p>\n\n<pre><code>done = const [] -- this is equivalent to done = \\_ -&gt; []\n</code></pre>\n\n<p>Now let's start figuring out what <code>step</code> should be. It combines a value of type <code>a</code> with a function of type <code>[b] -&gt; [(a,b)]</code> and returns a function of type <code>[b] -&gt; [(a,b)]</code>.</p>\n\n<p>In <code>3 `step` done</code>, we know that the result value that would later go to our zipped list must be <code>(3,6)</code> (knowing from original <code>xs</code> and <code>ys</code>). Therefore <code>3 `step` done</code> must evaluate into:</p>\n\n<pre><code>\\(y:ys) -&gt; (3,y) : done ys\n</code></pre>\n\n<p>Remember, we must return a function, inside which we somehow zip up the elements, the above code is what makes sense and typechecks.</p>\n\n<p>Now that we assumed how exactly <code>step</code> should evaluate, let's continue the evaluation. Here's how all reduction steps in our <code>foldr</code> evaluation look like:</p>\n\n<pre><code>3 `step` done -- becomes\n(\\(y:ys) -&gt; (3,y) : done ys)\n2 `step` (\\(y:ys) -&gt; (3,y) : done ys) -- becomes\n(\\(y:ys) -&gt; (2,y) : (\\(y:ys) -&gt; (3,y) : done ys) ys)\n1 `step` (\\(y:ys) -&gt; (2,y) : (\\(y:ys) -&gt; (3,y) : done ys) ys) -- becomes\n(\\(y:ys) -&gt; (1,y) : (\\(y:ys) -&gt; (2,y) : (\\(y:ys) -&gt; (3,y) : done ys) ys) ys)\n</code></pre>\n\n<p>The evaluation gives rise to this implementation of step (note that we account for <code>ys</code> running out of elements early by returning an empty list):</p>\n\n<pre><code>step x f = \\[] -&gt; []\nstep x f = \\(y:ys) -&gt; (x,y) : f ys\n</code></pre>\n\n<p>Thus, the full function <code>zip</code> is implemented as follows:</p>\n\n<pre><code>zip :: [a] -&gt; [b] -&gt; [(a,b)]\nzip xs ys = foldr step done xs ys\n where done = const []\n step x f [] = []\n step x f (y:ys) = (x,y) : f ys\n</code></pre>\n\n<p>P.S.: If you are inspired by elegance of folds, read <a href=\"https://stackoverflow.com/a/28754327/596361\"><em>Writing foldl using foldr</em></a> and then Graham Hutton's <a href=\"http://www.cs.nott.ac.uk/~gmh/fold.pdf\" rel=\"nofollow noreferrer\"><em>A tutorial on the universality and expressiveness of fold</em></a>.</p>\n" }, { "answer_id": 42542733, "author": "Zemyla", "author_id": 4416280, "author_profile": "https://Stackoverflow.com/users/4416280", "pm_score": 3, "selected": false, "text": "<p>The problem with all these solutions for <code>zip</code> is that they only fold over one list or the other, which can be a problem if both of them are \"good producers\", in the parlance of list fusion. What you actually need is a solution that folds over both lists. Fortunately, there is a paper about exactly that, called <a href=\"https://arxiv.org/pdf/1309.5135.pdf\" rel=\"noreferrer\">\"Coroutining Folds with Hyperfunctions\"</a>.</p>\n\n<p>You need an auxiliary type, a hyperfunction, which is basically a function that takes another hyperfunction as its argument.</p>\n\n<pre><code>newtype H a b = H { invoke :: H b a -&gt; b }\n</code></pre>\n\n<p>The hyperfunctions used here basically act like a \"stack\" of ordinary functions.</p>\n\n<pre><code>push :: (a -&gt; b) -&gt; H a b -&gt; H a b\npush f q = H $ \\k -&gt; f $ invoke k q\n</code></pre>\n\n<p>You also need a way to put two hyperfunctions together, end to end.</p>\n\n<pre><code>(.#.) :: H b c -&gt; H a b -&gt; H a c\nf .#. g = H $ \\k -&gt; invoke f $ g .#. k\n</code></pre>\n\n<p>This is related to <code>push</code> by the law:</p>\n\n<pre><code>(push f x) .#. (push g y) = push (f . g) (x .#. y)\n</code></pre>\n\n<p>This turns out to be an associative operator, and this is the identity:</p>\n\n<pre><code>self :: H a a\nself = H $ \\k -&gt; invoke k self\n</code></pre>\n\n<p>You also need something that disregards everything else on the \"stack\" and returns a specific value:</p>\n\n<pre><code>base :: b -&gt; H a b\nbase b = H $ const b\n</code></pre>\n\n<p>And finally, you need a way to get a value out of a hyperfunction:</p>\n\n<pre><code>run :: H a a -&gt; a\nrun q = invoke q self\n</code></pre>\n\n<p><code>run</code> strings all of the <code>push</code>ed functions together, end to end, until it hits a <code>base</code> or loops infinitely.</p>\n\n<p>So now you can fold both lists into hyperfunctions, using functions that pass information from one to the other, and assemble the final value.</p>\n\n<pre><code>zip xs ys = run $ foldr (\\x h -&gt; push (first x) h) (base []) xs .#. foldr (\\y h -&gt; push (second y) h) (base Nothing) ys where\n first _ Nothing = []\n first x (Just (y, xys)) = (x, y):xys\n\n second y xys = Just (y, xys)\n</code></pre>\n\n<p>The reason why folding over both lists matters is because of something GHC does called <em>list fusion</em>, which is talked about in <a href=\"http://hackage.haskell.org/package/base-4.9.0.0/docs/src/GHC.Base.html#build\" rel=\"noreferrer\">the GHC.Base module</a>, but probably should be much more well-known. Being a good list producer and using <code>build</code> with <code>foldr</code> can prevent lots of useless production and immediate consumption of list elements, and can expose further optimizations.</p>\n" }, { "answer_id": 47565981, "author": "guthrie", "author_id": 593975, "author_profile": "https://Stackoverflow.com/users/593975", "pm_score": 0, "selected": false, "text": "<p>A simple approach:</p>\n\n<pre><code>lZip, rZip :: Foldable t =&gt; [b] -&gt; t a -&gt; [(a, b)]\n\n-- implement zip using fold?\nlZip xs ys = reverse.fst $ foldl f ([],xs) ys\n where f (zs, (y:ys)) x = ((x,y):zs, ys)\n\n-- Or;\nrZip xs ys = fst $ foldr f ([],reverse xs) ys\n where f x (zs, (y:ys)) = ((x,y):zs, ys)\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
I'm currently on chapter 4 of Real World Haskell, and I'm trying to wrap my head around [implementing foldl in terms of foldr](http://book.realworldhaskell.org/read/functional-programming.html#x_E9). (Here's their code:) ``` myFoldl :: (a -> b -> a) -> a -> [b] -> a myFoldl f z xs = foldr step id xs z where step x g a = g (f a x) ``` I thought I'd try to implement `zip` using the same technique, but I don't seem to be making any progress. Is it even possible?
``` zip2 xs ys = foldr step done xs ys where done ys = [] step x zipsfn [] = [] step x zipsfn (y:ys) = (x, y) : (zipsfn ys) ``` How this works: (foldr step done xs) returns a function that consumes ys; so we go down the xs list building up a nested composition of functions that will each be applied to the corresponding part of ys. How to come up with it: I started with the general idea (from similar examples seen before), wrote ``` zip2 xs ys = foldr step done xs ys ``` then filled in each of the following lines in turn with what it had to be to make the types and values come out right. It was easiest to consider the simplest cases first before the harder ones. The first line could be written more simply as ``` zip2 = foldr step done ``` as mattiast showed.
235,156
<p>I'd like to know if it is possible to redirect StreamWriter output to a variable</p> <p>Something like</p> <pre><code>String^ myString; StreamWriter sw = gcnew StreamWriter([somehow specify myString]) sw-&gt;WriteLine("Foo"); </code></pre> <p>then myString will contain Foo. The reason I would like to do this is to reuse a complex function. I should probably refactor it into a String returning function but it still would be a nice hack to know</p>
[ { "answer_id": 235183, "author": "Matt Ellis", "author_id": 29306, "author_profile": "https://Stackoverflow.com/users/29306", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx\" rel=\"noreferrer\">StreamWriter</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.io.stringwriter.aspx\" rel=\"noreferrer\">StringWriter</a> both extend TextWriter, perhaps you could refactor your method that uses StreamWriter to use TextWriter instead so it could write to either a stream or a string?</p>\n" }, { "answer_id": 235189, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": -1, "selected": false, "text": "<p>Refactor the method to return string as you mentioned you could. Hacking it the way you are attempting, while academically interesting, will muddy the code and make it very hard to maintain for anyone that follows you.</p>\n" }, { "answer_id": 235194, "author": "Ely", "author_id": 30488, "author_profile": "https://Stackoverflow.com/users/30488", "pm_score": 6, "selected": false, "text": "<p>You can do this with a StringWriter writing the value directly to a string builder object</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\n// now, the StringWriter instance 'sw' will write to 'sb'\n</code></pre>\n" }, { "answer_id": 16556418, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Try out this code =]</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\nstring s = sb.ToString(); &lt;-- Now it will be a string.\n</code></pre>\n" }, { "answer_id": 29679597, "author": "Pascal Ganaye", "author_id": 964743, "author_profile": "https://Stackoverflow.com/users/964743", "pm_score": 4, "selected": false, "text": "<p>You should be able to do what you need using a Memory Stream.</p>\n\n<pre><code>MemoryStream mem = new MemoryStream(); \nStreamWriter sw = new StreamWriter(mem);\nsw.WriteLine(\"Foo\"); \n// then later you should be able to get your string.\n// this is in c# but I am certain you can do something of the sort in C++\nString result = System.Text.Encoding.UTF8.GetString(mem.ToArray(), 0, (int) mem.Length);\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367/" ]
I'd like to know if it is possible to redirect StreamWriter output to a variable Something like ``` String^ myString; StreamWriter sw = gcnew StreamWriter([somehow specify myString]) sw->WriteLine("Foo"); ``` then myString will contain Foo. The reason I would like to do this is to reuse a complex function. I should probably refactor it into a String returning function but it still would be a nice hack to know
[StreamWriter](http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx) and [StringWriter](http://msdn.microsoft.com/en-us/library/system.io.stringwriter.aspx) both extend TextWriter, perhaps you could refactor your method that uses StreamWriter to use TextWriter instead so it could write to either a stream or a string?
235,166
<p>I'm trying to add parameters to an objectDataSource at runtime like this:</p> <pre><code> Parameter objCustomerParameter = new Parameter("CustomerID", DbType.String, customerID); Parameter objGPDatabaseParameter = new Parameter("Database", DbType.String, gpDatabase); //set up object data source parameters objCustomer.SelectParameters["CustomerID"] = objCustomerParameter; objCustomer.SelectParameters["Database"] = objGPDatabaseParameter; </code></pre> <p>At what point in the objectDataSource lifecycle should these parameters be added (what event)? Also, some values are coming from a master page property (which loads <em>after</em> the page_load of the page containing the objectDataSource).</p>
[ { "answer_id": 235217, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 2, "selected": false, "text": "<p>Add as early as possible; at the <code>PreInit</code> event. This is part of initialization so should be done there.</p>\n\n<p>See the <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow noreferrer\">ASP.NET Page Life Cycle Overview</a> for more information.</p>\n" }, { "answer_id": 236420, "author": "Andy C.", "author_id": 28541, "author_profile": "https://Stackoverflow.com/users/28541", "pm_score": 6, "selected": true, "text": "<p>Add them to the event for the operation you are trying to use. For example, if these parameters are part of the SELECT command then add them to the Selecting event, if they need to go with the UPDATE command then add them on the Updating event.</p>\n\n<p>The ObjectDataSource raises an event before it performs each operation, that's when you can insert parameters (or validate/alter existing parameters).</p>\n\n<p>Also, don't try and modify the parameters collection of the ODS itself. You want to add your parameters to the ObjectDataSourceSelectingEventArgs that is passed to the event handler.</p>\n\n<p>Something like:</p>\n\n<pre><code>e.InputParameters[\"CustomerID\"] = customerId;\ne.InputParameters[\"database\"] = dbName;\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874/" ]
I'm trying to add parameters to an objectDataSource at runtime like this: ``` Parameter objCustomerParameter = new Parameter("CustomerID", DbType.String, customerID); Parameter objGPDatabaseParameter = new Parameter("Database", DbType.String, gpDatabase); //set up object data source parameters objCustomer.SelectParameters["CustomerID"] = objCustomerParameter; objCustomer.SelectParameters["Database"] = objGPDatabaseParameter; ``` At what point in the objectDataSource lifecycle should these parameters be added (what event)? Also, some values are coming from a master page property (which loads *after* the page\_load of the page containing the objectDataSource).
Add them to the event for the operation you are trying to use. For example, if these parameters are part of the SELECT command then add them to the Selecting event, if they need to go with the UPDATE command then add them on the Updating event. The ObjectDataSource raises an event before it performs each operation, that's when you can insert parameters (or validate/alter existing parameters). Also, don't try and modify the parameters collection of the ODS itself. You want to add your parameters to the ObjectDataSourceSelectingEventArgs that is passed to the event handler. Something like: ``` e.InputParameters["CustomerID"] = customerId; e.InputParameters["database"] = dbName; ```
235,191
<p>What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY:</p> <pre><code>map.connect('/logs/', controller='logs', action='logs') map.connect('/logs', controller='logs', action='logs') </code></pre> <p>I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?</p>
[ { "answer_id": 235238, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 4, "selected": true, "text": "<p>There are two possible ways to solve this:</p>\n\n<ol>\n<li><a href=\"http://wiki.pylonshq.com/display/pylonscookbook/Adding+trailing+slash+to+pages+automatically\" rel=\"nofollow noreferrer\">Do it entirely in pylons</a>.</li>\n<li><a href=\"http://enarion.net/web/apache/htaccess/trailing-slash/\" rel=\"nofollow noreferrer\">Add an htaccess rule to rewrite the trailing slash</a>.</li>\n</ol>\n\n<p>Personally I don't like the trailing slash, because if you have a uri like:</p>\n\n<p><a href=\"http://example.com/people\" rel=\"nofollow noreferrer\">http://example.com/people</a></p>\n\n<p>You should be able to get the same data in xml format by going to:</p>\n\n<p><a href=\"http://example.com/people.xml\" rel=\"nofollow noreferrer\">http://example.com/people.xml</a></p>\n" }, { "answer_id": 975529, "author": "AML", "author_id": 120520, "author_profile": "https://Stackoverflow.com/users/120520", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.siafoo.net/snippet/275\" rel=\"nofollow noreferrer\">http://www.siafoo.net/snippet/275</a> has a basic piece of middleware which removes a trailing slash from requests. Clever idea, and I understood the concept of middleware in WSGI applications much better after I realised what this does.</p>\n" }, { "answer_id": 1441104, "author": "Marius Gedminas", "author_id": 110151, "author_profile": "https://Stackoverflow.com/users/110151", "pm_score": 4, "selected": false, "text": "<p>The following snippet added as the very last route worked for me:</p>\n\n<pre><code>map.redirect('/*(url)/', '/{url}',\n _redirect_code='301 Moved Permanently')\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12981/" ]
What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY: ``` map.connect('/logs/', controller='logs', action='logs') map.connect('/logs', controller='logs', action='logs') ``` I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?
There are two possible ways to solve this: 1. [Do it entirely in pylons](http://wiki.pylonshq.com/display/pylonscookbook/Adding+trailing+slash+to+pages+automatically). 2. [Add an htaccess rule to rewrite the trailing slash](http://enarion.net/web/apache/htaccess/trailing-slash/). Personally I don't like the trailing slash, because if you have a uri like: <http://example.com/people> You should be able to get the same data in xml format by going to: <http://example.com/people.xml>
235,233
<p>Derik Whitaker posted an <a href="http://devlicio.us/blogs/derik_whittaker/archive/2008/10/22/how-is-interacting-with-your-data-repository-in-your-controller-different-or-better-than-doing-it-in-your-code-behind.aspx" rel="noreferrer">article</a> a couple of days ago that hit a point that I've been curious about for some time: <strong>should business logic exist in controllers?</strong></p> <p>So far all the ASP.NET MVC demos I've seen put repository access and business logic in the controller. Some even throw validation in there as well. This results in fairly large, bloated controllers. Is this really the way to use the MVC framework? It seems that this is just going to end up with a lot of duplicated code and logic spread out across different controllers.</p>
[ { "answer_id": 235243, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 7, "selected": true, "text": "<p>Business logic should really be in the model. You should be aiming for fat models, skinny controllers.</p>\n\n<p>For example, instead of having:</p>\n\n<pre><code>public interface IOrderService{\n int CalculateTotal(Order order);\n}\n</code></pre>\n\n<p>I would rather have:</p>\n\n<pre><code>public class Order{\n int CalculateTotal(ITaxService service){...} \n}\n</code></pre>\n\n<p>This assumes that tax is calculate by an external service, and requires your model to know about interfaces to your external services.</p>\n\n<p>This would make your controller look something like:</p>\n\n<pre><code>public class OrdersController{\n public OrdersController(ITaxService taxService, IOrdersRepository ordersRepository){...}\n\n public void Show(int id){\n ViewData[\"OrderTotal\"] = ordersRepository.LoadOrder(id).CalculateTotal(taxService);\n }\n}\n</code></pre>\n\n<p>Or something like that.</p>\n" }, { "answer_id": 458976, "author": "Joe Soul-bringer", "author_id": 56279, "author_profile": "https://Stackoverflow.com/users/56279", "pm_score": 4, "selected": false, "text": "<p>This is a fascinating question. </p>\n\n<p>I think that its interesting that a large number of sample MVC applications actually fail to follow the MVC paradigm in the sense of truly placing the \"business logic\" entirely in the model. Martin Fowler has pointed out that MVC is not a pattern in the sense of the Gang Of Four. Rather, it is paradigm that the programmer must add patterns <em>to</em> if they are creating something beyond a toy app. </p>\n\n<p>So, the short answer is that \"business logic\" should indeed not live in the controller, since the controller has the added function of dealing with the view and user interactions and we want to create objects with only one purpose. </p>\n\n<p>A longer answer is that you need to put some thought into the design of your model layer before just moving logic from controller to model. Perhaps you can handle all of app logic using REST, in which case the model's design should be fairly clear. If not, you should know what approach you are going to use to keep your model from becoming bloated. </p>\n" }, { "answer_id": 5696798, "author": "Leniel Maccaferri", "author_id": 114029, "author_profile": "https://Stackoverflow.com/users/114029", "pm_score": 4, "selected": false, "text": "<p>You can check this awesome tutorial by Stephen Walther that shows <a href=\"http://www.asp.net/mvc/tutorials/validating-with-a-service-layer-cs\" rel=\"noreferrer\">Validating with a Service Layer</a>.</p>\n\n<blockquote>\n <p>Learn how to move your validation\n logic out of your controller actions\n and into a separate service layer. In\n this tutorial, Stephen Walther\n explains how you can maintain a sharp\n separation of concerns by isolating\n your service layer from your\n controller layer.</p>\n</blockquote>\n" }, { "answer_id": 11531022, "author": "AlejandroR", "author_id": 120007, "author_profile": "https://Stackoverflow.com/users/120007", "pm_score": 6, "selected": false, "text": "<p>I like the diagram presented by <a href=\"https://msdn.microsoft.com/en-us/library/hh404093.aspx\" rel=\"noreferrer\">Microsoft Patterns &amp; Practices</a>. And I believe in the adage 'A picture is worth a thousand words'.</p>\n\n<p><img src=\"https://i.stack.imgur.com/VqqTF.jpg\" alt=\"Diagram shows architecture of MVC and business sevices layers\"></p>\n" }, { "answer_id": 18486080, "author": "Jacek Glen", "author_id": 1565633, "author_profile": "https://Stackoverflow.com/users/1565633", "pm_score": 3, "selected": false, "text": "<p>Business Logic should not be contained in controllers. Controllers should be as skinny as possible, ideally follow the patter:</p>\n\n<ol>\n<li>Find domain entity</li>\n<li>Act on domain entity</li>\n<li>Prepare data for view / return results</li>\n</ol>\n\n<p>Additionally controllers can contain some application logic.</p>\n\n<p>So where do I put my business logic? In Model.</p>\n\n<p>What is Model? Now that's a good question. Please see <a href=\"http://msdn.microsoft.com/en-us/library/hh404093.aspx\">Microsoft Patterns and Practices article</a> (kudos to AlejandroR for excellent find). In here there are three categories of models:</p>\n\n<ul>\n<li><strong>View Model</strong>: This is simply a data bag, with minimal, if any, logic to pass data from and to views, contains basic field validation.</li>\n<li><strong>Domain Model</strong>: Fat model with business logic, operates on a single or multiple data entities (i.e. entity A in a given state than action on entity B)</li>\n<li><strong>Data Model</strong>: Storage-aware model, logic contained within a single entity relates only to that entity (i.e. if field a then field b)</li>\n</ul>\n\n<p>Of course, MVC is a paradigm that comes in different varieties. What I describe here is MVC occupying top layer only, vide <a href=\"http://en.wikipedia.org/wiki/Multitier_architecture#Comparison_with_the_MVC_architecture\">this article on Wikipedia</a></p>\n\n<blockquote>\n <p>Today, MVC and similar model-view-presenter (MVP) are Separation of Concerns design patterns that apply exclusively to the presentation layer of a larger system. In simple scenarios MVC may represent the primary design of a system, reaching directly into the database; however, in most scenarios the Controller and Model in MVC have a loose dependency on either a Service or Data layer/tier. This is all about Client-Server architecture</p>\n</blockquote>\n" }, { "answer_id": 24208924, "author": "chandresh patel", "author_id": 2838540, "author_profile": "https://Stackoverflow.com/users/2838540", "pm_score": -1, "selected": false, "text": "<p>If u use Dependency Injectors your business logic will go to them and hence you will get neat and clean controllers.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
Derik Whitaker posted an [article](http://devlicio.us/blogs/derik_whittaker/archive/2008/10/22/how-is-interacting-with-your-data-repository-in-your-controller-different-or-better-than-doing-it-in-your-code-behind.aspx) a couple of days ago that hit a point that I've been curious about for some time: **should business logic exist in controllers?** So far all the ASP.NET MVC demos I've seen put repository access and business logic in the controller. Some even throw validation in there as well. This results in fairly large, bloated controllers. Is this really the way to use the MVC framework? It seems that this is just going to end up with a lot of duplicated code and logic spread out across different controllers.
Business logic should really be in the model. You should be aiming for fat models, skinny controllers. For example, instead of having: ``` public interface IOrderService{ int CalculateTotal(Order order); } ``` I would rather have: ``` public class Order{ int CalculateTotal(ITaxService service){...} } ``` This assumes that tax is calculate by an external service, and requires your model to know about interfaces to your external services. This would make your controller look something like: ``` public class OrdersController{ public OrdersController(ITaxService taxService, IOrdersRepository ordersRepository){...} public void Show(int id){ ViewData["OrderTotal"] = ordersRepository.LoadOrder(id).CalculateTotal(taxService); } } ``` Or something like that.
235,240
<p>Recently, <a href="https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception">I made a post about the developers I'm working with not using try catch blocks properly</a>, and unfortuantely using try... catch blocks in critical situations and ignoring the exception error all together. causing me major heart ache. Here is an example of one of the several thousand sections of code that they did this (some code left out that doesn't particuarly matter:</p> <pre><code>public void AddLocations(BOLocation objBllLocations) { try { dbManager.Open(); if (objBllLocations.StateID != 0) { // about 20 Paramters added to dbManager here } else { // about 19 Paramters added here } dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "ULOCATIONS.AddLocations"); } catch (Exception ex) { } finally { dbManager.Dispose(); } } </code></pre> <p>This is absolutely discusting, in my eyes, and does not notify the user in case some potential problem occurred. I know many people say that OOP is evil, and that adding multiple layers adds to the number of lines of code and to the complexity of the program, leading to possible issues with code maintainence. Much of my programming background, I personally, have taken almost the same approach in this area. Below I have listed out a basic structure of the way I normally code in such a situation, and I've been doing this accross many languages in my career, but this particular code is in C#. But the code below is a good basic idea of how I use the Objects, it seems to work for me, but since this is a good source of some fairly inteligent programming mines, I'd like to know If I should re-evaluate this technique that I've used for so many years. Mainly, because, in the next few weeks, i'm going to be plunging into the not so good code from the outsourced developers and modifying huge sections of code. i'd like to do it as well as possible. sorry for the long code reference. </p> <pre><code>// ******************************************************************************************* /// &lt;summary&gt; /// Summary description for BaseBusinessObject /// &lt;/summary&gt; /// &lt;remarks&gt; /// Base Class allowing me to do basic function on a Busines Object /// &lt;/remarks&gt; public class BaseBusinessObject : Object, System.Runtime.Serialization.ISerializable { public enum DBCode { DBUnknownError, DBNotSaved, DBOK } // private fields, public properties public int m_id = -1; public int ID { get { return m_id; } set { m_id = value; } } private int m_errorCode = 0; public int ErrorCode { get { return m_errorCode; } set { m_errorCode = value; } } private string m_errorMsg = ""; public string ErrorMessage { get { return m_errorMsg; } set { m_errorMsg = value; } } private Exception m_LastException = null; public Exception LastException { get { return m_LastException; } set { m_LastException = value;} } //Constructors public BaseBusinessObject() { Initialize(); } public BaseBusinessObject(int iID) { Initialize(); FillByID(iID); } // methods protected void Initialize() { Clear(); Object_OnInit(); // Other Initializable code here } public void ClearErrors() { m_errorCode = 0; m_errorMsg = ""; m_LastException = null; } void System.Runtime.Serialization.ISerializable.GetObjectData( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { //Serialization code for Object must be implemented here } // overrideable methods protected virtual void Object_OnInit() { // User can override to add additional initialization stuff. } public virtual BaseBusinessObject FillByID(int iID) { throw new NotImplementedException("method FillByID Must be implemented"); } public virtual void Clear() { throw new NotImplementedException("method Clear Must be implemented"); } public virtual DBCode Save() { throw new NotImplementedException("method Save Must be implemented"); } } // ******************************************************************************************* /// &lt;summary&gt; /// Example Class that might be based off of a Base Business Object /// &lt;/summary&gt; /// &lt;remarks&gt; /// Class for holding all the information about a Customer /// &lt;/remarks&gt; public class BLLCustomer : BaseBusinessObject { // *************************************** // put field members here other than the ID private string m_name = ""; public string Name { get { return m_name; } set { m_name = value; } } public override void Clear() { m_id = -1; m_name = ""; } public override BaseBusinessObject FillByID(int iID) { Clear(); try { // usually accessing a DataLayerObject, //to select a database record } catch (Exception Ex) { Clear(); LastException = Ex; // I can have many different exception, this is usually an enum ErrorCode = 3; ErrorMessage = "Customer couldn't be loaded"; } return this; } public override DBCode Save() { DBCode ret = DBCode.DBUnknownError; try { // usually accessing a DataLayerObject, //to save a database record ret = DBCode.DBOK; } catch (Exception Ex) { LastException = Ex; // I can have many different exception, this is usually an enum // i do not usually use just a General Exeption ErrorCode = 3; ErrorMessage = "some really weird error happened, customer not saved"; ret = DBCode.DBNotSaved; } return ret; } } // ******************************************************************************************* // Example of how it's used on an asp page.. protected void Page_Load(object sender, EventArgs e) { // Simplifying this a bit, normally, I'd use something like, // using some sort of static "factory" method // BaseObject.NewBusinessObject(typeof(BLLCustomer)).FillByID(34); BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34); if (cust.ErrorCode != 0) { // There was an error.. Error message is in //cust.ErrorMessage // some sort of internal error code is in //cust.ErrorCode // Give the users some sort of message through and asp:Label.. // probably based off of cust.ErrorMessage //log can be handled in the data, business layer... or whatever lab.ErrorText = cust.ErrorMessage; } else { // continue using the object, to fill in text boxes, // literals or whatever. this.labID = cust.ID.toString(); this.labCompName = cust.Name; } } </code></pre> <p>Bottom line, my question is, Am I over complicating things with the muliple layers, and the inherited classes or is my old concept illustrated still working good and stable? Is there a better way now a days to accomplish these things? Should I go to just making straight SQL calls from the asp.net page code behind pages as fellow work associate developer suggested (though that last solution makes me feel icky), instead of going through a business object, and data layer (data layer not shown, but basically holds all the stored proc calls). Yeah, another developer did ask me why i go through the effort of layering things, when you can just type what you need straight in a *.aspx.cs code behind page, and then I can have the joys of over 1k lines of code behind. What is some advice here?</p>
[ { "answer_id": 235301, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": true, "text": "<p>Have you considered using an ORM like NHibernate? There's no point in re-inventing the wheel.</p>\n\n<p>To me this is a code smell:</p>\n\n<pre><code>BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34);\n</code></pre>\n\n<p>Too many brackets!</p>\n\n<p>I've found that using the active record pattern in a language like C# always ends in tears because it's hard(er) to unit test.</p>\n" }, { "answer_id": 235456, "author": "Magnus Lindhe", "author_id": 966, "author_profile": "https://Stackoverflow.com/users/966", "pm_score": 0, "selected": false, "text": "<p>Why not just catch the exception in the Page_Load event? Some exception you might expect and know how to deal with, other exceptions should be handled by a global exception handler. </p>\n" }, { "answer_id": 235495, "author": "Luke", "author_id": 327, "author_profile": "https://Stackoverflow.com/users/327", "pm_score": 1, "selected": false, "text": "<p>The jump from the first bit of code to the next is huge. Whether a complicated business object layer is necessary will depend on the size of the app in question. At the very least though our policy is that exceptions are logged where they are handled. How you present to the user is up to you but having logs is essential so that developers can get more information if necessary.</p>\n" }, { "answer_id": 235527, "author": "DancesWithBamboo", "author_id": 1334, "author_profile": "https://Stackoverflow.com/users/1334", "pm_score": 0, "selected": false, "text": "<p>My rule of thumb is to only catch errors that I can handle or give the user something useful so that if they do whatever it was they did again, it is likely to work for them. I catch database exceptions; but only to add some more information onto the error about the data being used; then I re-throw it. The best way to handle errors in general is to not catch them at all anywhere but at the top of the UI stack. Just having one page to handle the errors and using the global.asax to route to it handles almost all situations. Using status codes is definitely out of style all together. It is a remnant of COM.</p>\n" }, { "answer_id": 235985, "author": "Simon P", "author_id": 31387, "author_profile": "https://Stackoverflow.com/users/31387", "pm_score": 0, "selected": false, "text": "<p>Is it possible to use an abstract base class instead of a concrete class? this would force the implementation of your methods at development time rather than runtime exceptions.</p>\n\n<p>The best comment here to agree with is from dances, where you should only handle exceptions you can recover from at that point. Catching others and rethrowing is the best method (although i think its rarely done). Also, make sure they are logged.... :)</p>\n" }, { "answer_id": 236371, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 0, "selected": false, "text": "<p>YOur way of errorhandling seems very outdated. Just make a new exeption and inherit from exeption that way you have the callstack at least. Then you should log with something like nlog or log4net. And this is the year 2008 so use generics. You will have to do a lot less casting that way.</p>\n\n<p>ANd use an ORM like someone said before. Don't try to reinvent the wheel. </p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
Recently, [I made a post about the developers I'm working with not using try catch blocks properly](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception), and unfortuantely using try... catch blocks in critical situations and ignoring the exception error all together. causing me major heart ache. Here is an example of one of the several thousand sections of code that they did this (some code left out that doesn't particuarly matter: ``` public void AddLocations(BOLocation objBllLocations) { try { dbManager.Open(); if (objBllLocations.StateID != 0) { // about 20 Paramters added to dbManager here } else { // about 19 Paramters added here } dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "ULOCATIONS.AddLocations"); } catch (Exception ex) { } finally { dbManager.Dispose(); } } ``` This is absolutely discusting, in my eyes, and does not notify the user in case some potential problem occurred. I know many people say that OOP is evil, and that adding multiple layers adds to the number of lines of code and to the complexity of the program, leading to possible issues with code maintainence. Much of my programming background, I personally, have taken almost the same approach in this area. Below I have listed out a basic structure of the way I normally code in such a situation, and I've been doing this accross many languages in my career, but this particular code is in C#. But the code below is a good basic idea of how I use the Objects, it seems to work for me, but since this is a good source of some fairly inteligent programming mines, I'd like to know If I should re-evaluate this technique that I've used for so many years. Mainly, because, in the next few weeks, i'm going to be plunging into the not so good code from the outsourced developers and modifying huge sections of code. i'd like to do it as well as possible. sorry for the long code reference. ``` // ******************************************************************************************* /// <summary> /// Summary description for BaseBusinessObject /// </summary> /// <remarks> /// Base Class allowing me to do basic function on a Busines Object /// </remarks> public class BaseBusinessObject : Object, System.Runtime.Serialization.ISerializable { public enum DBCode { DBUnknownError, DBNotSaved, DBOK } // private fields, public properties public int m_id = -1; public int ID { get { return m_id; } set { m_id = value; } } private int m_errorCode = 0; public int ErrorCode { get { return m_errorCode; } set { m_errorCode = value; } } private string m_errorMsg = ""; public string ErrorMessage { get { return m_errorMsg; } set { m_errorMsg = value; } } private Exception m_LastException = null; public Exception LastException { get { return m_LastException; } set { m_LastException = value;} } //Constructors public BaseBusinessObject() { Initialize(); } public BaseBusinessObject(int iID) { Initialize(); FillByID(iID); } // methods protected void Initialize() { Clear(); Object_OnInit(); // Other Initializable code here } public void ClearErrors() { m_errorCode = 0; m_errorMsg = ""; m_LastException = null; } void System.Runtime.Serialization.ISerializable.GetObjectData( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { //Serialization code for Object must be implemented here } // overrideable methods protected virtual void Object_OnInit() { // User can override to add additional initialization stuff. } public virtual BaseBusinessObject FillByID(int iID) { throw new NotImplementedException("method FillByID Must be implemented"); } public virtual void Clear() { throw new NotImplementedException("method Clear Must be implemented"); } public virtual DBCode Save() { throw new NotImplementedException("method Save Must be implemented"); } } // ******************************************************************************************* /// <summary> /// Example Class that might be based off of a Base Business Object /// </summary> /// <remarks> /// Class for holding all the information about a Customer /// </remarks> public class BLLCustomer : BaseBusinessObject { // *************************************** // put field members here other than the ID private string m_name = ""; public string Name { get { return m_name; } set { m_name = value; } } public override void Clear() { m_id = -1; m_name = ""; } public override BaseBusinessObject FillByID(int iID) { Clear(); try { // usually accessing a DataLayerObject, //to select a database record } catch (Exception Ex) { Clear(); LastException = Ex; // I can have many different exception, this is usually an enum ErrorCode = 3; ErrorMessage = "Customer couldn't be loaded"; } return this; } public override DBCode Save() { DBCode ret = DBCode.DBUnknownError; try { // usually accessing a DataLayerObject, //to save a database record ret = DBCode.DBOK; } catch (Exception Ex) { LastException = Ex; // I can have many different exception, this is usually an enum // i do not usually use just a General Exeption ErrorCode = 3; ErrorMessage = "some really weird error happened, customer not saved"; ret = DBCode.DBNotSaved; } return ret; } } // ******************************************************************************************* // Example of how it's used on an asp page.. protected void Page_Load(object sender, EventArgs e) { // Simplifying this a bit, normally, I'd use something like, // using some sort of static "factory" method // BaseObject.NewBusinessObject(typeof(BLLCustomer)).FillByID(34); BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34); if (cust.ErrorCode != 0) { // There was an error.. Error message is in //cust.ErrorMessage // some sort of internal error code is in //cust.ErrorCode // Give the users some sort of message through and asp:Label.. // probably based off of cust.ErrorMessage //log can be handled in the data, business layer... or whatever lab.ErrorText = cust.ErrorMessage; } else { // continue using the object, to fill in text boxes, // literals or whatever. this.labID = cust.ID.toString(); this.labCompName = cust.Name; } } ``` Bottom line, my question is, Am I over complicating things with the muliple layers, and the inherited classes or is my old concept illustrated still working good and stable? Is there a better way now a days to accomplish these things? Should I go to just making straight SQL calls from the asp.net page code behind pages as fellow work associate developer suggested (though that last solution makes me feel icky), instead of going through a business object, and data layer (data layer not shown, but basically holds all the stored proc calls). Yeah, another developer did ask me why i go through the effort of layering things, when you can just type what you need straight in a \*.aspx.cs code behind page, and then I can have the joys of over 1k lines of code behind. What is some advice here?
Have you considered using an ORM like NHibernate? There's no point in re-inventing the wheel. To me this is a code smell: ``` BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34); ``` Too many brackets! I've found that using the active record pattern in a language like C# always ends in tears because it's hard(er) to unit test.
235,248
<p>In Silverlight how can I launch / navigate to another page?</p>
[ { "answer_id": 235253, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 4, "selected": true, "text": "<pre><code>System.Windows.Browser.HtmlPage.Window.Navigate(\n new Uri( \"http://www.google.com\" ),\n \"_blank\"\n );\n</code></pre>\n\n<p>You can leave out the target (\"_blank\") if you just want to navigate within your current browser window.</p>\n" }, { "answer_id": 6353036, "author": "Philip K. Adetiloye", "author_id": 706454, "author_profile": "https://Stackoverflow.com/users/706454", "pm_score": 2, "selected": false, "text": "<p>To navigate to another page in from another page.</p>\n\n<pre><code>Frame frame =this.parent as Frame;\nframe.navigate(new Uri(\"/Views/Details.xaml\"),Uri.Relative);\n</code></pre>\n\n<p>Note, you must have a frame already in the MainPage.xaml.\nSo other pages are just calling the frame in the parent</p>\n" }, { "answer_id": 6806639, "author": "Ernest Poletaev", "author_id": 771098, "author_profile": "https://Stackoverflow.com/users/771098", "pm_score": 1, "selected": false, "text": "<p>Assume You are editing code behind file of Page class</p>\n\n<pre><code>this.NavigationService.Navigate(new Uri(\"/OtherPage.xaml\", UriKind.Relative));\n</code></pre>\n" }, { "answer_id": 7668913, "author": "Mr. Bungle", "author_id": 325442, "author_profile": "https://Stackoverflow.com/users/325442", "pm_score": 1, "selected": false, "text": "<p>To avoid issues with popups being blocked when you use _blank, ensure you call Navigate from the click event of a HyperlinkButton control, as described here:</p>\n\n<p><a href=\"http://www.tjsblog.net/2010/10/20/opening-a-new-chrome-page-in-silverlight/\" rel=\"nofollow\">http://www.tjsblog.net/2010/10/20/opening-a-new-chrome-page-in-silverlight/</a></p>\n" }, { "answer_id": 15001687, "author": "user2045883", "author_id": 2045883, "author_profile": "https://Stackoverflow.com/users/2045883", "pm_score": 0, "selected": false, "text": "<p>You all can also try this </p>\n\n<pre><code>this.content=new (place the page name which You want to navigate);\n\n but this code only works while navigate page having in same folder else You have to write like in given below manner\n</code></pre>\n\n<p>this.Content = new Views.(place the page name which You want to navigate);</p>\n\n<pre><code> here in place of Views write the folder name where the page having...\n</code></pre>\n\n<p>Hope it's also helpful for you all.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
In Silverlight how can I launch / navigate to another page?
``` System.Windows.Browser.HtmlPage.Window.Navigate( new Uri( "http://www.google.com" ), "_blank" ); ``` You can leave out the target ("\_blank") if you just want to navigate within your current browser window.
235,254
<p>I am running GNU Emacs on Windows so entering:</p> <pre><code>M-x shell </code></pre> <p>launches the Windows command-line DOS shell. However, I would like to instead be able to run the Cygwin Bash Shell (or any other non-Windows shell) from within Emacs. How can this be easily done?</p>
[ { "answer_id": 235344, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 3, "selected": false, "text": "<p>I use XEmacs with Cygwin, and can run bash from XEmacs relatively easily.</p>\n\n<p>Here's the relevant section from <code>init.el</code></p>\n\n<pre><code>;; Let's use CYGWIN bash...\n;;\n(setq binary-process-input t) \n(setq w32-quote-process-args ?\\\") \n(setq shell-file-name \"bash\") ;; or sh if you rename your bash executable to sh. \n(setenv \"SHELL\" shell-file-name) \n(setq explicit-shell-file-name shell-file-name) \n(setq explicit-sh-args '(\"-login\" \"-i\"))\n</code></pre>\n" }, { "answer_id": 235356, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 6, "selected": true, "text": "<p><code>shell-file-name</code> is the variable that controls which shell Emacs uses when it wants to run a shell command.</p>\n\n<p><code>explicit-shell-file-name</code> is the variable that controls which shell <code>M-x shell</code> starts up.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/235254/how-can-i-run-cygwin-bash-shell-from-within-emacs#235344\">Ken's answer</a> changes both of those, which you may or may not want.</p>\n\n<p>You can also have a function that starts a different shell by temporarily changing <code>explicit-shell-file-name</code>:</p>\n\n<pre><code>(defun cygwin-shell ()\n \"Run cygwin bash in shell mode.\"\n (interactive)\n (let ((explicit-shell-file-name \"C:/cygwin/bin/bash\"))\n (call-interactively 'shell)))\n</code></pre>\n\n<p>You will probably also want to pass the <code>--login</code> argument to bash, because you're starting a new Cygwin session. You can do that by setting <code>explicit-bash-args</code>. (Note that <code>M-x shell</code> uses <code>explicit-</code>PROGRAM<code>-args</code>, where PROGRAM is the filename part of the shell's pathname. This is why you should not include the <code>.exe</code> when setting the shell.</p>\n" }, { "answer_id": 339026, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 2, "selected": false, "text": "<p>You can run bash directly from the default Windows command-line shell within your Emacs *shell* buffer:</p>\n\n<pre><code>Microsoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\n\nC:\\temp&gt;bash\nbash \n</code></pre>\n\n<p>However, no command prompt is visible which can be disorienting resulting in your commands and their output results all blending together. </p>\n\n<p>In addition, for some unknown reason, if you do enter a command and hit return, a return line character (\\r) is appended to the end of your command statement causing a bash error:</p>\n\n<pre><code>ls\nbash: line 1: $'ls\\r': command not found\n</code></pre>\n\n<p>A workaround is to manually add a comment character (#) at the end of every command which effectively comments out the \\r text:</p>\n\n<pre><code>ls #\nmyfile,txt\nfoo.bar\nanotherfile.txt\n</code></pre>\n\n<p>This overall approach is far from ideal but might be useful if you want to drop into bash from Windows' native shell to do some quick operations and then exit out to continue working in Windows.</p>\n" }, { "answer_id": 862947, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>One more important hint on this subject.</p>\n\n<p>If you use Emacs shell mode and want both bash and cmd sometimes, set it up to use bash by default, because you can type cmd at bash and the resulting dos shell works just fine.</p>\n\n<p>If you setup Emacs to use cmd as the shell (which is the way NT emacs installs), then dos shell works fine, but if you type bash or bash -i to run a bash shell, the resulting shell doesn't work right - see answer 0.</p>\n\n<p>But it works fine if bash is the \"first\" shell emacs invokes.</p>\n" }, { "answer_id": 1304975, "author": "Inno", "author_id": 97118, "author_profile": "https://Stackoverflow.com/users/97118", "pm_score": 1, "selected": false, "text": "<p>Since these approaches didn't work for me I got it the following way:</p>\n\n<p>(I'm using NTEmacs which opens a dos shell by default, so perhaps your emacs behaves the same)</p>\n\n<p>Create a windows environment variable named SHELL ('SHELL' not '$SHELL') and give it the path to bash.exe of your cygwin installation (for example c:\\programs\\cygwin\\bin\\bash.exe)</p>\n\n<p>Now when doing M-x shell it opens a bash.</p>\n\n<p>Regards,</p>\n\n<p>Inno</p>\n" }, { "answer_id": 2164491, "author": "Yoo", "author_id": 37664, "author_profile": "https://Stackoverflow.com/users/37664", "pm_score": 2, "selected": false, "text": "<p>I'm using EmacsW32. <code>C-h a shell$</code> gives a list of shell launching commands and the commands cmd-shell and cygwin-shell look interesting. Both commands need EmacsW32. They are also found in the menu: <strong>Tools > W&amp;32 Shells</strong>.</p>\n\n<p>If you run cygwin-shell for the first time, and if you have not setup cygwin path in Emacs, it leads you to the Customization page where you can setup the cygwin path by pressing Find button.</p>\n" }, { "answer_id": 8748674, "author": "Chris Jones", "author_id": 107357, "author_profile": "https://Stackoverflow.com/users/107357", "pm_score": 3, "selected": false, "text": "<p>The best solution I've found to this is the following:</p>\n\n<pre><code>;; When running in Windows, we want to use an alternate shell so we\n;; can be more unixy.\n(setq shell-file-name \"C:/MinGW/msys/1.0/bin/bash\")\n(setq explicit-shell-file-name shell-file-name)\n(setenv \"PATH\"\n (concat \".:/usr/local/bin:/mingw/bin:/bin:\"\n (replace-regexp-in-string \" \" \"\\\\\\\\ \"\n (replace-regexp-in-string \"\\\\\\\\\" \"/\"\n (replace-regexp-in-string \"\\\\([A-Za-z]\\\\):\" \"/\\\\1\"\n (getenv \"PATH\"))))))\n</code></pre>\n\n<p>The problem with passing \"--login\" as cjm <a href=\"https://stackoverflow.com/a/235356/107357\">suggests</a> is your shell will always start in your home directory. But if you're editing a file and you hit \"M-x shell\", you want your shell in that file's directory. Furthermore, I've tested this setup with \"M-x grep\" and \"M-x compile\". I'm suspicious that other examples here wouldn't work with those due to directory and PATH problems.</p>\n\n<p>This elisp snippet belongs in your ~/.emacs file. If you want to use Cygwin instead of MinGW, change the first string to C:/cygwin/bin/bash. The second string is prepended to your Windows PATH (after converting that PATH to an appropriately unixy form); in Cygwin you probably want \"~/bin:/usr/local/bin:/usr/bin:\" or something similar.</p>\n" }, { "answer_id": 13453672, "author": "mcheema", "author_id": 519057, "author_profile": "https://Stackoverflow.com/users/519057", "pm_score": 0, "selected": false, "text": "<p>In addition to @Chris Jones' answer about avoiding the --login argument to bash, I set the following command line arguments:</p>\n\n<pre><code> (setq explicit-bash-args '(\"--noediting\" \"-i\"))\n</code></pre>\n\n<p>The --noediting option prevents interference with the GNU readline library and the -i option specifies that the shell is interactive. I also use the .emacs_bash file in my home directory for any emacs specific bash customizations. </p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I am running GNU Emacs on Windows so entering: ``` M-x shell ``` launches the Windows command-line DOS shell. However, I would like to instead be able to run the Cygwin Bash Shell (or any other non-Windows shell) from within Emacs. How can this be easily done?
`shell-file-name` is the variable that controls which shell Emacs uses when it wants to run a shell command. `explicit-shell-file-name` is the variable that controls which shell `M-x shell` starts up. [Ken's answer](https://stackoverflow.com/questions/235254/how-can-i-run-cygwin-bash-shell-from-within-emacs#235344) changes both of those, which you may or may not want. You can also have a function that starts a different shell by temporarily changing `explicit-shell-file-name`: ``` (defun cygwin-shell () "Run cygwin bash in shell mode." (interactive) (let ((explicit-shell-file-name "C:/cygwin/bin/bash")) (call-interactively 'shell))) ``` You will probably also want to pass the `--login` argument to bash, because you're starting a new Cygwin session. You can do that by setting `explicit-bash-args`. (Note that `M-x shell` uses `explicit-`PROGRAM`-args`, where PROGRAM is the filename part of the shell's pathname. This is why you should not include the `.exe` when setting the shell.
235,272
<p>I'm probably doing this all wrong. I have a text file full of data and I want to match and replace patterns of "item" and "catalog number" that are in the file. But the order of each element in the file is very important, so I want to match/replace starting from the top of the file and then work my way down.</p> <p>The code snippet below actually works, but when I execute it, it replaces the third instance of the "SeaMonkey" &amp; "SMKY-1978" pattern and then it replaces the second instance of that pattern. What I'd like it to do is replace the first instance of the pattern and then the second.</p> <p>So I'd like the output to say "Found <strong>Kurt's</strong> SMKY-1978 SeaMonkeys" and then "Found <strong>Shane's</strong> SMKY-1978 SeaMonkeys" and then leave Mick's SMKY-1978 SeaMonkeys alone since I only want to find and replace the first 2 instances of the pattern. Right now it says "Found <strong>Shane's</strong> SMKY-1978 SeaMonkeys" and "Found <strong>Mick's</strong> SMKY-1978 SeaMonkeys" because it is matching the last pattern each time the for loop is executed.</p> <p>So am I missing a subtle little known regex character or am I just doing what I want to do completely and utterly wrong?</p> <p>Here is the working code:</p> <pre><code># my regexp matches from the bottom to the top but I'd like it to replace from the top down local $/=undef; my $DataToParse = &lt;DATA&gt;; my $item = "SeaMonkeys"; my $catNum = "SMKY-1978"; my $maxInstancesToReplace = 2; parseData(); exit(); sub parseData { for (my $counter = 0; $counter &lt; $maxInstancesToReplace; $counter++) { # Stick in a temporary text placeholder that I will replace later after more processing $DataToParse =~ s/(.+)\sELEMENT\s(.+?)\s\(Item := \"$item\".+?CatalogNumber := \"$catNum.+?END_ELEMENT(.+)/$1 ***** Found $2\'s $catNum $item. (counter: $counter) *****$3/s; } print("Here's the result:\n$DataToParse\n"); } __DATA__ ELEMENT Kurt (Item := "BrightLite", ItemID := 29, CatalogNumber := "BTLT-9274", Vendor := 100, END_ELEMENT ELEMENT Mick (Item := "PetRock", ItemID := 36, CatalogNumber := "PTRK-3475/A", Vendor := 82, END_ELEMENT ELEMENT Kurt (Item := "SeaMonkeys", ItemID := 12, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Joe (Item := "Pong", ItemID := 24, CatalogNumber := "PONG-1482", Vendor := 5, END_ELEMENT ELEMENT Shane (Item := "SeaMonkeys", ItemID := 1032, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Kurt (Item := "Battleship", ItemID := 99, CatalogNumber := "BTLS-5234", Vendor := 529, END_ELEMENT ELEMENT Mick (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1978/F", Vendor := 77, END_ELEMENT ELEMENT Frank (Item := "PetRock", ItemID := 42, CatalogNumber := "PTRK-3475/B", Vendor := 82, END_ELEMENT ELEMENT Joe (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1979/A", Vendor := 77, END_ELEMENT </code></pre> <p>And here is what it currently outputs:</p> <pre>Here's the result: ELEMENT Kurt (Item := "BrightLite", ItemID := 29, CatalogNumber := "BTLT-9274", Vendor := 100, END_ELEMENT ELEMENT Mick (Item := "PetRock", ItemID := 36, CatalogNumber := "PTRK-3475/A", Vendor := 82, END_ELEMENT ELEMENT Kurt (Item := "SeaMonkeys", ItemID := 12, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Joe (Item := "Pong", ItemID := 24, CatalogNumber := "PONG-1482", Vendor := 5, END_ELEMENT ***** Found Shane's SMKY-1978 SeaMonkeys. (counter: 1) ***** ELEMENT Kurt (Item := "Battleship", ItemID := 99, CatalogNumber := "BTLS-5234", Vendor := 529, END_ELEMENT ***** Found Mick's SMKY-1978 SeaMonkeys. (counter: 0) ***** ELEMENT Frank (Item := "PetRock", ItemID := 42, CatalogNumber := "PTRK-3475/B", Vendor := 82, END_ELEMENT ELEMENT Joe (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1979/A", Vendor := 77, END_ELEMENT</pre>
[ { "answer_id": 235300, "author": "Alexandr Ciornii", "author_id": 13467, "author_profile": "https://Stackoverflow.com/users/13467", "pm_score": 4, "selected": false, "text": "<p>.+ at start of your regex is \"greedy\". This means that it will match maximum chars.</p>\n\n<p>You regex is better written (it would be more readable and faster) as</p>\n\n<pre><code>my $re=qr/\\sELEMENT\\s(.+?)\\s\\(Item := \"$item\".+?CatalogNumber := \"$catNum.+?END_ELEMENT/;\n</code></pre>\n\n<p>I think that you can simply repeat this match:</p>\n\n<pre><code>sub parseData {\n my $re=qr/\\sELEMENT\\s(.+?)\\s\\(Item := \"$item\".+?CatalogNumber := \"$catNum.+?END_ELEMENT(.+)/;\n foreach my $counter (0..$maxInstancesToReplace) {\n # Stick in a temporary text placeholder that I will replace later after more processing\n $DataToParse =~ s/$re/ ***** Found $1\\'s $catNum $item. (counter: $counter) *****$2/s;\n } \n print(\"Here's the result:\\n$DataToParse\\n\");\n}\n</code></pre>\n\n<p>If repeating is not possible, you should use /e regex modifier.</p>\n" }, { "answer_id": 404552, "author": "Kurt W. Leucht", "author_id": 27687, "author_profile": "https://Stackoverflow.com/users/27687", "pm_score": -1, "selected": true, "text": "<p>The best solution appears to be to grab each ELEMENT ... END_ELEMENT section from the data and regex only one section at a time rather than feeding the whole complete data set to a regular expression at once. Not exactly what I was trying to accomplish, but I rewrote my program to do this piecemeal processing and it works like a charm. </p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27687/" ]
I'm probably doing this all wrong. I have a text file full of data and I want to match and replace patterns of "item" and "catalog number" that are in the file. But the order of each element in the file is very important, so I want to match/replace starting from the top of the file and then work my way down. The code snippet below actually works, but when I execute it, it replaces the third instance of the "SeaMonkey" & "SMKY-1978" pattern and then it replaces the second instance of that pattern. What I'd like it to do is replace the first instance of the pattern and then the second. So I'd like the output to say "Found **Kurt's** SMKY-1978 SeaMonkeys" and then "Found **Shane's** SMKY-1978 SeaMonkeys" and then leave Mick's SMKY-1978 SeaMonkeys alone since I only want to find and replace the first 2 instances of the pattern. Right now it says "Found **Shane's** SMKY-1978 SeaMonkeys" and "Found **Mick's** SMKY-1978 SeaMonkeys" because it is matching the last pattern each time the for loop is executed. So am I missing a subtle little known regex character or am I just doing what I want to do completely and utterly wrong? Here is the working code: ``` # my regexp matches from the bottom to the top but I'd like it to replace from the top down local $/=undef; my $DataToParse = <DATA>; my $item = "SeaMonkeys"; my $catNum = "SMKY-1978"; my $maxInstancesToReplace = 2; parseData(); exit(); sub parseData { for (my $counter = 0; $counter < $maxInstancesToReplace; $counter++) { # Stick in a temporary text placeholder that I will replace later after more processing $DataToParse =~ s/(.+)\sELEMENT\s(.+?)\s\(Item := \"$item\".+?CatalogNumber := \"$catNum.+?END_ELEMENT(.+)/$1 ***** Found $2\'s $catNum $item. (counter: $counter) *****$3/s; } print("Here's the result:\n$DataToParse\n"); } __DATA__ ELEMENT Kurt (Item := "BrightLite", ItemID := 29, CatalogNumber := "BTLT-9274", Vendor := 100, END_ELEMENT ELEMENT Mick (Item := "PetRock", ItemID := 36, CatalogNumber := "PTRK-3475/A", Vendor := 82, END_ELEMENT ELEMENT Kurt (Item := "SeaMonkeys", ItemID := 12, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Joe (Item := "Pong", ItemID := 24, CatalogNumber := "PONG-1482", Vendor := 5, END_ELEMENT ELEMENT Shane (Item := "SeaMonkeys", ItemID := 1032, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Kurt (Item := "Battleship", ItemID := 99, CatalogNumber := "BTLS-5234", Vendor := 529, END_ELEMENT ELEMENT Mick (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1978/F", Vendor := 77, END_ELEMENT ELEMENT Frank (Item := "PetRock", ItemID := 42, CatalogNumber := "PTRK-3475/B", Vendor := 82, END_ELEMENT ELEMENT Joe (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1979/A", Vendor := 77, END_ELEMENT ``` And here is what it currently outputs: ``` Here's the result: ELEMENT Kurt (Item := "BrightLite", ItemID := 29, CatalogNumber := "BTLT-9274", Vendor := 100, END_ELEMENT ELEMENT Mick (Item := "PetRock", ItemID := 36, CatalogNumber := "PTRK-3475/A", Vendor := 82, END_ELEMENT ELEMENT Kurt (Item := "SeaMonkeys", ItemID := 12, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Joe (Item := "Pong", ItemID := 24, CatalogNumber := "PONG-1482", Vendor := 5, END_ELEMENT ***** Found Shane's SMKY-1978 SeaMonkeys. (counter: 1) ***** ELEMENT Kurt (Item := "Battleship", ItemID := 99, CatalogNumber := "BTLS-5234", Vendor := 529, END_ELEMENT ***** Found Mick's SMKY-1978 SeaMonkeys. (counter: 0) ***** ELEMENT Frank (Item := "PetRock", ItemID := 42, CatalogNumber := "PTRK-3475/B", Vendor := 82, END_ELEMENT ELEMENT Joe (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1979/A", Vendor := 77, END_ELEMENT ```
The best solution appears to be to grab each ELEMENT ... END\_ELEMENT section from the data and regex only one section at a time rather than feeding the whole complete data set to a regular expression at once. Not exactly what I was trying to accomplish, but I rewrote my program to do this piecemeal processing and it works like a charm.
235,295
<p>Im trying to use to define a one-to-many relationship in a single table. For example lets say I have a Groups table with these entries:</p> <pre> Group: Group_1: name: Atlantic Records Group_2: name: Capital Records Group_3: name: Gnarls Barkley Group_4: name: Death Cab For Cutie Group_5: name: Coldplay Group_6: name: Management Company </pre> <p>The group Coldplay could be a child of the group Capital Records and a child of the group Management Company and Gnarls Barkley could only be a child of Atlantic Records.</p> <p>What is the best way to represent this relationship. I am using PHP and mySQL. Also I am using PHP-Doctrine as my ORM if that helps.</p> <p>I was thinking that I would need to create a linking table called group_groups that would have 2 columns. owner_id and group_id. However i'm not sure if that is best way to do this. </p> <p>Any insight would be appreciated. Let me know if I explained my problem good enough.</p>
[ { "answer_id": 235314, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 2, "selected": false, "text": "<p>A couple of options:</p>\n\n<p>Easiest: If each group can only have one parent, then you just need a \"ParentID\" field in the main table. </p>\n\n<p>If relationships can be more complex than that, then yes, you'd need some sort of linking table. Maybe even a \"relationship type\" column to define what <em>kind</em> of relationship between the two groups.</p>\n" }, { "answer_id": 235317, "author": "Totty", "author_id": 30838, "author_profile": "https://Stackoverflow.com/users/30838", "pm_score": -1, "selected": false, "text": "<p>Yes, you would need a bridge that contained the fields you described. However, I would think your table should be split if it is following the same type of entities as you describe.</p>\n" }, { "answer_id": 235329, "author": "Rami", "author_id": 8571, "author_profile": "https://Stackoverflow.com/users/8571", "pm_score": -1, "selected": false, "text": "<p>(I am assuming there is an id column which can be used for references).</p>\n\n<p>You can add a column called parent_id (allow nulls) and store the id of the parent group in it. Then you can join using sql like: \"Select a.<em>, b.</em> from group parent join group child on parent.id = child.parent_id\".</p>\n\n<p>I do recommend using a separate table for this link because:\n1. You cannot support multiple parents with a field. You have to use a separate table.\n2. Import/Export/Delete is way more difficult with a field in the table because you may run into key conflicts. For example, if you try to import data, you need to make sure that you first import the parents and then children. With a separate table, you can import all groups and then all relationships without worrying about the actual order of the data.</p>\n" }, { "answer_id": 235331, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 3, "selected": false, "text": "<p>There are a number of possible issues with this approach, but with a minimal understanding of the requirements, here goes:</p>\n\n<p>There appear to be really three 'entities' here: Artist/Band, Label/Recording Co. and Management Co.</p>\n\n<p>Artists/Bands can have a Label/Recording CO\nArtists/Bands can have a Management Co.</p>\n\n<p>Label/Recording Co can have multiple Artists/Bands</p>\n\n<p>Management Co can have multiple Artists/Bands</p>\n\n<p>So there are one-to-many relationships between Recording Co and Artists and between Management Co and Artists.</p>\n\n<p>Record each entity only once, in its own table, with a unique ID.</p>\n\n<p>Put the key of the \"one\" in each instance of the \"many\" - in this case, Artist/Band would have both a Recording Co ID and a Management Co ID</p>\n\n<p>Then your query will ultimately join Artist, Recording Co and Management Co.</p>\n\n<p>With this structure, you don't need intersection tables, there is a clear separation of \"entities\" and the query is relatively simple. </p>\n" }, { "answer_id": 235358, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 1, "selected": false, "text": "<p>In this particular instance, you would be wise to follow Ken G's advice, since it does indeed appear that you are modeling three separate entities in one table.</p>\n\n<p>In general, it is possible that this could come up -- If you had a \"person\" table and were modeling who everybody's friends were, for a contrived example.</p>\n\n<p>In this case, you would indeed have a \"linking\" or associative or marriage table to manage those relationships.</p>\n" }, { "answer_id": 235445, "author": "Mike Daniels", "author_id": 31339, "author_profile": "https://Stackoverflow.com/users/31339", "pm_score": 0, "selected": false, "text": "<p>I agree with Ken G and JohnMcG that you should separate Management and Labels. However they may be forgetting that a band can have multiple managers and/or multiple managers over a period of time. In that case you would need a many to many relationship.</p>\n\n<ul>\n<li>management has many bands</li>\n<li>band has many management</li>\n<li>label has many bands</li>\n<li>band has many labels</li>\n</ul>\n\n<p>In that case your orginal idea of using a relationship table is correct. That is home many-to-many relationships are done. However, group_groups could be named better. </p>\n\n<p>Ultimately it will depend on your requirements. For instance if you're storing CD titles then perhaps you would rather attach labels to a particular CD rather than a band.</p>\n" }, { "answer_id": 236603, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 0, "selected": false, "text": "<p>This does appear to be a conflation of STI (single-table inheritance) and nested sets / tree structures. Nested set/trees are one parent to multiple children:</p>\n\n<p><a href=\"http://jgeewax.wordpress.com/2006/07/18/hierarchical-data-side-note/\" rel=\"nofollow noreferrer\">http://jgeewax.wordpress.com/2006/07/18/hierarchical-data-side-note/</a></p>\n\n<p><a href=\"http://www.dbmsmag.com/9603d06.html\" rel=\"nofollow noreferrer\">http://www.dbmsmag.com/9603d06.html</a></p>\n\n<p><a href=\"http://www.sitepoint.com/article/hierarchical-data-database\" rel=\"nofollow noreferrer\">http://www.sitepoint.com/article/hierarchical-data-database</a></p>\n" }, { "answer_id": 363671, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I think best of all is to use NestedSet\n<a href=\"http://www.doctrine-project.org/documentation/manual/1_0/en/hierarchical-data#nested-set\" rel=\"nofollow noreferrer\">http://www.doctrine-project.org/documentation/manual/1_0/en/hierarchical-data#nested-set</a></p>\n\n<p>Just set actAs NestedSet</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31327/" ]
Im trying to use to define a one-to-many relationship in a single table. For example lets say I have a Groups table with these entries: ``` Group: Group_1: name: Atlantic Records Group_2: name: Capital Records Group_3: name: Gnarls Barkley Group_4: name: Death Cab For Cutie Group_5: name: Coldplay Group_6: name: Management Company ``` The group Coldplay could be a child of the group Capital Records and a child of the group Management Company and Gnarls Barkley could only be a child of Atlantic Records. What is the best way to represent this relationship. I am using PHP and mySQL. Also I am using PHP-Doctrine as my ORM if that helps. I was thinking that I would need to create a linking table called group\_groups that would have 2 columns. owner\_id and group\_id. However i'm not sure if that is best way to do this. Any insight would be appreciated. Let me know if I explained my problem good enough.
There are a number of possible issues with this approach, but with a minimal understanding of the requirements, here goes: There appear to be really three 'entities' here: Artist/Band, Label/Recording Co. and Management Co. Artists/Bands can have a Label/Recording CO Artists/Bands can have a Management Co. Label/Recording Co can have multiple Artists/Bands Management Co can have multiple Artists/Bands So there are one-to-many relationships between Recording Co and Artists and between Management Co and Artists. Record each entity only once, in its own table, with a unique ID. Put the key of the "one" in each instance of the "many" - in this case, Artist/Band would have both a Recording Co ID and a Management Co ID Then your query will ultimately join Artist, Recording Co and Management Co. With this structure, you don't need intersection tables, there is a clear separation of "entities" and the query is relatively simple.
235,360
<p>Today I had a discussion with a colleague about nested functions in Javascript:</p> <pre><code>function a() { function b() { alert('boo') } var c = 'Bound to local call object.' d = 'Bound to global object.' } </code></pre> <p>In this example, trials point out that b is not reachable outside the body of a, much like c is. However, d is - after executing a(). Looking for the exact definition of this behaviour in the <a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf" rel="noreferrer">ECMAScript v.3 standard </a>, I didn't find the exact wording I was looking for; what Sec.13 p.71 does not say, is which object the function object created by the function declaration statement is to be bound to. Am I missing something?</p>
[ { "answer_id": 235377, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>As I understand it, these are equivalent as far as scoping is concerned:</p>\n\n<pre><code>function a() { ... }\n</code></pre>\n\n<p>and</p>\n\n<pre><code>var a = function() { ... }\n</code></pre>\n" }, { "answer_id": 235381, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 6, "selected": true, "text": "<p>This is static scoping. Statements within a function are scoped within that function.</p>\n<p>Javascript has a quirky behavior, however, which is that without the <strong>var</strong> keyword, you've implied a <strong>global variable</strong>. That's what you're seeing in your test. Your &quot;d&quot; variable is available because it is an implied global, despite being written within the body of a function.</p>\n<p>Also, to answer the second part of your question: A function exists in whatever scope it is declared, just like a variable.</p>\n<p><strong>Sidenote:</strong>\nYou probably don't want global variables, especially not implied ones. It's recommended that you always use the var keyword, to prevent confusion and to keep everything clean.</p>\n<p><strong>Sidenote:</strong>\nThe ECMA Standard isn't probably the most helpful place to find answers about Javascript, although it certainly isn't a bad resource. Remember that javascript in your browser is just an implementation of that standard, so the standards document will be giving you the rules that were (mostly) followed by the implementors when the javascript engine was being built. It can't offer specific information about the implementations you care about, namely the major browsers. There are a couple of books in particular which will give you very direct information about how the javascript implementations in the major browsers behave. To illustrate the difference, I'll include excerpts below from both the ECMAScript specification, and a book on Javascript. I think you'll agree that the book gives a more direct answer.</p>\n<p>Here's from the <strong>ECMAScript Language Specification</strong>:</p>\n<blockquote>\n<p>10.2 <em>Entering An Execution Context</em></p>\n<p>Every function and constructor call\nenters a new execution context, even\nif a function is calling itself\nrecursively. Every return exits an\nexecution context. A thrown exception,\nif not caught, may also exit one or\nmore execution contexts.</p>\n<p>When control\nenters an execution context, the scope\nchain is created and initialised,\nvariable instantiation is performed,\nand the this value is determined.</p>\n<p>The\ninitialisation of the scope chain,\nvariable instantiation, and the\ndetermination of the this value depend\non the type of code being entered.</p>\n</blockquote>\n<p>Here's from <strong>O'Reilly's <a href=\"http://oreilly.com/catalog/9780596101992/index.html\" rel=\"noreferrer\">Javascript: The Definitive Guide (5th Edition)</a></strong>:</p>\n<blockquote>\n<p>8.8.1 Lexical Scoping</p>\n<p>Functions in JavaScript are lexically\nrather than dynamically scoped. This\nmeans that they run in the scope in\nwhich they are defined, not the scope\nfrom which they are executed. When a\nfunction is defined, the current scope\nchain is saved and becomes part of\nthe internal state of the function.\n...</p>\n</blockquote>\n<p>Highly recommended for covering these kinds of questions is Douglas Crockford's book:</p>\n<p><a href=\"http://oreilly.com/catalog/covers/9780596517748_cat.gif\" rel=\"noreferrer\">JavaScript, The Good Parts http://oreilly.com/catalog/covers/9780596517748_cat.gif</a></p>\n<p><a href=\"http://oreilly.com/catalog/9780596517748/index.html\" rel=\"noreferrer\"><strong>Javascript, The Good Parts</strong></a>, also from O'Reilly.</p>\n" }, { "answer_id": 235388, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 0, "selected": false, "text": "<p>...</p>\n\n<pre><code>function a() {\n function b() {\n alert('boo')\n }\n var c = 'Bound to local call object.'\n d = 'Bound to global object.'\n}\n</code></pre>\n\n<p>without being preceded by <em>var</em>, d is global. Do this to made d private:</p>\n\n<pre><code>function a() {\n function b() {\n alert('boo')\n }\n var c = 'Bound to local call object.'\n var d = 'Bound to local object.'\n}\n</code></pre>\n" }, { "answer_id": 235550, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": false, "text": "<p>It seems important to note that while d is being created as a \"global\", it is in reality being created as a property of the window object. This means that you could inadvertently be overwriting something that already exists on the window object or your variable might actually fail to be created at all. So:</p>\n\n<pre><code>function a() {\n d = 'Hello World';\n}\nalert(window.d); // shows 'Hello World'\n</code></pre>\n\n<p>But you cannot do:</p>\n\n<pre><code>function a() {\n document = 'something';\n}\n</code></pre>\n\n<p>because you cannot overwrite the window.document object.</p>\n\n<p>For all practical purposes you can imaging that all of your code is running in a giant <code>with(window)</code> block.</p>\n" }, { "answer_id": 235611, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 1, "selected": false, "text": "<p>Javascript has two scopes. Global, and functional. If you declare a variable inside a function using the \"var\" keyword, it will be local to that function, and any inner functions. If you declare a variable outside of a function, it has global scope.</p>\n\n<p>Finally, <strong>if you omit the var keyword when first declaring a variable, javascript assumes you wanted a global variable, no matter where you declare it</strong>.</p>\n\n<p>So, you're calling function a, and function a is declaring a global variable d.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31330/" ]
Today I had a discussion with a colleague about nested functions in Javascript: ``` function a() { function b() { alert('boo') } var c = 'Bound to local call object.' d = 'Bound to global object.' } ``` In this example, trials point out that b is not reachable outside the body of a, much like c is. However, d is - after executing a(). Looking for the exact definition of this behaviour in the [ECMAScript v.3 standard](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) , I didn't find the exact wording I was looking for; what Sec.13 p.71 does not say, is which object the function object created by the function declaration statement is to be bound to. Am I missing something?
This is static scoping. Statements within a function are scoped within that function. Javascript has a quirky behavior, however, which is that without the **var** keyword, you've implied a **global variable**. That's what you're seeing in your test. Your "d" variable is available because it is an implied global, despite being written within the body of a function. Also, to answer the second part of your question: A function exists in whatever scope it is declared, just like a variable. **Sidenote:** You probably don't want global variables, especially not implied ones. It's recommended that you always use the var keyword, to prevent confusion and to keep everything clean. **Sidenote:** The ECMA Standard isn't probably the most helpful place to find answers about Javascript, although it certainly isn't a bad resource. Remember that javascript in your browser is just an implementation of that standard, so the standards document will be giving you the rules that were (mostly) followed by the implementors when the javascript engine was being built. It can't offer specific information about the implementations you care about, namely the major browsers. There are a couple of books in particular which will give you very direct information about how the javascript implementations in the major browsers behave. To illustrate the difference, I'll include excerpts below from both the ECMAScript specification, and a book on Javascript. I think you'll agree that the book gives a more direct answer. Here's from the **ECMAScript Language Specification**: > > 10.2 *Entering An Execution Context* > > > Every function and constructor call > enters a new execution context, even > if a function is calling itself > recursively. Every return exits an > execution context. A thrown exception, > if not caught, may also exit one or > more execution contexts. > > > When control > enters an execution context, the scope > chain is created and initialised, > variable instantiation is performed, > and the this value is determined. > > > The > initialisation of the scope chain, > variable instantiation, and the > determination of the this value depend > on the type of code being entered. > > > Here's from **O'Reilly's [Javascript: The Definitive Guide (5th Edition)](http://oreilly.com/catalog/9780596101992/index.html)**: > > 8.8.1 Lexical Scoping > > > Functions in JavaScript are lexically > rather than dynamically scoped. This > means that they run in the scope in > which they are defined, not the scope > from which they are executed. When a > function is defined, the current scope > chain is saved and becomes part of > the internal state of the function. > ... > > > Highly recommended for covering these kinds of questions is Douglas Crockford's book: [JavaScript, The Good Parts http://oreilly.com/catalog/covers/9780596517748\_cat.gif](http://oreilly.com/catalog/covers/9780596517748_cat.gif) [**Javascript, The Good Parts**](http://oreilly.com/catalog/9780596517748/index.html), also from O'Reilly.
235,376
<p>Is there any way to add a field to a class at runtime ( a field that didn't exist before ) ? Something like this snippet :</p> <pre><code>Myobject *ob; // create an object ob-&gt;addField("newField",44); // we add the field to the class and we assign an initial value to it printf("%d",ob-&gt;newField); // now we can access that field </code></pre> <p>I don't really care how it would be done , I don't care if it's an ugly hack or not , I would like to know if it could be done , and a small example , if possible .</p> <p><strong>Another Example:</strong> say I have an XML file describing this class :</p> <pre><code>&lt;class name="MyClass"&gt; &lt;member name="field1" /&gt; &lt;member name="field2" /&gt; &lt;/class&gt; </code></pre> <p>and I want to "add" the fields "field1" and "field2" to the class (assuming the class already exists) . Let's say this is the code for the class :</p> <pre><code>class MyClass { }; </code></pre> <p>I don't want to create a class at runtime , I just want to add members/fields to an existing one .</p> <p>Thank you !</p>
[ { "answer_id": 235404, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "<p>There's no way to do it in the way you've described, since the compiler needs to resolve the reference at compile time - it will generate an error.</p>\n\n<p>But see <a href=\"http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html\" rel=\"nofollow noreferrer\">The Universal Design Pattern</a>.</p>\n" }, { "answer_id": 235408, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>No -- C++ does not support any manipulation of the type system like this. Even languages with some degree of runtime reflection (e.g. .NET) would not support exactly this paradigm. You would need a much more dynamic language to be able to do it.</p>\n" }, { "answer_id": 235417, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "<p><strong>Short version:</strong> Can't do it. There is no native support for this, c++ is statically typed and the <em>compiler</em> has to know the structure of each object to be manipulated.</p>\n\n<p><strong>Recommendation:</strong> Use an embedded interperter. And don't write your own (see below), get one that is already working and debugged.</p>\n\n<hr>\n\n<p><strong>What you can do:</strong> Implement just enough interperter for your needs.</p>\n\n<p>It would be simple enough to setup the class with a data member like</p>\n\n<pre><code>std::vector&lt;void*&gt; extra_data;\n</code></pre>\n\n<p>to which you could attach arbitrary data at run-time. The cost of this is that you will have to manage that data by hand with methods like:</p>\n\n<pre><code>size_t add_data_link(void *p); // points to existing data, returns index\nsize_t add_data_copy(void *p, size_t s) // copies data (dispose at\n // destruction time!), returns \n // index \nvoid* get_data(size_t i); //...\n</code></pre>\n\n<p>But that is not the limit, with a little more care, you could associate the arbitrary data with a name and you can continue to elaborate this scheme as far as you wish (add type info, etc...), but what this comes down to is implementing an interperter to take care of your run-time flexibility.</p>\n" }, { "answer_id": 235482, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 2, "selected": false, "text": "<p>You can't make that syntax work (because of static checking at compile time), but if you're willing to modify the syntax, you can achieve the same effect pretty easily. It would be fairly easy to have a dictionary member with a string->blob mapping, and have member functions like:</p>\n\n<pre><code>template&lt; typename T &gt; T get_member( string name );\ntemplate&lt; typename T &gt; void set_member( string name, T value );\n</code></pre>\n\n<p>You could make the syntax more compact/tricky if you want (eg: using a '->' operator override). There are also some compiler-specific tricks you could possibly leverage (MSVC supports __declspec(property), for example, which allows you to map references to a member variable to methods of a specific format). At the end of the day, though, you're not going to be able to do something the compiler doesn't accept in the language and get it to compile.</p>\n" }, { "answer_id": 235503, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": true, "text": "<h2>Use a map and a variant.</h2>\n<p>For example, using boost::variant. See <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html</a></p>\n<p>(But of course, you can create your own, to suit the types of your XML attributes.)</p>\n<pre><code>#include &lt;map&gt;\n#include &lt;boost/variant.hpp&gt;\n\ntypedef boost::variant&lt; int, std::string &gt; MyValue ;\ntypedef std::map&lt;std::string, MyValue&gt; MyValueMap ;\n</code></pre>\n<p>By adding MyValueMap as a member of your class, you can add properties according to their names. Which means the code:</p>\n<pre><code>oMyValueMap.insert(std::make_pair(&quot;newField&quot;, 44)) ;\noMyValueMap.insert(std::make_pair(&quot;newField2&quot;, &quot;Hello World&quot;)) ;\nstd::cout &lt;&lt; oMyValueMap[&quot;newField&quot;] ;\nstd::cout &lt;&lt; oMyValueMap[&quot;newField2&quot;] ;\n</code></pre>\n<p>By encapsulating it in a MyObject class, and adding the right overloaded accessors in this MyObject class, the code above becomes somewhat clearer:</p>\n<pre><code>oMyObject.addField(&quot;newField&quot;, 44) ;\noMyObject.addField(&quot;newField2&quot;, &quot;Hello World&quot;) ;\nstd::cout &lt;&lt; oMyObject[&quot;newField&quot;] ;\nstd::cout &lt;&lt; oMyObject[&quot;newField2&quot;] ;\n</code></pre>\n<p>But you lose somewhat the type safety of C++ doing so. But for XML, this is unavoidable, I guess.</p>\n" }, { "answer_id": 8537463, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was looking at this and I did a little search around, this code snippet obtained from : <a href=\"http://www.michael-hammer.at/blog/c++_dynamic_parametrization/\" rel=\"nofollow\">Michael Hammer's Blog</a>\nseems to be a good way to do this, by using <a href=\"http://www.boost.org/doc/libs/1_48_0/doc/html/any.html\" rel=\"nofollow\">boost::any</a></p>\n\n<p>First you define a structure that defines an std::map that contains a key (i.e. variable name) and the value. A function is defined to ad the pair and set it along with a function to get the value. Pretty simple if you ask me, but it seems a good way to start before doing more complex things.</p>\n\n<pre><code>struct AnyMap {\n void addAnyPair( const std::string&amp; key , boost::any&amp; value );\n\n template&lt;typename T&gt;\n T&amp; get( const std::string key ) {\n return( boost::any_cast&lt;T&amp;&gt;(map_[key]) );\n }\n\n std::map&lt;const std::string, boost::any&gt; map_;\n};\n\nvoid AnyMap::addAnyPair( const std::string&amp; key , boost::any&amp; value ) {\n map_.insert( std::make_pair( key, value ) );\n}\n</code></pre>\n\n<p>Bottom line, this is a hack, since C++ is strict type-checking language, and thus monster lie within for those that bend the rules. </p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
Is there any way to add a field to a class at runtime ( a field that didn't exist before ) ? Something like this snippet : ``` Myobject *ob; // create an object ob->addField("newField",44); // we add the field to the class and we assign an initial value to it printf("%d",ob->newField); // now we can access that field ``` I don't really care how it would be done , I don't care if it's an ugly hack or not , I would like to know if it could be done , and a small example , if possible . **Another Example:** say I have an XML file describing this class : ``` <class name="MyClass"> <member name="field1" /> <member name="field2" /> </class> ``` and I want to "add" the fields "field1" and "field2" to the class (assuming the class already exists) . Let's say this is the code for the class : ``` class MyClass { }; ``` I don't want to create a class at runtime , I just want to add members/fields to an existing one . Thank you !
Use a map and a variant. ------------------------ For example, using boost::variant. See <http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html> (But of course, you can create your own, to suit the types of your XML attributes.) ``` #include <map> #include <boost/variant.hpp> typedef boost::variant< int, std::string > MyValue ; typedef std::map<std::string, MyValue> MyValueMap ; ``` By adding MyValueMap as a member of your class, you can add properties according to their names. Which means the code: ``` oMyValueMap.insert(std::make_pair("newField", 44)) ; oMyValueMap.insert(std::make_pair("newField2", "Hello World")) ; std::cout << oMyValueMap["newField"] ; std::cout << oMyValueMap["newField2"] ; ``` By encapsulating it in a MyObject class, and adding the right overloaded accessors in this MyObject class, the code above becomes somewhat clearer: ``` oMyObject.addField("newField", 44) ; oMyObject.addField("newField2", "Hello World") ; std::cout << oMyObject["newField"] ; std::cout << oMyObject["newField2"] ; ``` But you lose somewhat the type safety of C++ doing so. But for XML, this is unavoidable, I guess.
235,386
<p>What's the best way to use NaNs in C++?</p> <p>I found <code>std::numeric_limits&lt;double&gt;::quiet_NaN()</code> and <code>std::numeric_limits&lt;double&gt;::signaling_NaN()</code>. I'd like to use <code>signaling_NaN</code> to represent an uninitialized variable as follows:</p> <pre><code>double diameter = std::numeric_limits&lt;double&gt;::signaling_NaN(); </code></pre> <p>This, however, signals (raises an exception) on assignment. I want it to raise an exception on use, not on assignment.</p> <p>Is there any way to use <code>signaling_NaN</code> without raising an exception on assignment? Is there a good, portable alternative to <code>signaling_NaN</code> that will raise a floating point exception when used?</p>
[ { "answer_id": 235490, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 2, "selected": false, "text": "<p>You can write a signalling NaN into a variable without triggering an exception with something like this (nb: untested)</p>\n\n<pre><code>void set_snan( double &amp;d )\n{\n long long *bits = (long long *)&amp;d;\n *bits = 0x7ff0000080000001LL;\n}\n</code></pre>\n\n<p>It'll work most places, but no, it's not 100% portable.</p>\n" }, { "answer_id": 235509, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 0, "selected": false, "text": "<p>Your C++ implementation may have an API for accessing the floating point environment to test for and clear certain floating point exceptions. See <a href=\"https://stackoverflow.com/questions/85726/converting-floating-point-exceptions-into-c-exceptions#88829\">my answer to a related question</a> for more information.</p>\n" }, { "answer_id": 236942, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 2, "selected": false, "text": "<p>Well, looking after the definition of both quiet and signaling NaN, I can't really make out any difference.</p>\n\n<p>You could use the code that is used in those functions yourself, maybe it prevents an exception that way, but seeing no exception in those two functions, I think it might be related to something else.</p>\n\n<p>If you want to directly assign the NaN:</p>\n\n<pre><code>double value = _Nan._Double;\n</code></pre>\n" }, { "answer_id": 236952, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "<p>What signaling NAN means is that when the CPU encounters it a signal is fired, (hence the name). If you want to detect uninitialized variables then raising the warning level on your compiler usually detects all paths that use uninitalized values. Failing that you can use a wrapper class that stores a boolean saying if the value is initialized:</p>\n\n<pre><code>template &lt;class T&gt;\nclass initialized {\n T t;\n bool is_initialized;\npublic:\n initialized() : t(T()), is_initialized(false) { }\n initialized(const T&amp; tt) : t(tt), is_initialized(true) { }\n T&amp; operator=(const T&amp; tt) { t = tt; is_initialized = true; return t; }\n operator T&amp;() {\n if (!is_initialized)\n throw std::exception(\"uninitialized\");\n return t; \n }\n};\n</code></pre>\n" }, { "answer_id": 281771, "author": "Josh Kelley", "author_id": 25507, "author_profile": "https://Stackoverflow.com/users/25507", "pm_score": 5, "selected": true, "text": "<p>After looking into this some more, it looks like <code>signaling_NaN</code> is useless as provided. If floating point exceptions are enabled, then calling it counts as processing a signaling NaN, so it immediately raises an exception. If floating point exceptions are disabled, then processing a signaling NaN automatically demotes it to a quiet NaN, so <code>signaling_NaN</code> doesn't work either way.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/235386/using-nan-in-c#235490\">Menkboy's code</a> works, but trying to use signaling NaNs runs into other problems: there's no portable way to enable or disable floating point exceptions (as alluded to <a href=\"https://stackoverflow.com/questions/85726/converting-floating-point-exceptions-into-c-exceptions#88829\">here</a> and <a href=\"https://stackoverflow.com/questions/235664/how-to-use-stdsignalingnan#236025\">here</a>), and if you're relying on exceptions being enabled, third party code may disable them (as described <a href=\"https://stackoverflow.com/questions/235664/how-to-use-stdsignalingnan#237391\">here</a>).</p>\n\n<p>So it seems like <a href=\"https://stackoverflow.com/questions/235386/using-nan-in-c#236952\">Motti's solution</a> is really the best choice.</p>\n" }, { "answer_id": 13235569, "author": "Rahul", "author_id": 1264515, "author_profile": "https://Stackoverflow.com/users/1264515", "pm_score": 2, "selected": false, "text": "<p>Simple answer:\nDo something like this in the header file and use it everywhere else:</p>\n\n<pre><code>#define NegativeNaN log(-1)\n</code></pre>\n\n<p>If you wish to do some kind of manipulations on them better write some extended wrapper function around <code>exp()</code> like <code>extended_exp()</code> and so on!</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25507/" ]
What's the best way to use NaNs in C++? I found `std::numeric_limits<double>::quiet_NaN()` and `std::numeric_limits<double>::signaling_NaN()`. I'd like to use `signaling_NaN` to represent an uninitialized variable as follows: ``` double diameter = std::numeric_limits<double>::signaling_NaN(); ``` This, however, signals (raises an exception) on assignment. I want it to raise an exception on use, not on assignment. Is there any way to use `signaling_NaN` without raising an exception on assignment? Is there a good, portable alternative to `signaling_NaN` that will raise a floating point exception when used?
After looking into this some more, it looks like `signaling_NaN` is useless as provided. If floating point exceptions are enabled, then calling it counts as processing a signaling NaN, so it immediately raises an exception. If floating point exceptions are disabled, then processing a signaling NaN automatically demotes it to a quiet NaN, so `signaling_NaN` doesn't work either way. [Menkboy's code](https://stackoverflow.com/questions/235386/using-nan-in-c#235490) works, but trying to use signaling NaNs runs into other problems: there's no portable way to enable or disable floating point exceptions (as alluded to [here](https://stackoverflow.com/questions/85726/converting-floating-point-exceptions-into-c-exceptions#88829) and [here](https://stackoverflow.com/questions/235664/how-to-use-stdsignalingnan#236025)), and if you're relying on exceptions being enabled, third party code may disable them (as described [here](https://stackoverflow.com/questions/235664/how-to-use-stdsignalingnan#237391)). So it seems like [Motti's solution](https://stackoverflow.com/questions/235386/using-nan-in-c#236952) is really the best choice.
235,391
<p>I am trying to find out how to upload a file from a web user to a server using an ASP page. The displayed page has an Input tag of type "File" like this:</p> <pre><code>&lt;input type="file" name="uploadfile"&gt; </code></pre> <p>And a submit button that passes the Form info to another .ASP page. This page must take the path it gets from the Input control and use it to somehow save the file to the server.</p> <p>I keep thinking there must be a common way to do this, since I see this kind of thing on a number of websites, but how is it done? Is there some sort of server object that can be called for it?</p>
[ { "answer_id": 235395, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 2, "selected": true, "text": "<p>This <a href=\"http://www.webconcerns.co.uk/asp/uploadasp/default.asp\" rel=\"nofollow noreferrer\">script</a> will help you.</p>\n\n<p>Also, you may google for \"<a href=\"http://www.google.com/search?q=asp+upload+file\" rel=\"nofollow noreferrer\">asp upload file</a>\" - there are tons of results.</p>\n" }, { "answer_id": 235421, "author": "DancesWithBamboo", "author_id": 1334, "author_profile": "https://Stackoverflow.com/users/1334", "pm_score": 1, "selected": false, "text": "<p>If you are doing any serious uploading or have a commercial product you really need to use a COM component in classic asp. Check out SA-FileUp. It has been the defacto standard for this since like forever.</p>\n" }, { "answer_id": 236867, "author": "AnonJr", "author_id": 25163, "author_profile": "https://Stackoverflow.com/users/25163", "pm_score": 0, "selected": false, "text": "<p>If your hosting service doesn't allow you to install components, you may also want to look at this script:</p>\n\n<p><a href=\"http://chris.brimson-read.com.au/index.php?option=com_content&amp;view=article&amp;id=6&amp;Itemid=7\" rel=\"nofollow noreferrer\">http://chris.brimson-read.com.au/index.php?option=com_content&amp;view=article&amp;id=6&amp;Itemid=7</a></p>\n\n<p>I've seen a wide variety of upload scripts floating around, and they ... vary ... in quality. I've not used the script in the selected answer, but its worth trying a few different options.</p>\n" }, { "answer_id": 358321, "author": "Espen", "author_id": 50718, "author_profile": "https://Stackoverflow.com/users/50718", "pm_score": 0, "selected": false, "text": "<p>I can recommend <a href=\"http://fileup.softartisans.com/\" rel=\"nofollow noreferrer\">SA-FileUp</a> and Dundas Upload. They both are easy to install and have good tutorials on how to implement.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16964/" ]
I am trying to find out how to upload a file from a web user to a server using an ASP page. The displayed page has an Input tag of type "File" like this: ``` <input type="file" name="uploadfile"> ``` And a submit button that passes the Form info to another .ASP page. This page must take the path it gets from the Input control and use it to somehow save the file to the server. I keep thinking there must be a common way to do this, since I see this kind of thing on a number of websites, but how is it done? Is there some sort of server object that can be called for it?
This [script](http://www.webconcerns.co.uk/asp/uploadasp/default.asp) will help you. Also, you may google for "[asp upload file](http://www.google.com/search?q=asp+upload+file)" - there are tons of results.
235,409
<p>I have trouble comparing 2 double in Excel VBA</p> <p>suppose that I have the following code</p> <pre><code>Dim a as double Dim b as double a = 0.15 b = 0.01 </code></pre> <p>After a few manipulations on b, b is now equal to 0.6</p> <p>however the imprecision related to the double data type gives me headache because</p> <pre><code>if a = b then //this will never trigger end if </code></pre> <p>Do you know how I can remove the trailing imprecision on the double type?</p>
[ { "answer_id": 235424, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": false, "text": "<p>It is never wise to compare doubles on equality.</p>\n\n<p>Some decimal values map to several floating point representations. So one 0.6 is not always equal to the other 0.6.</p>\n\n<p>If we subtract one from the other, we probably get something like 0.00000000051. </p>\n\n<p>We can now define equality as having a difference smaller that a certain error margin.</p>\n" }, { "answer_id": 235431, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 5, "selected": true, "text": "<p>You can't compare floating point values for equality. See this article on \"<a href=\"http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/\" rel=\"noreferrer\">Comparing floating point numbers</a>\" for a discussion of how to handle the intrinsic error.</p>\n\n<p>It isn't as simple as comparing to a constant error margin unless you know for sure what the absolute range of the floats is beforehand.</p>\n" }, { "answer_id": 235581, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 2, "selected": false, "text": "<p>As has been pointed out, many decimal numbers cannot be represented precisely as traditional floating-point types. Depending on the nature of your problem space, you may be better off using the Decimal VBA type which can represent decimal numbers (base 10) with perfect precision up to a certain decimal point. This is often done for representing money for example where 2-digit decimal precision is often desired.</p>\n\n<pre><code>Dim a as Decimal\nDim b as Decimal\na = 0.15\nb = 0.01\n</code></pre>\n" }, { "answer_id": 241476, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 1, "selected": false, "text": "<p>The Currency data type may be a good alternative. It handles relatively large numbers with fixed four digit precision.</p>\n" }, { "answer_id": 5576799, "author": "Anonymous Type", "author_id": 141720, "author_profile": "https://Stackoverflow.com/users/141720", "pm_score": 3, "selected": false, "text": "<p>if you are going to do this....</p>\n\n<pre><code>Dim a as double \n Dim b as double \n a = 0.15 \n b = 0.01\n</code></pre>\n\n<p>you need to add the round function in your IF statement like this...</p>\n\n<pre><code> If Round(a,2) = Round(b,2) Then \n //code inside block will now trigger.\n End If \n</code></pre>\n\n<p>See also <a href=\"http://support.microsoft.com/kb/78113\" rel=\"noreferrer\">here for additional Microsoft reference</a>.</p>\n" }, { "answer_id": 24041248, "author": "user3706920", "author_id": 3706920, "author_profile": "https://Stackoverflow.com/users/3706920", "pm_score": 3, "selected": false, "text": "<p>Here is a simple function I wrote:</p>\n\n<pre><code>Function dblCheckTheSame(number1 As Double, number2 As Double, Optional Digits As Integer = 12) As Boolean\n\nIf (number1 - number2) ^ 2 &lt; (10 ^ -Digits) ^ 2 Then\n dblCheckTheSame = True\nElse\n dblCheckTheSame = False\nEnd If\n\nEnd Function\n</code></pre>\n\n<p>Call it with:</p>\n\n<pre><code>MsgBox dblCheckTheSame(1.2345, 1.23456789)\nMsgBox dblCheckTheSame(1.2345, 1.23456789, 4)\nMsgBox dblCheckTheSame(1.2345678900001, 1.2345678900002)\nMsgBox dblCheckTheSame(1.2345678900001, 1.2345678900002, 14)\n</code></pre>\n" }, { "answer_id": 56482767, "author": "Josh Anstead", "author_id": 6322229, "author_profile": "https://Stackoverflow.com/users/6322229", "pm_score": 0, "selected": false, "text": "<p>Work-a-round??\nNot sure if this will answer all scenarios, but I ran into a problem comparing rounded double values in VBA. When I compared to numbers that appeared to be identical after rounding, VBA would trigger false in an if-then compare statement.\nMy fix was to run two conversions, first double to string, then string to double, and then do the compare.</p>\n\n<p><strong><em>Simulated Example</em></strong>\nI did not record the exact numbers that caused the error mentioned in this post, and the amounts in my example do not trigger the problem currently and are intended to represent the type of issue.</p>\n\n<pre><code> Sub Test_Rounded_Numbers()\n\n Dim Num1 As Double\n\n Dim Num2 As Double\n\n Let Num1 = 123.123456789\n\n Let Num2 = 123.123467891\n\n Let Num1 = Round(Num1, 4) '123.1235\n\n\n Let Num2 = Round(Num2, 4) '123.1235\n\n If Num1 = Num2 Then\n\n MsgBox \"Correct Match, \" &amp; Num1 &amp; \" does equal \" &amp; Num2\n Else\n MsgBox \"Inccorrect Match, \" &amp; Num1 &amp; \" does not equal \" &amp; Num2\n End If\n\n 'Here it would say that \"Inccorrect Match, 123.1235 does not equal 123.1235.\"\n\n End Sub\n\n Sub Fixed_Double_Value_Type_Compare_Issue()\n\n Dim Num1 As Double\n\n Dim Num2 As Double\n\n Let Num1 = 123.123456789\n\n Let Num2 = 123.123467891\n\n Let Num1 = Round(Num1, 4) '123.1235\n\n\n Let Num2 = Round(Num2, 4) '123.1235\n\n 'Add CDbl(CStr(Double_Value))\n 'By doing this step the numbers\n 'would trigger if they matched\n '100% of the time\n\n If CDbl(CStr(Num1)) = CDbl(CStr(Num2)) Then\n\n MsgBox \"Correct Match\"\n Else\n MsgBox \"Inccorrect Match\"\n\n End If\n\n 'Now it says Here it would say that \"Correct Match, 123.1235 does equal 123.1235.\"\n End Sub\n</code></pre>\n" }, { "answer_id": 61971839, "author": "Elimar", "author_id": 9681226, "author_profile": "https://Stackoverflow.com/users/9681226", "pm_score": -1, "selected": false, "text": "<p>Try to use Single values if possible.\nConversion to Double values generates random errors.</p>\n\n<pre><code>Public Sub Test()\nDim D01 As Double\nDim D02 As Double\nDim S01 As Single\nDim S02 As Single\nS01 = 45.678 / 12\nS02 = 45.678\nD01 = S01\nD02 = S02\nDebug.Print S01 * 12\nDebug.Print S02\nDebug.Print D01 * 12\nDebug.Print D02\nEnd Sub\n\n 45,678 \n 45,678 \n 45,67799949646 \n 45,6780014038086 \n</code></pre>\n" }, { "answer_id": 68291403, "author": "Greedo", "author_id": 6609896, "author_profile": "https://Stackoverflow.com/users/6609896", "pm_score": 2, "selected": false, "text": "<p>Late answer but I'm surprised a solution hasn't been posted that addresses the concerns outlined in the article linked in the (currently) accepted <a href=\"https://stackoverflow.com/a/235431/6609896\">answer</a>, namely that:</p>\n<ul>\n<li>Rounding checks equality with absolute tolerance (e.g. 0.0001 units if rounded to 4d.p.) which is rubbish when comparing different values on multiple orders of magnitude (so not just comparing to 0)</li>\n<li>Relative tolerance that scales with one of the numbers being compared meanwhile is not mentioned in the current answers, but performs well on non-zero comparisons (however will be bad at comparing to zero as the scaling blows up around then).</li>\n</ul>\n<hr />\n<p>To solve this, I've taken inspiration from Python: <em><a href=\"https://www.python.org/dev/peps/pep-0485\" rel=\"nofollow noreferrer\">PEP 485 -- A Function for testing approximate equality</a></em> to implement the following (in a standard module):</p>\n<h3>Code</h3>\n<pre><code>'@NoIndent: Don't want to lose our description annotations\n'@Folder(&quot;Tests.Utils&quot;)\n\nOption Explicit\nOption Private Module\n\n'Based on Python's math.isclose https://github.com/python/cpython/blob/17f94e28882e1e2b331ace93f42e8615383dee59/Modules/mathmodule.c#L2962-L3003\n'math.isclose -&gt; boolean\n' a: double\n' b: double\n' relTol: double = 1e-09\n' maximum difference for being considered &quot;close&quot;, relative to the\n' magnitude of the input values\n' absTol: double = 0.0\n' maximum difference for being considered &quot;close&quot;, regardless of the\n' magnitude of the input values\n'Determine whether two floating point numbers are close in value.\n'Return True if a is close in value to b, and False otherwise.\n'For the values to be considered close, the difference between them\n'must be smaller than at least one of the tolerances.\n'-inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n'is, NaN is not close to anything, even itself. inf and -inf are\n'only close to themselves.\n'@Description(&quot;Determine whether two floating point numbers are close in value, accounting for special values in IEEE 754&quot;)\nPublic Function IsClose(ByVal a As Double, ByVal b As Double, _\n Optional ByVal relTol As Double = 0.000000001, _\n Optional ByVal absTol As Double = 0 _\n ) As Boolean\n \n If relTol &lt; 0# Or absTol &lt; 0# Then\n Err.Raise 5, Description:=&quot;tolerances must be non-negative&quot;\n ElseIf a = b Then\n 'Short circuit exact equality -- needed to catch two infinities of\n ' the same sign. And perhaps speeds things up a bit sometimes.\n IsClose = True\n ElseIf IsInfinity(a) Or IsInfinity(b) Then\n 'This catches the case of two infinities of opposite sign, or\n ' one infinity and one finite number. Two infinities of opposite\n ' sign would otherwise have an infinite relative tolerance.\n 'Two infinities of the same sign are caught by the equality check\n ' above.\n IsClose = False\n Else\n 'Now do the regular computation on finite arguments. Here an\n ' infinite tolerance will always result in the function returning True,\n ' since an infinite difference will be &lt;= to the infinite tolerance.\n \n 'This is to supress overflow errors as we deal with infinity.\n 'NaN has already been filtered out in the equality checks earlier.\n On Error Resume Next\n Dim diff As Double: diff = Abs(b - a)\n \n If diff &lt;= absTol Then\n IsClose = True\n ElseIf diff &lt;= CDbl(Abs(relTol * b)) Then\n IsClose = True\n ElseIf diff &lt;= CDbl(Abs(relTol * a)) Then\n IsClose = True\n End If\n On Error GoTo 0\n End If\nEnd Function\n\n'@Description &quot;Checks if Number is IEEE754 +/- inf, won't raise an error&quot;\nPublic IsInfinity(ByVal Number As Double) As Boolean\n On Error Resume Next 'in case of NaN\n IsInfinity = Abs(Number) = PosInf\n On Error GoTo 0\nEnd Function\n\n'@Description &quot;IEEE754 -inf&quot;\nPublic Property Get NegInf() As Double\n On Error Resume Next\n NegInf = -1 / 0\n On Error GoTo 0\nEnd Property\n\n'@Description &quot;IEEE754 +inf&quot;\nPublic Property Get PosInf() As Double\n On Error Resume Next\n PosInf = 1 / 0\n On Error GoTo 0\nEnd Property\n\n'@Description &quot;IEEE754 signaling NaN (sNaN)&quot;\nPublic Property Get NaN() As Double\n On Error Resume Next\n NaN = 0 / 0\n On Error GoTo 0\nEnd Property\n\n'@Description &quot;IEEE754 quiet NaN (qNaN)&quot;\nPublic Property Get QNaN() As Double\n QNaN = -NaN\nEnd Property\n</code></pre>\n<p><sub>Updated to incorporate <a href=\"https://codereview.stackexchange.com/a/266123/146810\">great feedback</a> from <a href=\"https://stackoverflow.com/users/8488913/cristian-buse\">Cristian Buse</a></sub></p>\n<h3>Examples</h3>\n<p>The <code>IsClose</code> function can be used to check for absolute difference:</p>\n<pre><code>assert(IsClose(0, 0.0001233, absTol:= 0.001)) 'same to 3 d.p.?\n</code></pre>\n<p>... or relative difference:</p>\n<pre><code>assert(IsClose(1234.5, 1234.6, relTol:= 0.0001)) '0.01% relative difference?\n</code></pre>\n<p>... but generally you specify both and if either tolerance is met then the numbers are considered close. It has special handling of +-infinity which are only close to themselves, and NaN which is close to nothing (see the PEP for full justification, or <a href=\"https://codereview.stackexchange.com/q/263839/146810\">my Code Review post</a> where I'd love feedback on this code :)</p>\n" }, { "answer_id": 72864907, "author": "Michael", "author_id": 7444507, "author_profile": "https://Stackoverflow.com/users/7444507", "pm_score": 0, "selected": false, "text": "<p>Depending on your situation and your data, and if you're happy with the level of precision shown by default, you can try comparing the string conversions of the numbers as a very simple coding solution:</p>\n<pre><code>if cstr(a) = cstr(b)\n</code></pre>\n<p>This will include as much precision as would be displayed by default, which is generally sufficient to consider the numbers equal.</p>\n<p>This would be inefficient for very large data sets, but for me was useful when reconciling imported data which was identical but was not matching after storing the data in VBA Arrays.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367/" ]
I have trouble comparing 2 double in Excel VBA suppose that I have the following code ``` Dim a as double Dim b as double a = 0.15 b = 0.01 ``` After a few manipulations on b, b is now equal to 0.6 however the imprecision related to the double data type gives me headache because ``` if a = b then //this will never trigger end if ``` Do you know how I can remove the trailing imprecision on the double type?
You can't compare floating point values for equality. See this article on "[Comparing floating point numbers](http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/)" for a discussion of how to handle the intrinsic error. It isn't as simple as comparing to a constant error margin unless you know for sure what the absolute range of the floats is beforehand.
235,411
<p>Finding out what's selected in real browsers is as simple as:</p> <pre><code>var range = { start: textbox.selectionStart, end: textbox.selectionEnd } </code></pre> <p>But IE, as usual, doesn't understand. What's the best cross-browser way to do this?</p>
[ { "answer_id": 235419, "author": "TALlama", "author_id": 5657, "author_profile": "https://Stackoverflow.com/users/5657", "pm_score": 3, "selected": false, "text": "<p>My current solution is verbose and based on <a href=\"http://www.webdeveloper.com/forum/showthread.php?t=111407\" rel=\"noreferrer\">this thread</a>, but I'm open to better solutions.</p>\n\n<pre><code>function getSelection(inputBox) {\n if (\"selectionStart\" in inputBox) {\n return {\n start: inputBox.selectionStart,\n end: inputBox.selectionEnd\n }\n }\n\n //and now, the blinkered IE way\n var bookmark = document.selection.createRange().getBookmark()\n var selection = inputBox.createTextRange()\n selection.moveToBookmark(bookmark)\n\n var before = inputBox.createTextRange()\n before.collapse(true)\n before.setEndPoint(\"EndToStart\", selection)\n\n var beforeLength = before.text.length\n var selLength = selection.text.length\n\n return {\n start: beforeLength,\n end: beforeLength + selLength\n }\n}\n</code></pre>\n" }, { "answer_id": 235582, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": false, "text": "<p>IE's Range implementation is a slithy horror. It really wants you to use the execrable execCommand interface instead of anything involving indexing into the text.</p>\n\n<p>There are two approaches I know of for getting the indices and they both have problems. The first uses range.text as in your example code. Unfortunately range.text has a habit of stripping off leading and trailing newlines, which means if the caret/selection is at the start of a line other than the first one, beforeLength will be off by (number of newlines*2) characters and you'll get the wrong selected text.</p>\n\n<p>The second approach is to use range.moveStart/End (on a duplicated range), as outlined in the answer to this question: <a href=\"https://stackoverflow.com/questions/164147/character-offset-in-an-internet-explorer-textrange\">Character offset in an Internet Explorer TextRange</a> (however as you are using a known textarea parent you can ignore the stuff about node-finding). This doesn't have the same problem, but it does report all indices as if newlines were simple LF characters, even though textarea.value and range.text will return them as CRLF sequences! So you can't use them directly to index into the textarea, but you can either fix them up with a bunch of newline counting or just string-replace away all the CRs from the value before you use it.</p>\n" }, { "answer_id": 4207763, "author": "Tim Down", "author_id": 96100, "author_profile": "https://Stackoverflow.com/users/96100", "pm_score": 6, "selected": true, "text": "<p>I'll post this function for another time, seeing as this question got linked to from another one.</p>\n\n<p>The following will do the job in all browsers and deals with all new line problems without seriously compromising performance. I've arrived at this after <a href=\"https://stackoverflow.com/questions/3622818/ies-document-selection-createrange-doesnt-include-leading-or-trailing-blank-lin\">some toing and froing</a> and now I'm pretty convinced it's the best such function around.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>This function does assume the textarea/input has focus, so you may need to call the textarea's <code>focus()</code> method before calling it.</p>\n\n<pre><code>function getInputSelection(el) {\n var start = 0, end = 0, normalizedValue, range,\n textInputRange, len, endRange;\n\n if (typeof el.selectionStart == \"number\" &amp;&amp; typeof el.selectionEnd == \"number\") {\n start = el.selectionStart;\n end = el.selectionEnd;\n } else {\n range = document.selection.createRange();\n\n if (range &amp;&amp; range.parentElement() == el) {\n len = el.value.length;\n normalizedValue = el.value.replace(/\\r\\n/g, \"\\n\");\n\n // Create a working TextRange that lives only in the input\n textInputRange = el.createTextRange();\n textInputRange.moveToBookmark(range.getBookmark());\n\n // Check if the start and end of the selection are at the very end\n // of the input, since moveStart/moveEnd doesn't return what we want\n // in those cases\n endRange = el.createTextRange();\n endRange.collapse(false);\n\n if (textInputRange.compareEndPoints(\"StartToEnd\", endRange) &gt; -1) {\n start = end = len;\n } else {\n start = -textInputRange.moveStart(\"character\", -len);\n start += normalizedValue.slice(0, start).split(\"\\n\").length - 1;\n\n if (textInputRange.compareEndPoints(\"EndToEnd\", endRange) &gt; -1) {\n end = len;\n } else {\n end = -textInputRange.moveEnd(\"character\", -len);\n end += normalizedValue.slice(0, end).split(\"\\n\").length - 1;\n }\n }\n }\n }\n\n return {\n start: start,\n end: end\n };\n}\n\nvar el = document.getElementById(\"your_input\");\nel.focus();\nvar sel = getInputSelection(el);\nalert(sel.start + \", \" + sel.end);\n</code></pre>\n" }, { "answer_id": 27116215, "author": "Atav32", "author_id": 1248811, "author_profile": "https://Stackoverflow.com/users/1248811", "pm_score": 0, "selected": false, "text": "<p>From <a href=\"https://github.com/winmarkltd/BootstrapFormHelpers/blob/0d89ab451ded3a4c6a47acb0e4bf023504a94434/js/bootstrap-formhelpers-phone.js\" rel=\"nofollow\">BootstrapFormHelpers</a></p>\n\n<pre><code> function getCursorPosition($element) {\n var position = 0,\n selection;\n\n if (document.selection) {\n // IE Support\n $element.focus();\n selection = document.selection.createRange();\n selection.moveStart ('character', -$element.value.length);\n position = selection.text.length;\n } else if ($element.selectionStart || $element.selectionStart === 0) {\n position = $element.selectionStart;\n }\n\n return position;\n }\n\n function setCursorPosition($element, position) {\n var selection;\n\n if (document.selection) {\n // IE Support\n $element.focus ();\n selection = document.selection.createRange();\n selection.moveStart ('character', -$element.value.length);\n selection.moveStart ('character', position);\n selection.moveEnd ('character', 0);\n selection.select ();\n } else if ($element.selectionStart || $element.selectionStart === 0) {\n $element.selectionStart = position;\n $element.selectionEnd = position;\n $element.focus ();\n }\n }\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5657/" ]
Finding out what's selected in real browsers is as simple as: ``` var range = { start: textbox.selectionStart, end: textbox.selectionEnd } ``` But IE, as usual, doesn't understand. What's the best cross-browser way to do this?
I'll post this function for another time, seeing as this question got linked to from another one. The following will do the job in all browsers and deals with all new line problems without seriously compromising performance. I've arrived at this after [some toing and froing](https://stackoverflow.com/questions/3622818/ies-document-selection-createrange-doesnt-include-leading-or-trailing-blank-lin) and now I'm pretty convinced it's the best such function around. **UPDATE** This function does assume the textarea/input has focus, so you may need to call the textarea's `focus()` method before calling it. ``` function getInputSelection(el) { var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { start = el.selectionStart; end = el.selectionEnd; } else { range = document.selection.createRange(); if (range && range.parentElement() == el) { len = el.value.length; normalizedValue = el.value.replace(/\r\n/g, "\n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { start = end = len; } else { start = -textInputRange.moveStart("character", -len); start += normalizedValue.slice(0, start).split("\n").length - 1; if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) { end = len; } else { end = -textInputRange.moveEnd("character", -len); end += normalizedValue.slice(0, end).split("\n").length - 1; } } } } return { start: start, end: end }; } var el = document.getElementById("your_input"); el.focus(); var sel = getInputSelection(el); alert(sel.start + ", " + sel.end); ```
235,418
<p>I have (simplified for the example) a table with the following data</p> <pre><code>Row Start Finish ID Amount --- --------- ---------- -- ------ 1 2008-10-01 2008-10-02 01 10 2 2008-10-02 2008-10-03 02 20 3 2008-10-03 2008-10-04 01 38 4 2008-10-04 2008-10-05 01 23 5 2008-10-05 2008-10-06 03 14 6 2008-10-06 2008-10-07 02 3 7 2008-10-07 2008-10-08 02 8 8 2008-10-08 2008-11-08 03 19 </code></pre> <p>The dates represent a period in time, the ID is the state a system was in during that period and the amount is a value related to that state.</p> <p>What I want to do is to aggregate the Amounts for <em>adjacent</em> rows with the <em>same</em> ID number, but keep the same overall sequence so that contiguous runs can be combined. Thus I want to end up with data like:</p> <pre><code>Row Start Finish ID Amount --- --------- ---------- -- ------ 1 2008-10-01 2008-10-02 01 10 2 2008-10-02 2008-10-03 02 20 3 2008-10-03 2008-10-05 01 61 4 2008-10-05 2008-10-06 03 14 5 2008-10-06 2008-10-08 02 11 6 2008-10-08 2008-11-08 03 19 </code></pre> <p>I am after a T-SQL solution that can be put into a SP, however I can't see how to do that with simple queries. I suspect that it may require iteration of some sort but I don't want to go down that path.</p> <p>The reason I want to do this aggregation is that the next step in the process is to do a SUM() and Count() grouped by the unique ID's that occur within the sequence, so that my final data will look something like:</p> <pre><code>ID Counts Total -- ------ ----- 01 2 71 02 2 31 03 2 33 </code></pre> <p>However if I do a simple </p> <pre><code>SELECT COUNT(ID), SUM(Amount) FROM data GROUP BY ID </code></pre> <p>On the original table I get something like</p> <pre><code>ID Counts Total -- ------ ----- 01 3 71 02 3 31 03 2 33 </code></pre> <p>Which is not what I want.</p>
[ { "answer_id": 235429, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>Probably need to create a cursor and loop through the results, keeping track of which id you are working with and accumulating the data along the way. When the id changes you can insert the accumulated data into a temporary table and return the table at the end of the procedure (select all from it). A table-based function might be better as you can then just insert into the return table as you go along.</p>\n" }, { "answer_id": 235781, "author": "Dave_H", "author_id": 17109, "author_profile": "https://Stackoverflow.com/users/17109", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I suspect that it may require iteration of some sort but I don't want to go down that path.</p>\n</blockquote>\n\n<p>I think that's the route you'll have to take, use a cursor to populate a table variable. If you have a large number of records you could use a permanent table to store the results then when you need to retrieve the data you could process only the new data. </p>\n\n<p>I would add a bit field with a default of 0 to the source table to keep track of which records have been processed. Assuming no one is using select * on the table, adding a column with a default value won't affect the rest of your application.</p>\n\n<p>Add a comment to this post if you want help coding the solution.</p>\n" }, { "answer_id": 235956, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>If you read the book \"Developing Time-Oriented Database Applications in SQL\" by <a href=\"http://www.cs.arizona.edu/~rts/\" rel=\"nofollow noreferrer\">R T Snodgrass</a> (the pdf of which is available from his web site under publications), and get as far as Figure 6.25 on p165-166, you will find the non-trivial SQL which can be used in the current example to group the various rows with the same ID value and continuous time intervals.</p>\n\n<p><em>The query development below is close to correct, but there is a problem spotted right at the end, that has its source in the first SELECT statement. I've not yet tracked down why the incorrect answer is being given.</em> [If someone can test the SQL on their DBMS and tell me whether the first query works correctly there, it would be a great help!]</p>\n\n<p>It looks something like:</p>\n\n<pre><code>-- Derived from Figure 6.25 from Snodgrass \"Developing Time-Oriented\n-- Database Applications in SQL\"\nCREATE TABLE Data\n(\n Start DATE,\n Finish DATE,\n ID CHAR(2),\n Amount INT\n);\n\nINSERT INTO Data VALUES('2008-10-01', '2008-10-02', '01', 10);\nINSERT INTO Data VALUES('2008-10-02', '2008-10-03', '02', 20);\nINSERT INTO Data VALUES('2008-10-03', '2008-10-04', '01', 38);\nINSERT INTO Data VALUES('2008-10-04', '2008-10-05', '01', 23);\nINSERT INTO Data VALUES('2008-10-05', '2008-10-06', '03', 14);\nINSERT INTO Data VALUES('2008-10-06', '2008-10-07', '02', 3);\nINSERT INTO Data VALUES('2008-10-07', '2008-10-08', '02', 8);\nINSERT INTO Data VALUES('2008-10-08', '2008-11-08', '03', 19);\n\nSELECT DISTINCT F.ID, F.Start, L.Finish\n FROM Data AS F, Data AS L\n WHERE F.Start &lt; L.Finish\n AND F.ID = L.ID\n -- There are no gaps between F.Finish and L.Start\n AND NOT EXISTS (SELECT *\n FROM Data AS M\n WHERE M.ID = F.ID\n AND F.Finish &lt; M.Start\n AND M.Start &lt; L.Start\n AND NOT EXISTS (SELECT *\n FROM Data AS T1\n WHERE T1.ID = F.ID\n AND T1.Start &lt; M.Start\n AND M.Start &lt;= T1.Finish))\n -- Cannot be extended further\n AND NOT EXISTS (SELECT *\n FROM Data AS T2\n WHERE T2.ID = F.ID\n AND ((T2.Start &lt; F.Start AND F.Start &lt;= T2.Finish)\n OR (T2.Start &lt;= L.Finish AND L.Finish &lt; T2.Finish)));\n</code></pre>\n\n<p>The output from that query is:</p>\n\n<pre><code>01 2008-10-01 2008-10-02\n01 2008-10-03 2008-10-05\n02 2008-10-02 2008-10-03\n02 2008-10-06 2008-10-08\n03 2008-10-05 2008-10-06\n03 2008-10-05 2008-11-08\n03 2008-10-08 2008-11-08\n</code></pre>\n\n<p><strong>Edited</strong>: There's a problem with the penultimate row - it should not be there. And I'm not clear (yet) where it is coming from.</p>\n\n<p>Now we need to treat that complex expression as a query expression in the FROM clause of another SELECT statement, which will sum the amount values for a given ID over the entries that overlap with the maximal ranges shown above.</p>\n\n<pre><code>SELECT M.ID, M.Start, M.Finish, SUM(D.Amount)\n FROM Data AS D,\n (SELECT DISTINCT F.ID, F.Start, L.Finish\n FROM Data AS F, Data AS L\n WHERE F.Start &lt; L.Finish\n AND F.ID = L.ID\n -- There are no gaps between F.Finish and L.Start\n AND NOT EXISTS (SELECT *\n FROM Data AS M\n WHERE M.ID = F.ID\n AND F.Finish &lt; M.Start\n AND M.Start &lt; L.Start\n AND NOT EXISTS (SELECT *\n FROM Data AS T1\n WHERE T1.ID = F.ID\n AND T1.Start &lt; M.Start\n AND M.Start &lt;= T1.Finish))\n -- Cannot be extended further\n AND NOT EXISTS (SELECT *\n FROM Data AS T2\n WHERE T2.ID = F.ID\n AND ((T2.Start &lt; F.Start AND F.Start &lt;= T2.Finish)\n OR (T2.Start &lt;= L.Finish AND L.Finish &lt; T2.Finish)))) AS M\n WHERE D.ID = M.ID\n AND M.Start &lt;= D.Start\n AND M.Finish &gt;= D.Finish\n GROUP BY M.ID, M.Start, M.Finish\n ORDER BY M.ID, M.Start;\n</code></pre>\n\n<p>This gives:</p>\n\n<pre><code>ID Start Finish Amount\n01 2008-10-01 2008-10-02 10\n01 2008-10-03 2008-10-05 61\n02 2008-10-02 2008-10-03 20\n02 2008-10-06 2008-10-08 11\n03 2008-10-05 2008-10-06 14\n03 2008-10-05 2008-11-08 33 -- Here be trouble!\n03 2008-10-08 2008-11-08 19\n</code></pre>\n\n<p><strong>Edited</strong>: This is <em>almost</em> the correct data set on which to do the COUNT and SUM aggregation requested by the original question, so the final answer is:</p>\n\n<pre><code>SELECT I.ID, COUNT(*) AS Number, SUM(I.Amount) AS Amount\n FROM (SELECT M.ID, M.Start, M.Finish, SUM(D.Amount) AS Amount\n FROM Data AS D,\n (SELECT DISTINCT F.ID, F.Start, L.Finish\n FROM Data AS F, Data AS L\n WHERE F.Start &lt; L.Finish\n AND F.ID = L.ID\n -- There are no gaps between F.Finish and L.Start\n AND NOT EXISTS\n (SELECT *\n FROM Data AS M\n WHERE M.ID = F.ID\n AND F.Finish &lt; M.Start\n AND M.Start &lt; L.Start\n AND NOT EXISTS\n (SELECT *\n FROM Data AS T1\n WHERE T1.ID = F.ID\n AND T1.Start &lt; M.Start\n AND M.Start &lt;= T1.Finish))\n -- Cannot be extended further\n AND NOT EXISTS\n (SELECT *\n FROM Data AS T2\n WHERE T2.ID = F.ID\n AND ((T2.Start &lt; F.Start AND F.Start &lt;= T2.Finish) OR\n (T2.Start &lt;= L.Finish AND L.Finish &lt; T2.Finish)))\n ) AS M\n WHERE D.ID = M.ID\n AND M.Start &lt;= D.Start\n AND M.Finish &gt;= D.Finish\n GROUP BY M.ID, M.Start, M.Finish\n ) AS I\n GROUP BY I.ID\n ORDER BY I.ID;\n\nid number amount\n01 2 71\n02 2 31\n03 3 66\n</code></pre>\n\n<p><strong>Review</strong>:\nOh! Drat...the entry for 3 has twice the 'amount' that it should have. Previous 'edited' parts indicate where things started to go wrong. It looks as though either the first query is subtly wrong (maybe it is intended for a different question), or the optimizer I'm working with is misbehaving. Nevertheless, there should be an answer closely related to this that will give the correct values.</p>\n\n<p>For the record: tested on IBM Informix Dynamic Server 11.50 on Solaris 10. However, should work fine on any other moderately standard-conformant SQL DBMS.</p>\n" }, { "answer_id": 240574, "author": "Peter M", "author_id": 31326, "author_profile": "https://Stackoverflow.com/users/31326", "pm_score": 0, "selected": false, "text": "<p>Well I decided to go down the iteration route using a mixture of joins and cursors. By JOINing the data table against itself I can create a link list of only those records that are consecutive. </p>\n\n<pre><code>INSERT INTO #CONSEC\n SELECT a.ID, a.Start, b.Finish, b.Amount \n FROM Data a JOIN Data b \n ON (a.Finish = b.Start) AND (a.ID = b.ID)\n</code></pre>\n\n<p>Then I can unwind the list by iterating over it with a cursor, and doing updates back to the data table to adjust (And delete the now extraneous records from the Data table)</p>\n\n<pre><code>DECLARE CCursor CURSOR FOR\n SELECT ID, Start, Finish, Amount FROM #CONSEC ORDER BY Start DESC\n\n@Total = 0\nOPEN CCursor\nFETCH NEXT FROM CCursor INTO @ID, @START, @FINISH, @AMOUNT\nWHILE @FETCH_STATUS = 0\nBEGIN\n @Total = @Total + @Amount\n @Start_Last = @Start\n @Finish_Last = @Finish\n @ID_Last = @ID\n\n DELETE FROM Data WHERE Start = @Finish\n FETCH NEXT FROM CCursor INTO @ID, @START, @FINISH, @AMOUNT\n IF (@ID_Last&lt;&gt; @ID) OR (@Finish&lt;&gt;@Start_Last)\n BEGIN\n UPDATE Data\n SET Amount = Amount + @Total\n WHERE Start = @Start_Last\n @Total = 0\n END \nEND\n\nCLOSE CCursor\nDEALLOCATE CCursor\n</code></pre>\n\n<p>This all works and has acceptable performance for typical data that I am using.</p>\n\n<p>I did find one small issue with the above code. Originally I was updating the Data table on each loop through the cursor. But this didn't work. It seems that you can only do one update on a record, and that multiple updates (in order to keep adding data) revert back to the reading the original contents of the record.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31326/" ]
I have (simplified for the example) a table with the following data ``` Row Start Finish ID Amount --- --------- ---------- -- ------ 1 2008-10-01 2008-10-02 01 10 2 2008-10-02 2008-10-03 02 20 3 2008-10-03 2008-10-04 01 38 4 2008-10-04 2008-10-05 01 23 5 2008-10-05 2008-10-06 03 14 6 2008-10-06 2008-10-07 02 3 7 2008-10-07 2008-10-08 02 8 8 2008-10-08 2008-11-08 03 19 ``` The dates represent a period in time, the ID is the state a system was in during that period and the amount is a value related to that state. What I want to do is to aggregate the Amounts for *adjacent* rows with the *same* ID number, but keep the same overall sequence so that contiguous runs can be combined. Thus I want to end up with data like: ``` Row Start Finish ID Amount --- --------- ---------- -- ------ 1 2008-10-01 2008-10-02 01 10 2 2008-10-02 2008-10-03 02 20 3 2008-10-03 2008-10-05 01 61 4 2008-10-05 2008-10-06 03 14 5 2008-10-06 2008-10-08 02 11 6 2008-10-08 2008-11-08 03 19 ``` I am after a T-SQL solution that can be put into a SP, however I can't see how to do that with simple queries. I suspect that it may require iteration of some sort but I don't want to go down that path. The reason I want to do this aggregation is that the next step in the process is to do a SUM() and Count() grouped by the unique ID's that occur within the sequence, so that my final data will look something like: ``` ID Counts Total -- ------ ----- 01 2 71 02 2 31 03 2 33 ``` However if I do a simple ``` SELECT COUNT(ID), SUM(Amount) FROM data GROUP BY ID ``` On the original table I get something like ``` ID Counts Total -- ------ ----- 01 3 71 02 3 31 03 2 33 ``` Which is not what I want.
If you read the book "Developing Time-Oriented Database Applications in SQL" by [R T Snodgrass](http://www.cs.arizona.edu/~rts/) (the pdf of which is available from his web site under publications), and get as far as Figure 6.25 on p165-166, you will find the non-trivial SQL which can be used in the current example to group the various rows with the same ID value and continuous time intervals. *The query development below is close to correct, but there is a problem spotted right at the end, that has its source in the first SELECT statement. I've not yet tracked down why the incorrect answer is being given.* [If someone can test the SQL on their DBMS and tell me whether the first query works correctly there, it would be a great help!] It looks something like: ``` -- Derived from Figure 6.25 from Snodgrass "Developing Time-Oriented -- Database Applications in SQL" CREATE TABLE Data ( Start DATE, Finish DATE, ID CHAR(2), Amount INT ); INSERT INTO Data VALUES('2008-10-01', '2008-10-02', '01', 10); INSERT INTO Data VALUES('2008-10-02', '2008-10-03', '02', 20); INSERT INTO Data VALUES('2008-10-03', '2008-10-04', '01', 38); INSERT INTO Data VALUES('2008-10-04', '2008-10-05', '01', 23); INSERT INTO Data VALUES('2008-10-05', '2008-10-06', '03', 14); INSERT INTO Data VALUES('2008-10-06', '2008-10-07', '02', 3); INSERT INTO Data VALUES('2008-10-07', '2008-10-08', '02', 8); INSERT INTO Data VALUES('2008-10-08', '2008-11-08', '03', 19); SELECT DISTINCT F.ID, F.Start, L.Finish FROM Data AS F, Data AS L WHERE F.Start < L.Finish AND F.ID = L.ID -- There are no gaps between F.Finish and L.Start AND NOT EXISTS (SELECT * FROM Data AS M WHERE M.ID = F.ID AND F.Finish < M.Start AND M.Start < L.Start AND NOT EXISTS (SELECT * FROM Data AS T1 WHERE T1.ID = F.ID AND T1.Start < M.Start AND M.Start <= T1.Finish)) -- Cannot be extended further AND NOT EXISTS (SELECT * FROM Data AS T2 WHERE T2.ID = F.ID AND ((T2.Start < F.Start AND F.Start <= T2.Finish) OR (T2.Start <= L.Finish AND L.Finish < T2.Finish))); ``` The output from that query is: ``` 01 2008-10-01 2008-10-02 01 2008-10-03 2008-10-05 02 2008-10-02 2008-10-03 02 2008-10-06 2008-10-08 03 2008-10-05 2008-10-06 03 2008-10-05 2008-11-08 03 2008-10-08 2008-11-08 ``` **Edited**: There's a problem with the penultimate row - it should not be there. And I'm not clear (yet) where it is coming from. Now we need to treat that complex expression as a query expression in the FROM clause of another SELECT statement, which will sum the amount values for a given ID over the entries that overlap with the maximal ranges shown above. ``` SELECT M.ID, M.Start, M.Finish, SUM(D.Amount) FROM Data AS D, (SELECT DISTINCT F.ID, F.Start, L.Finish FROM Data AS F, Data AS L WHERE F.Start < L.Finish AND F.ID = L.ID -- There are no gaps between F.Finish and L.Start AND NOT EXISTS (SELECT * FROM Data AS M WHERE M.ID = F.ID AND F.Finish < M.Start AND M.Start < L.Start AND NOT EXISTS (SELECT * FROM Data AS T1 WHERE T1.ID = F.ID AND T1.Start < M.Start AND M.Start <= T1.Finish)) -- Cannot be extended further AND NOT EXISTS (SELECT * FROM Data AS T2 WHERE T2.ID = F.ID AND ((T2.Start < F.Start AND F.Start <= T2.Finish) OR (T2.Start <= L.Finish AND L.Finish < T2.Finish)))) AS M WHERE D.ID = M.ID AND M.Start <= D.Start AND M.Finish >= D.Finish GROUP BY M.ID, M.Start, M.Finish ORDER BY M.ID, M.Start; ``` This gives: ``` ID Start Finish Amount 01 2008-10-01 2008-10-02 10 01 2008-10-03 2008-10-05 61 02 2008-10-02 2008-10-03 20 02 2008-10-06 2008-10-08 11 03 2008-10-05 2008-10-06 14 03 2008-10-05 2008-11-08 33 -- Here be trouble! 03 2008-10-08 2008-11-08 19 ``` **Edited**: This is *almost* the correct data set on which to do the COUNT and SUM aggregation requested by the original question, so the final answer is: ``` SELECT I.ID, COUNT(*) AS Number, SUM(I.Amount) AS Amount FROM (SELECT M.ID, M.Start, M.Finish, SUM(D.Amount) AS Amount FROM Data AS D, (SELECT DISTINCT F.ID, F.Start, L.Finish FROM Data AS F, Data AS L WHERE F.Start < L.Finish AND F.ID = L.ID -- There are no gaps between F.Finish and L.Start AND NOT EXISTS (SELECT * FROM Data AS M WHERE M.ID = F.ID AND F.Finish < M.Start AND M.Start < L.Start AND NOT EXISTS (SELECT * FROM Data AS T1 WHERE T1.ID = F.ID AND T1.Start < M.Start AND M.Start <= T1.Finish)) -- Cannot be extended further AND NOT EXISTS (SELECT * FROM Data AS T2 WHERE T2.ID = F.ID AND ((T2.Start < F.Start AND F.Start <= T2.Finish) OR (T2.Start <= L.Finish AND L.Finish < T2.Finish))) ) AS M WHERE D.ID = M.ID AND M.Start <= D.Start AND M.Finish >= D.Finish GROUP BY M.ID, M.Start, M.Finish ) AS I GROUP BY I.ID ORDER BY I.ID; id number amount 01 2 71 02 2 31 03 3 66 ``` **Review**: Oh! Drat...the entry for 3 has twice the 'amount' that it should have. Previous 'edited' parts indicate where things started to go wrong. It looks as though either the first query is subtly wrong (maybe it is intended for a different question), or the optimizer I'm working with is misbehaving. Nevertheless, there should be an answer closely related to this that will give the correct values. For the record: tested on IBM Informix Dynamic Server 11.50 on Solaris 10. However, should work fine on any other moderately standard-conformant SQL DBMS.
235,435
<p>Python's access to environment variables does not accurately reflect the operating system's view of the processes environment.</p> <p>os.getenv and os.environ do not function as expected in particular cases.</p> <p>Is there a way to properly get the running process' environment?</p> <hr> <p>To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; int main(int argc, char *argv[]){ char *env; for(;;){ env = getenv("SOME_VARIABLE"); if(env) puts(env); sleep(5); } } </code></pre> <hr> <pre><code>import os import time while True: env = os.getenv("SOME_VARIABLE") if env is not None: print env time.sleep(5) </code></pre> <hr> <p>Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this:</p> <pre><code>(gdb) print setenv("SOME_VARIABLE", "my value", 1) [Switching to Thread -1208600896 (LWP 16163)] $1 = 0 (gdb) print (char *)getenv("SOME_VARIABLE") $2 = 0x8293126 "my value" </code></pre> <p>then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not.</p> <p>Is there a way to get the python program to function like the C program in this case?</p> <p>(Yes, I realize this is a very obscure and potentially damaging action to perform on a running process)</p> <p>Also, I'm currently using python 2.4, this may have been fixed in a later version of python.</p>
[ { "answer_id": 235448, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 1, "selected": false, "text": "<p>Looking at the Python source code (2.4.5):</p>\n\n<ul>\n<li><p>Modules/posixmodule.c gets the environ in convertenviron() which gets run at startup (see INITFUNC) and stores the environment in a platform-specific module (nt, os2, or posix)</p></li>\n<li><p>Lib/os.py looks at sys.builtin_module_names, and imports all symbols from either posix, nt, or os2</p></li>\n</ul>\n\n<p>So yes, it gets decided at startup. os.environ is not going to be helpful here.</p>\n\n<p>If you really want to do this, then the most obvious approach that comes to mind is to create your own custom C-based python module, with a getenv that always invokes the system call.</p>\n" }, { "answer_id": 235475, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 5, "selected": true, "text": "<p>That's a very good question.</p>\n\n<p>It turns out that the <code>os</code> module initializes <code>os.environ</code> to the value of <a href=\"http://docs.python.org/library/posix.html\" rel=\"noreferrer\"><code>posix</code></a><code>.environ</code>, which is set on interpreter start up. In other words, the standard library does not appear to provide access to the <a href=\"http://www.opengroup.org/onlinepubs/000095399/functions/getenv.html\" rel=\"noreferrer\">getenv</a> function.</p>\n\n<p>That is a case where it would probably be safe to use <a href=\"http://docs.python.org/library/ctypes.html\" rel=\"noreferrer\">ctypes</a> on unix. Since you would be calling an ultra-standard libc function.</p>\n" }, { "answer_id": 236523, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I don't believe many programs EVER expect to have their environment externally modified, so loading a copy of the passed environment at startup is equivalent. You have simply stumbled on an implementation choice.</p>\n\n<p>If you are seeing all the set-at-startup values and putenv/setenv from within your program works, I don't think there's anything to be concerned about. There are far cleaner ways to pass updated information to running executables.</p>\n" }, { "answer_id": 237217, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "<p>Another possibility is to use pdb, or some other python debugger instead, and change os.environ at the python level, rather than the C level. <a href=\"https://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#133384\">Here's</a> a small recipe I posted to interrupt a running python process and provide access to a python console on receiving a signal. Alternatively, just stick a pdb.set_trace() at some point in your code you want to interrupt. In either case, just run the statement \"<code>import os; os.environ['SOME_VARIABLE']='my_value'</code>\" and you should be updated as far as python is concerned. </p>\n\n<p>I'm not sure if this will also update the C environment with setenv, so if you have C modules using getenv directly you may have to do some more work to keep this in sync.</p>\n" }, { "answer_id": 242175, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 4, "selected": false, "text": "<p>You can use <code>ctypes</code> to do this pretty simply:</p>\n\n<pre><code>&gt;&gt;&gt; from ctypes import CDLL, c_char_p\n&gt;&gt;&gt; getenv = CDLL(\"libc.so.6\").getenv\n&gt;&gt;&gt; getenv.restype = c_char_p\n&gt;&gt;&gt; getenv(\"HOME\")\n'/home/glyph'\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9241/" ]
Python's access to environment variables does not accurately reflect the operating system's view of the processes environment. os.getenv and os.environ do not function as expected in particular cases. Is there a way to properly get the running process' environment? --- To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python): ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]){ char *env; for(;;){ env = getenv("SOME_VARIABLE"); if(env) puts(env); sleep(5); } } ``` --- ``` import os import time while True: env = os.getenv("SOME_VARIABLE") if env is not None: print env time.sleep(5) ``` --- Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this: ``` (gdb) print setenv("SOME_VARIABLE", "my value", 1) [Switching to Thread -1208600896 (LWP 16163)] $1 = 0 (gdb) print (char *)getenv("SOME_VARIABLE") $2 = 0x8293126 "my value" ``` then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not. Is there a way to get the python program to function like the C program in this case? (Yes, I realize this is a very obscure and potentially damaging action to perform on a running process) Also, I'm currently using python 2.4, this may have been fixed in a later version of python.
That's a very good question. It turns out that the `os` module initializes `os.environ` to the value of [`posix`](http://docs.python.org/library/posix.html)`.environ`, which is set on interpreter start up. In other words, the standard library does not appear to provide access to the [getenv](http://www.opengroup.org/onlinepubs/000095399/functions/getenv.html) function. That is a case where it would probably be safe to use [ctypes](http://docs.python.org/library/ctypes.html) on unix. Since you would be calling an ultra-standard libc function.
235,437
<p>Given the following file:</p> <pre><code>department=value1 location=valueA location=valueB department=value2 </code></pre> <p>I use the following to load the file into a Perl hash:</p> <pre><code>use File::Slurp; use Data::Dumper; my %hash = map { s/#.*//; s/^\s+//; s/\s+$//; m/(.*?)\s*=\s*(.*)/; } read_file($file); print Dumper(\%hash); </code></pre> <p>The result, however, is as follows:</p> <pre><code>$VAR1 = { 'location' =&gt; 'valueB', 'department' =&gt; 'value2' }; </code></pre> <p>How can I load the above file into a hash with, say,</p> <pre><code>$VAR1 = { 'location' =&gt; 'valueA,valueB', 'department' =&gt; 'value1,value2' }; </code></pre> <p>Thanks.</p>
[ { "answer_id": 235489, "author": "Nikhil", "author_id": 5734, "author_profile": "https://Stackoverflow.com/users/5734", "pm_score": 6, "selected": true, "text": "<p>Here you go:</p>\n\n<pre><code>my %hash;\nwhile (&lt;FILE&gt;)\n{\n chomp;\n my ($key, $val) = split /=/;\n $hash{$key} .= exists $hash{$key} ? \",$val\" : $val;\n}\n</code></pre>\n\n<p>This walks through every line splitting on the '=' sign and either adds an entry or appends to an existing entry in the hash table.</p>\n" }, { "answer_id": 235500, "author": "Mark", "author_id": 9303, "author_profile": "https://Stackoverflow.com/users/9303", "pm_score": -1, "selected": false, "text": "<p>Can you add some code to your map function to check for the existence of a hash entry and append the new value?</p>\n\n<p>I haven't done Perl in a while, but when I did something like this in the past, I read the file in line by line (while $inputLine = &lt;FILE&gt;) and used split on '=' to load the hash with additional checks to see if the hash already had that key, appending if the entry already existed.</p>\n" }, { "answer_id": 237256, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 3, "selected": false, "text": "<p>If you have control over the data file, consider switching from a custom format to something like YAML. This gives you a lot of power out of the box without having to hack your custom format more and more. In particular, multiple keys creating a list is non-obvious. YAML's way of doing it is much clearer.</p>\n\n<pre><code>name: Wally Jones\ndepartment: [foo, bar]\nlocation: [baz, biff]\n</code></pre>\n\n<p>Note also that YAML allows you to sculpt the key/value pairs so they line up for easier reading.</p>\n\n<p>And the code to parse it is done by a module, <a href=\"http://search.cpan.org/perldoc?YAML::XS\" rel=\"nofollow noreferrer\">YAML::XS</a> being the best of the bunch.</p>\n\n<pre><code>use File::Slurp;\nuse YAML::XS;\nuse Data::Dumper;\n\nprint Dumper Load scalar read_file(shift);\n</code></pre>\n\n<p>And the data structure looks like so:</p>\n\n<pre><code>$VAR1 = {\n 'department' =&gt; [\n 'foo',\n 'bar'\n ],\n 'location' =&gt; [\n 'baz',\n 'biff'\n ],\n 'name' =&gt; 'Wally Jones'\n };\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Given the following file: ``` department=value1 location=valueA location=valueB department=value2 ``` I use the following to load the file into a Perl hash: ``` use File::Slurp; use Data::Dumper; my %hash = map { s/#.*//; s/^\s+//; s/\s+$//; m/(.*?)\s*=\s*(.*)/; } read_file($file); print Dumper(\%hash); ``` The result, however, is as follows: ``` $VAR1 = { 'location' => 'valueB', 'department' => 'value2' }; ``` How can I load the above file into a hash with, say, ``` $VAR1 = { 'location' => 'valueA,valueB', 'department' => 'value1,value2' }; ``` Thanks.
Here you go: ``` my %hash; while (<FILE>) { chomp; my ($key, $val) = split /=/; $hash{$key} .= exists $hash{$key} ? ",$val" : $val; } ``` This walks through every line splitting on the '=' sign and either adds an entry or appends to an existing entry in the hash table.
235,439
<p>The way I do 80-column indication in Vim seems incorrect:<code>set columns=80</code>. At times I also <code>set textwidth</code>, but I want to be able to see and anticipate line overflow with the <code>set columns</code> alternative.</p> <p>This has some <strong>unfortunate</strong> side effects:</p> <ol> <li>I can't <code>set number</code> for fear of splitting between files that have different orders of line numbers; i.e. &lt; 100 line files and >= 100 line files will require two different <code>set columns</code> values because of the extra column used for the additional digit display. </li> <li>I also start new (g)Vim sessions instead of splitting windows vertically. This is because <code>vsplit</code> forces me to <code>set columns</code> every time I open or close a pane, so starting a new session is less hassle.</li> </ol> <p>How do you handle the 80-character indication when you want to <code>set numbers</code>, vertically split, etc.?</p>
[ { "answer_id": 235501, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 3, "selected": false, "text": "<p>I'm afraid that you've put constraints on the set of solutions that, well, leave you with the null set.</p>\n\n<p>Using <code>:set textwidth=80</code> will fix all of the problems you mentioned <em>except</em> that you can't easily see the line limit coming up. If you <code>:set ruler</code>, you'll enable the x,y position display on the status bar, which you can use to see which column you're in.</p>\n\n<p>Aside from that, I'm not sure what to tell you. It's a shame to lose the number column, fold column and splits just because you have to <code>:set columns=80</code>.</p>\n" }, { "answer_id": 235599, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 3, "selected": false, "text": "<p>Newer versions of vim allow a <code>:set numberwidth=x</code> value, which sets the width of the line number display. I don't really use folding etc, so I wouldn't know about that though. Drawing a thin vertical line is beyond the abilities of a console application though. GVim may allow this (I don't use it, so can't comment there).</p>\n" }, { "answer_id": 235962, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "<p>You can try this:</p>\n\n<pre><code>au BufWinEnter * if &amp;textwidth &gt; 8\n\\ | let w:m1=matchadd('MatchParen', printf('\\%%&lt;%dv.\\%%&gt;%dv', &amp;textwidth+1, &amp;textwidth-8), -1)\n\\ | let w:m2=matchadd('ErrorMsg', printf('\\%%&gt;%dv.\\+', &amp;textwidth), -1)\n\\ | endif\n</code></pre>\n\n<p>That will set up two highlights in every buffer, one for characters in the 8 columns prior to whatever your <code>&amp;textwidth</code> is set to, and one for characters beyond that column. That way you have some extent of anticipation. Of course you can tweak it to use a different width if you want more or less anticipation (which you pay for in the form of loss of syntax highlighting in those columns).</p>\n" }, { "answer_id": 235970, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 10, "selected": true, "text": "<p>I have this set up in my .vimrc:</p>\n\n<pre><code>highlight OverLength ctermbg=red ctermfg=white guibg=#592929\nmatch OverLength /\\%81v.\\+/\n</code></pre>\n\n<p>This highlights the background in a subtle red for text that goes over the 80 column limit (subtle in GUI mode, anyway - in terminal mode it's less so).</p>\n" }, { "answer_id": 1117367, "author": "Maksim Vi.", "author_id": 136666, "author_profile": "https://Stackoverflow.com/users/136666", "pm_score": 6, "selected": false, "text": "<p>Shorter way:</p>\n\n<pre><code>match ErrorMsg '\\%&gt;80v.\\+'\n</code></pre>\n" }, { "answer_id": 3305790, "author": "Z.Zen", "author_id": 345844, "author_profile": "https://Stackoverflow.com/users/345844", "pm_score": 5, "selected": false, "text": "<p>Simon Howard's answer is great. But <code>/\\%81v.\\+/</code> fails to highlight tabs that exceed column 81 . So I did a little tweak, based on the stuff I found on <a href=\"http://vim.wikia.com/wiki/VimTip810\" rel=\"nofollow noreferrer\">VIM wiki</a> and HS's choice of colors above:</p>\n\n<pre><code>highlight OverLength ctermbg=darkred ctermfg=white guibg=#FFD9D9\nmatch OverLength /\\%&gt;80v.\\+/\n</code></pre>\n\n<p>And now VIM will highlight anything that exceeds column 80.</p>\n" }, { "answer_id": 3765575, "author": "Jeremy W. Sherman", "author_id": 72508, "author_profile": "https://Stackoverflow.com/users/72508", "pm_score": 10, "selected": false, "text": "<p>As of vim 7.3, you can use <code>set colorcolumn=80</code> (<code>set cc=80</code> for short).</p>\n\n<p>Since earlier versions do not support this, my <code>.vimrc</code> uses instead:</p>\n\n<pre><code>if exists('+colorcolumn')\n set colorcolumn=80\nelse\n au BufWinEnter * let w:m2=matchadd('ErrorMsg', '\\%&gt;80v.\\+', -1)\nendif\n</code></pre>\n\n<p>See also <a href=\"http://vimdoc.sourceforge.net/htmldoc/options.html#%27colorcolumn%27\" rel=\"noreferrer\">the online documentation on the <code>colorcolumn</code> option</a>.</p>\n" }, { "answer_id": 3809577, "author": "Ding-Yi Chen", "author_id": 350580, "author_profile": "https://Stackoverflow.com/users/350580", "pm_score": 2, "selected": false, "text": "<p>Well, looking at the :help columns, it's not really being made to mess with.</p>\n\n<p>In console, it's usually determined by console setting (i.e. it's detected automatically) ; in GUI, it determines (and is determined by) the width of the gvim windows.</p>\n\n<p>So normally you just let consoles and window managers doing their jobs by commented out the <code>set columns</code></p>\n\n<p>I am not sure what you mean by \"see and anticipate line overflow\".\nIf you want EOL to be inserted roughly column 80, use either <code>set textwidth</code> or <code>set wrapmargin</code>; if you just want soft wrap (i.e. line is wrapped, but no actual EOL), then play with <code>set linebreak</code> and <code>set showbreak</code>.</p>\n" }, { "answer_id": 4431701, "author": "Mike L", "author_id": 540835, "author_profile": "https://Stackoverflow.com/users/540835", "pm_score": 1, "selected": false, "text": "<p>You can try this to set the window size to allow 80 characters of actual text. This still doesn't work with vertical splits though.</p>\n\n<p><code>let &amp;co=80 + &amp;foldcolumn + (&amp;number || &amp;relativenumber ? &amp;numberwidth : 0)</code></p>\n\n<p>This requires vim 7+, 7.3 for relativenumber.</p>\n" }, { "answer_id": 14082092, "author": "ErichBSchulz", "author_id": 894487, "author_profile": "https://Stackoverflow.com/users/894487", "pm_score": 2, "selected": false, "text": "<p>this one is out of left field but its a nice little map for resizing your current split to 80 characters if you've got the line numbers on:</p>\n\n<pre><code>\" make window 80 + some for numbers wide \nnoremap &lt;Leader&gt;w :let @w=float2nr(log10(line(\"$\")))+82\\|:vertical resize &lt;c-r&gt;w&lt;cr&gt; \n</code></pre>\n" }, { "answer_id": 21406581, "author": "Dominykas Mostauskis", "author_id": 1714997, "author_profile": "https://Stackoverflow.com/users/1714997", "pm_score": 4, "selected": false, "text": "<p><img src=\"https://i.stack.imgur.com/AGsQy.png\" alt=\"enter image description here\"></p>\n\n<p>Minimalistic, not-over-the-top approach. Only the 79th character of lines that are too long gets highlighted. It overcomes a few common problems: works on new windows, overflowing words are highlighted properly.</p>\n\n<pre><code>augroup collumnLimit\n autocmd!\n autocmd BufEnter,WinEnter,FileType scala,java\n \\ highlight CollumnLimit ctermbg=DarkGrey guibg=DarkGrey\n let collumnLimit = 79 \" feel free to customize\n let pattern =\n \\ '\\%&lt;' . (collumnLimit+1) . 'v.\\%&gt;' . collumnLimit . 'v'\n autocmd BufEnter,WinEnter,FileType scala,java\n \\ let w:m1=matchadd('CollumnLimit', pattern, -1)\naugroup END\n</code></pre>\n\n<p>Note: notice the <code>FileType scala,java</code> this limits this to Scala and Java source files. You'll probably want to customize this. If you were to omit it, it would work on all file types.</p>\n" }, { "answer_id": 26685437, "author": "Shanded", "author_id": 3624253, "author_profile": "https://Stackoverflow.com/users/3624253", "pm_score": 4, "selected": false, "text": "<p>A nice way of marking just the first character going out of the specified bounds:</p>\n\n<pre><code>highlight ColorColumn ctermbg=magenta \"set to whatever you like\ncall matchadd('ColorColumn', '\\%81v', 100) \"set column nr\n</code></pre>\n\n<p>From Damian Conway's <a href=\"https://www.youtube.com/watch?v=aHm36-na4-4\" rel=\"noreferrer\">talk</a>.</p>\n" }, { "answer_id": 30265194, "author": "0x8BADF00D", "author_id": 2196150, "author_profile": "https://Stackoverflow.com/users/2196150", "pm_score": 4, "selected": false, "text": "<p>You also can draw line to see 80 limit:</p>\n\n<pre><code>let &amp;colorcolumn=join(range(81,999),\",\")\nlet &amp;colorcolumn=\"80,\".join(range(400,999),\",\")\n</code></pre>\n\n<p>Result:</p>\n\n<p><img src=\"https://i.stack.imgur.com/6kqGm.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 35794968, "author": "wieczorek1990", "author_id": 761200, "author_profile": "https://Stackoverflow.com/users/761200", "pm_score": 6, "selected": false, "text": "<p>I prefer:</p>\n\n<pre><code>highlight ColorColumn ctermbg=gray\nset colorcolumn=80\n</code></pre>\n" }, { "answer_id": 70432783, "author": "Techie", "author_id": 6764110, "author_profile": "https://Stackoverflow.com/users/6764110", "pm_score": 0, "selected": false, "text": "<p>set column line using set colorcolumn</p>\n<pre><code>set autoindent \nset smartindent \nset nowrap \nset hlsearch \nset tabstop=4 \nset shiftwidth=4 \nsyntax on \nset colorcolumn=80\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
The way I do 80-column indication in Vim seems incorrect:`set columns=80`. At times I also `set textwidth`, but I want to be able to see and anticipate line overflow with the `set columns` alternative. This has some **unfortunate** side effects: 1. I can't `set number` for fear of splitting between files that have different orders of line numbers; i.e. < 100 line files and >= 100 line files will require two different `set columns` values because of the extra column used for the additional digit display. 2. I also start new (g)Vim sessions instead of splitting windows vertically. This is because `vsplit` forces me to `set columns` every time I open or close a pane, so starting a new session is less hassle. How do you handle the 80-character indication when you want to `set numbers`, vertically split, etc.?
I have this set up in my .vimrc: ``` highlight OverLength ctermbg=red ctermfg=white guibg=#592929 match OverLength /\%81v.\+/ ``` This highlights the background in a subtle red for text that goes over the 80 column limit (subtle in GUI mode, anyway - in terminal mode it's less so).
235,446
<p>Anybody have a slicker way to do this? Seems like it should be easier than this, but I'm having a mental block. Basically I need to remove items from an dictionary and recurse into the values of the items that are also dictionaries.</p> <pre><code>private void RemoveNotPermittedItems(ActionDictionary menu) { var keysToRemove = new List&lt;string&gt;(); foreach (var item in menu) { if (!GetIsPermitted(item.Value.Call)) { keysToRemove.Add(item.Key); } else if (item.Value is ActionDictionary) { RemoveNotPermittedItems((ActionDictionary)item.Value); if (((ActionDictionary)item.Value).Count == 0) { keysToRemove.Add(item.Key); } } } foreach (var key in (from item in menu where keysToRemove.Contains(item.Key) select item.Key).ToArray()) { menu.Remove(key); } } </code></pre> <p>Action dictionary is like this:</p> <pre><code>public class ActionDictionary : Dictionary&lt;string, IActionItem&gt;, IActionItem </code></pre>
[ { "answer_id": 235469, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>To start with, your <code>foreach</code> loop is way more complicated than it needs to be. Just do:</p>\n\n<pre><code>foreach (var key in keysToRemove)\n{\n menu.Remove(key);\n}\n</code></pre>\n\n<p>I'm slightly surprised that <code>Dictionary</code> doesn't have a <code>RemoveAll</code> method but it doesn't look like it does...</p>\n" }, { "answer_id": 235756, "author": "Geoff Cox", "author_id": 30505, "author_profile": "https://Stackoverflow.com/users/30505", "pm_score": 1, "selected": false, "text": "<p>Option 1: A Dictionary is still a Collection. Iterate over menu.Values.</p>\n\n<p>You can iterate over menu.Values and remove them as you iterate. The values won't come in any sorted order (which should be fine for your case). You may need to use a for loop and adjust the index rather than using foreach - the enumerator will throw an exception if you modify the collection while iterating.</p>\n\n<p>(I'll try to add the code when I'm on my dev machine Mon)</p>\n\n<p>Option 2: Create a custom iterator.</p>\n\n<p>Some collections returned from ListBox SelectedItems in Winforms don't really contain the collection, they provide a wrapper around the underlying collection. Kind of like CollectionViewSource in WPF. ReadOnlyCollection does something similar too.</p>\n\n<p>Create a class that can \"flatten\" your nested dictionaries into something that can enumerate over them like they are a single collection. Implement a delete function that looks like it removes an item from the collection, but really removes from the current dictionary.</p>\n" }, { "answer_id": 235916, "author": "Lex Li", "author_id": 11182, "author_profile": "https://Stackoverflow.com/users/11182", "pm_score": 2, "selected": false, "text": "<p>While foreach and GetEnumerator fails, a for-loop works, </p>\n\n<p><code></p>\n\n<pre><code>var table = new Dictionary&lt;string, int&gt;() {{\"first\", 1}, {\"second\", 2}};\nfor (int i = 0; i &lt; table.Keys.Count; i++)//string key in table.Keys)\n{\n string key = table.Keys.ElementAt(i);\n if (key.StartsWith(\"f\"))\n {\n table.Remove(key);\n }\n}\n</code></pre>\n\n<p></code></p>\n\n<p>But ElementAt() is a .NET 3.5 feature.</p>\n" }, { "answer_id": 235994, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": true, "text": "<p>You don't really need to collect the keys and iterate them again if you iterate the dictionary in reverse (from 'menu.Count - 1' to zero). Iterating in forward order will, of course, yield mutated collection exceptions if you start removing things.</p>\n\n<p>I don't know what an ActionDictionary is, so I couldn't test your exact scenario, but here's an example using just <code>Dictionary&lt;string,object&gt;</code>.</p>\n\n<pre><code> static int counter = 0;\n private static void RemoveNotPermittedItems(Dictionary&lt;string, object&gt; menu)\n {\n for (int c = menu.Count - 1; c &gt;= 0; c--)\n {\n var key = menu.Keys.ElementAt(c);\n var value = menu[key];\n if (value is Dictionary&lt;string, object&gt;)\n {\n RemoveNotPermittedItems((Dictionary&lt;string, object&gt;)value);\n if (((Dictionary&lt;string, object&gt;)value).Count == 0)\n {\n menu.Remove(key);\n }\n }\n else if (!GetIsPermitted(value))\n {\n menu.Remove(key);\n }\n }\n }\n\n // This just added to actually cause some elements to be removed...\n private static bool GetIsPermitted(object value)\n {\n if (counter++ % 2 == 0)\n return false;\n return true;\n }\n</code></pre>\n\n<p>I also reversed the 'if' statement, but that was just an assumption that you'd want to do type checking before calling a method to act on the item's value...it will work either way assuming 'GetIsPermitted' always returns TRUE for ActionDictionary.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 10566049, "author": "Writwick", "author_id": 1118933, "author_profile": "https://Stackoverflow.com/users/1118933", "pm_score": 1, "selected": false, "text": "<p>In My Opinion, you can define your own generic class deriving from the <code>KeyValuePair&lt;...&gt;</code> both TKey and TValue will be <code>List&lt;T&gt;</code> and you can use the <code>RemoveAll</code> or the <code>RemoveRange</code> of the <code>List&lt;T&gt;</code> in a new <code>RemoveRange()</code> or <code>RemoveAll()</code> method in your derived class to Remove the items you want.</p>\n" }, { "answer_id": 10623148, "author": "Val Bakhtin", "author_id": 798261, "author_profile": "https://Stackoverflow.com/users/798261", "pm_score": 1, "selected": false, "text": "<p>I know you probably found good solution already, but just for the reason of 'slickness' if you could modify your method signatures to (I know it may not be appropriate in your scenario):</p>\n\n<pre><code>private ActionDictionary RemoveNotPermittedItems(ActionDictionary menu)\n{\n return new ActionDictionary(from item in menu where GetIsPermitted(item.Value.Call) select item)\n.ToDictionary(d=&gt;d.Key, d=&gt;d.Value is ActionDictionary?RemoveNotPermittedItems(d.Value as ActionDictionary) : d.Value));\n}\n</code></pre>\n\n<p>And I can see couple ways where you can use your dictionary with filtered items without modification and materializing new dictionaries.</p>\n" }, { "answer_id": 10638955, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 1, "selected": false, "text": "<p>It's not much less complicated, but some idiomatic changes make it a bit shorter and easier on the eyes:</p>\n\n<pre><code> private static void RemoveNotPermittedItems(IDictionary&lt;string, IActionItem&gt; menu)\n {\n var keysToRemove = new List&lt;string&gt;();\n\n foreach (var item in menu)\n {\n if (GetIsPermitted(item.Value.Call))\n {\n var value = item.Value as ActionDictionary;\n\n if (value != null)\n {\n RemoveNotPermittedItems(value);\n if (!value.Any())\n {\n keysToRemove.Add(item.Key);\n }\n }\n }\n else\n {\n keysToRemove.Add(item.Key);\n }\n }\n\n foreach (var key in keysToRemove)\n {\n menu.Remove(key);\n }\n }\n\n private static bool GetIsPermitted(object call)\n {\n return ...;\n }\n</code></pre>\n" }, { "answer_id": 10640444, "author": "Gebb", "author_id": 129073, "author_profile": "https://Stackoverflow.com/users/129073", "pm_score": 1, "selected": false, "text": "<p>Change the type of the <code>keysToRemove</code> to <code>HashSet&lt;string&gt;</code> and you'll get an O(1) <code>Contains</code> method. With <code>List&lt;string&gt;</code> it's O(n), which is slower as you might guess.</p>\n" }, { "answer_id": 10646195, "author": "ZagNut", "author_id": 401659, "author_profile": "https://Stackoverflow.com/users/401659", "pm_score": 1, "selected": false, "text": "<p>untested until i'm at my VS machine tomorrow :o</p>\n\n<pre><code>private void RemoveNotPermittedItems(ActionDictionary menu)\n{\n foreach(var _checked in (from m in menu\n select new\n {\n gip = !GetIsPermitted(m.Value.Call),\n recur = m.Value is ActionDictionary,\n item = m\n }).ToArray())\n {\n ActionDictionary tmp = _checked.item.Value as ActionDictionary;\n if (_checked.recur)\n {\n RemoveNotPermittedItems(tmp);\n }\n if (_checked.gip || (tmp != null &amp;&amp; tmp.Count == 0) {\n menu.Remove(_checked.item.Key);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 10650748, "author": "misha", "author_id": 1403091, "author_profile": "https://Stackoverflow.com/users/1403091", "pm_score": 1, "selected": false, "text": "<p>I think</p>\n\n<pre><code>public class ActionSet : HashSet&lt;IActionItem&gt;, IActionItem\n</code></pre>\n\n<p>And</p>\n\n<pre><code>bool Clean(ActionSet nodes)\n {\n if (nodes != null)\n {\n var removed = nodes.Where(n =&gt; this.IsNullOrNotPermitted(n) || !this.IsNotSetOrNotEmpty(n) || !this.Clean(n as ActionSet));\n\n removed.ToList().ForEach(n =&gt; nodes.Remove(n));\n\n return nodes.Any();\n }\n\n return true;\n }\n\n bool IsNullOrNotPermitted(IActionItem node)\n {\n return node == null || *YourTest*(node.Call);\n }\n\n bool IsNotSetOrNotEmpty(IActionItem node)\n {\n var hset = node as ActionSet;\n return hset == null || hset.Any();\n }\n</code></pre>\n\n<p>Should work fast</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29493/" ]
Anybody have a slicker way to do this? Seems like it should be easier than this, but I'm having a mental block. Basically I need to remove items from an dictionary and recurse into the values of the items that are also dictionaries. ``` private void RemoveNotPermittedItems(ActionDictionary menu) { var keysToRemove = new List<string>(); foreach (var item in menu) { if (!GetIsPermitted(item.Value.Call)) { keysToRemove.Add(item.Key); } else if (item.Value is ActionDictionary) { RemoveNotPermittedItems((ActionDictionary)item.Value); if (((ActionDictionary)item.Value).Count == 0) { keysToRemove.Add(item.Key); } } } foreach (var key in (from item in menu where keysToRemove.Contains(item.Key) select item.Key).ToArray()) { menu.Remove(key); } } ``` Action dictionary is like this: ``` public class ActionDictionary : Dictionary<string, IActionItem>, IActionItem ```
You don't really need to collect the keys and iterate them again if you iterate the dictionary in reverse (from 'menu.Count - 1' to zero). Iterating in forward order will, of course, yield mutated collection exceptions if you start removing things. I don't know what an ActionDictionary is, so I couldn't test your exact scenario, but here's an example using just `Dictionary<string,object>`. ``` static int counter = 0; private static void RemoveNotPermittedItems(Dictionary<string, object> menu) { for (int c = menu.Count - 1; c >= 0; c--) { var key = menu.Keys.ElementAt(c); var value = menu[key]; if (value is Dictionary<string, object>) { RemoveNotPermittedItems((Dictionary<string, object>)value); if (((Dictionary<string, object>)value).Count == 0) { menu.Remove(key); } } else if (!GetIsPermitted(value)) { menu.Remove(key); } } } // This just added to actually cause some elements to be removed... private static bool GetIsPermitted(object value) { if (counter++ % 2 == 0) return false; return true; } ``` I also reversed the 'if' statement, but that was just an assumption that you'd want to do type checking before calling a method to act on the item's value...it will work either way assuming 'GetIsPermitted' always returns TRUE for ActionDictionary. Hope this helps.
235,455
<pre><code>string [] files = new string[2]; files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml"; files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml"; //Resharper complains this is an "access to modified closure" for (int i = 0; i &lt; files.Length; i++ ) { // Resharper disable AccessToModifiedClosure if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(), delegate(string name) { return name.Equals(files[i]); })) return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]); // ReSharper restore AccessToModifiedClosure } </code></pre> <p>The above seems to work fine though ReSharper complains that this is "access to modified closure". Can any one shed light on this?</p> <p>(this topic continued <a href="https://stackoverflow.com/questions/304258">here</a>)</p>
[ { "answer_id": 235459, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p>In this case, it's okay, since you are actually executing the delegate <em>within</em> the loop.</p>\n\n<p>If you were saving the delegate and using it later, however, you'd find that all of the delegates would throw exceptions when trying to access files[i] - they're capturing the <em>variable</em> <code>i</code> rather than its value at the time of the delegates creation.</p>\n\n<p>In short, it's something to be aware of as a <em>potential</em> trap, but in this case it doesn't hurt you.</p>\n\n<p>See the <a href=\"http://jonskeet.uk/csharp/csharp2/delegates.html#captured.variables\" rel=\"noreferrer\">bottom of this page</a> for a more complex example where the results are counterintuitive.</p>\n" }, { "answer_id": 15708331, "author": "gerrard00", "author_id": 1011470, "author_profile": "https://Stackoverflow.com/users/1011470", "pm_score": 5, "selected": false, "text": "<p>I know this is an old question, but I've recently been studying closures and thought a code sample might be useful. Behind the scenes, the compiler is generating a class that represents a lexical closure for your function call. It probably looks something like:</p>\n\n<pre><code>private sealed class Closure\n{\n public string[] files;\n public int i;\n\n public bool YourAnonymousMethod(string name)\n {\n return name.Equals(this.files[this.i]);\n }\n}\n</code></pre>\n\n<p>As mentioned above, your function works because the predicates are invoked immediately after creation. The compiler will generate something like:</p>\n\n<pre><code>private string Works()\n{\n var closure = new Closure();\n\n closure.files = new string[3];\n closure.files[0] = \"notfoo\";\n closure.files[1] = \"bar\";\n closure.files[2] = \"notbaz\";\n\n var arrayToSearch = new string[] { \"foo\", \"bar\", \"baz\" };\n\n //this works, because the predicates are being executed during the loop\n for (closure.i = 0; closure.i &lt; closure.files.Length; closure.i++)\n {\n if (Array.Exists(arrayToSearch, closure.YourAnonymousMethod))\n return closure.files[closure.i];\n }\n\n return null;\n}\n</code></pre>\n\n<p>On the other hand, if you were to store and then later invoke the predicates, you would see that every single call to the predicates would really be calling the same method on the same instance of the closure class and therefore would use the same value for i.</p>\n" }, { "answer_id": 45665676, "author": "chris hu", "author_id": 2612134, "author_profile": "https://Stackoverflow.com/users/2612134", "pm_score": 2, "selected": false, "text": "<p>\"files\" is a <strong>captured outer variable</strong> because it has been captured by the anonymous delegate function. Its lifetime is extended by the anonymous delegate function.</p>\n\n<blockquote>\n <p>Captured outer variables\n When an outer variable is referenced by an anonymous function, the outer variable is said to have been captured by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated (Local variables). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.</p>\n</blockquote>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#outer-variables\" rel=\"nofollow noreferrer\">Outer Variables on MSDN</a></p>\n\n<blockquote>\n <p>When a local variable or a value parameter is captured by an anonymous function, the local variable or parameter is no longer considered to be a fixed variable (Fixed and moveable variables), but is instead considered to be a moveable variable. Thus any unsafe code that takes the address of a captured outer variable must first use the fixed statement to fix the variable.\n Note that unlike an uncaptured variable, a captured local variable can be simultaneously exposed to multiple threads of execution.</p>\n</blockquote>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28413/" ]
``` string [] files = new string[2]; files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml"; files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml"; //Resharper complains this is an "access to modified closure" for (int i = 0; i < files.Length; i++ ) { // Resharper disable AccessToModifiedClosure if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(), delegate(string name) { return name.Equals(files[i]); })) return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]); // ReSharper restore AccessToModifiedClosure } ``` The above seems to work fine though ReSharper complains that this is "access to modified closure". Can any one shed light on this? (this topic continued [here](https://stackoverflow.com/questions/304258))
In this case, it's okay, since you are actually executing the delegate *within* the loop. If you were saving the delegate and using it later, however, you'd find that all of the delegates would throw exceptions when trying to access files[i] - they're capturing the *variable* `i` rather than its value at the time of the delegates creation. In short, it's something to be aware of as a *potential* trap, but in this case it doesn't hurt you. See the [bottom of this page](http://jonskeet.uk/csharp/csharp2/delegates.html#captured.variables) for a more complex example where the results are counterintuitive.
235,515
<p>Way back when I was working in an Oracle shop I took the CONNECT_BY for granted. Now I'm stuck working with SQL Server 2005 and have some nasty object hierarchies. Specifically, we have a self referencing table where all child records have a column with their parent's id. Currently we have a view that maps children to levels in the hierarchy and a nasty query that does the heavy lifting to connect parents with their children. While this method works, it is far from elegant and reeks of taint. I'm just curious how other people retrieve hierarchical data from SQL Server 2005.</p>
[ { "answer_id": 235531, "author": "Mladen Prajdic", "author_id": 31345, "author_profile": "https://Stackoverflow.com/users/31345", "pm_score": 1, "selected": false, "text": "<p>in SQL Server 2005 you can use Common Table Expressions (CTE) for this.</p>\n" }, { "answer_id": 235534, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 5, "selected": false, "text": "<p>This creates your typical hierarchical table and uses a CTE to select the hierarchy structure and create a path for each item.</p>\n\n<pre><code>CREATE TABLE tblHierarchy (ID int, ParentID int NULL, Name varchar(128));\n\nINSERT INTO tblHierarchy VALUES (1, NULL, '1');\nINSERT INTO tblHierarchy VALUES (2, NULL, '2');\nINSERT INTO tblHierarchy VALUES (3, NULL, '3');\nINSERT INTO tblHierarchy VALUES (4, 1, '1.1');\nINSERT INTO tblHierarchy VALUES (5, 1, '1.2');\nINSERT INTO tblHierarchy VALUES (6, 4, '1.1.1');\n\nWITH Parent AS\n(\n SELECT\n ID,\n ParentID,\n Name AS Path\n FROM\n tblHierarchy\n WHERE\n ParentID IS NULL\n\n UNION ALL\n\n SELECT\n TH.ID,\n TH.ParentID,\n CONVERT(varchar(128), Parent.Path + '/' + TH.Name) AS Path\n FROM\n tblHierarchy TH\n INNER JOIN\n Parent\n ON\n Parent.ID = TH.ParentID\n)\nSELECT * FROM Parent\n</code></pre>\n\n<p>OUTPUT:</p>\n\n<pre><code>ID ParentID Path\n1 NULL 1\n2 NULL 2\n3 NULL 3\n4 1 1/1.1\n5 1 1/1.2\n6 4 1/1.1/1.1.1\n</code></pre>\n" }, { "answer_id": 235536, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>Just FYI. SQL Server 2008 supports a new data type <a href=\"http://msdn.microsoft.com/en-us/magazine/cc794278.aspx\" rel=\"nofollow noreferrer\">Hierarchy ID</a>.</p>\n" }, { "answer_id": 235543, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "<p>Having used both, I found CONNECT BY is somewhat more flexible and easier to use than CTE's. The question is not dissimilar to one I answered a few weeks ago. See <a href=\"https://stackoverflow.com/questions/112866/database-schema-for-a-hierarchial-groups#114477\">Here</a> for a brief comparison of CONNECT BY and CTE's and <a href=\"https://stackoverflow.com/questions/69923/stored-procedures-reverse-engineering#93967\">Here</a> for an example of a query using CTE's.</p>\n" }, { "answer_id": 9529223, "author": "Noora Akhtar", "author_id": 1244481, "author_profile": "https://Stackoverflow.com/users/1244481", "pm_score": 0, "selected": false, "text": "<p>To traverse the Depth of the Hierarchy first then the next sibling level,\nCTE can be used:</p>\n\n<pre><code>declare @tempTable TABLE\n(\n ORGUID int,\n ORGNAME nvarchar(100), \n PARENTORGUID int,\n ORGPATH nvarchar(max)\n)\n\n;WITH RECORG(ORGuid, ORGNAME, PARENTORGUID, ORGPATH)\nas\n(\n select \n org.UID,\n org.Name,\n org.ParentOrganizationUID,\n dbo.fGetOrganizationBreadcrumbs(org.UID)\n from Organization org\n where org.UID =1\n\n union all\n\n select \n orgRec.UID,\n orgRec.Name,\n orgRec.ParentOrganizationUID,\n dbo.fGetOrganizationBreadcrumbs(orgRec.UID) \n from Organization orgRec\n inner join RECORG recOrg on orgRec.ParentOrganizationUID = recOrg.ORGuid\n\n)\ninsert into @tempTable(ORGUID, ORGNAME, PARENTORGUID,ORGPATH)\n\nselect ORGUID, ORGNAME, PARENTORGUID,ORGPATH \nfrom RECORG rec \n\nselect * \nfrom @tempTable where ORGUID in(select MIN(tt.ORGUID) \n from @tempTable tt \n group by tt.PARENTORGUID)\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31336/" ]
Way back when I was working in an Oracle shop I took the CONNECT\_BY for granted. Now I'm stuck working with SQL Server 2005 and have some nasty object hierarchies. Specifically, we have a self referencing table where all child records have a column with their parent's id. Currently we have a view that maps children to levels in the hierarchy and a nasty query that does the heavy lifting to connect parents with their children. While this method works, it is far from elegant and reeks of taint. I'm just curious how other people retrieve hierarchical data from SQL Server 2005.
This creates your typical hierarchical table and uses a CTE to select the hierarchy structure and create a path for each item. ``` CREATE TABLE tblHierarchy (ID int, ParentID int NULL, Name varchar(128)); INSERT INTO tblHierarchy VALUES (1, NULL, '1'); INSERT INTO tblHierarchy VALUES (2, NULL, '2'); INSERT INTO tblHierarchy VALUES (3, NULL, '3'); INSERT INTO tblHierarchy VALUES (4, 1, '1.1'); INSERT INTO tblHierarchy VALUES (5, 1, '1.2'); INSERT INTO tblHierarchy VALUES (6, 4, '1.1.1'); WITH Parent AS ( SELECT ID, ParentID, Name AS Path FROM tblHierarchy WHERE ParentID IS NULL UNION ALL SELECT TH.ID, TH.ParentID, CONVERT(varchar(128), Parent.Path + '/' + TH.Name) AS Path FROM tblHierarchy TH INNER JOIN Parent ON Parent.ID = TH.ParentID ) SELECT * FROM Parent ``` OUTPUT: ``` ID ParentID Path 1 NULL 1 2 NULL 2 3 NULL 3 4 1 1/1.1 5 1 1/1.2 6 4 1/1.1/1.1.1 ```
235,556
<p>Using jQuery, how would you <code>show()</code> every <code>div.foo</code> on a page in a random order, with a new one appearing every X milliseconds?</p> <p><strong>Clarification</strong>: I want to start with all these elements hidden and end with all of them showing, so it wouldn't make sense to <code>show()</code> the same element twice.</p> <p>I originally thought I'd make an array listing all the elements, randomly pick one, show that one, remove it from the array using <code>splice()</code>, and then randomly pick the next one from the remaining list - etc. But since my array is part of a jQuery object, <code>splice()</code> is not available.</p>
[ { "answer_id": 235705, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 1, "selected": false, "text": "<p>I don't use jQuery myself, but what about this:</p>\n\n<pre><code>var intervalMilliseconds = X; // set to your value for X\nvar divFoos = $(\"div.foo\").get();\nvar intervalId = setInterval(function() {\n $(divFoos.splice(Math.floor(Math.random() * divFoos.length), 1)).show();\n if(divFoos.length == 0) clearInterval(intervalId);\n}, intervalMilliseconds);\n</code></pre>\n\n<p>That should do the trick.</p>\n\n<hr>\n\n<p>UPDATE: Since your description isn't explicit about it, I assumed you meant that you ultimately want to show all of them, and that once they are visible, we are done. If not, please explain further so I can update this (if you can't already determine what you need from the code I provided).</p>\n" }, { "answer_id": 235775, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "<p>Here's how I would do it <s>(untested)</s>:</p>\n\n<pre><code>(function () {\n var int, els;\n int = 100; // interval, in milliseconds\n els = $('div.foo');\n setInterval(function () {\n var idx;\n idx = Math.floor(els.length * Math.random());\n $(els[idx]).show();\n setTimeout(function () {\n $(els[idx]).hide();\n }, int);\n }, int);\n})();\n</code></pre>\n" }, { "answer_id": 235937, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 3, "selected": true, "text": "<p>An interesting way to do this would be the extend Javascript's Array base object with a shuffle function. In Prototype (should be the same in JQuery, except jQuery.extend). This is quick and dirty shuffle, there are plenty of other ways to do it.</p>\n\n<pre><code>Object.extend(Array.prototype, {\n shuffle : function() {\n this.sort( function() { return 0.5 - Math.random(); } );\n return this;\n }\n});\n</code></pre>\n\n<p>So assuming you have your array of divs ready to go, call the shuffle() method and simply go through them one by one, in order (they're now shuffled) and show them (according to your intervals). Might want to make that 'non-destructive' though by cloning the array returned by the shuffle method instead of sorting it directly.</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ]
Using jQuery, how would you `show()` every `div.foo` on a page in a random order, with a new one appearing every X milliseconds? **Clarification**: I want to start with all these elements hidden and end with all of them showing, so it wouldn't make sense to `show()` the same element twice. I originally thought I'd make an array listing all the elements, randomly pick one, show that one, remove it from the array using `splice()`, and then randomly pick the next one from the remaining list - etc. But since my array is part of a jQuery object, `splice()` is not available.
An interesting way to do this would be the extend Javascript's Array base object with a shuffle function. In Prototype (should be the same in JQuery, except jQuery.extend). This is quick and dirty shuffle, there are plenty of other ways to do it. ``` Object.extend(Array.prototype, { shuffle : function() { this.sort( function() { return 0.5 - Math.random(); } ); return this; } }); ``` So assuming you have your array of divs ready to go, call the shuffle() method and simply go through them one by one, in order (they're now shuffled) and show them (according to your intervals). Might want to make that 'non-destructive' though by cloning the array returned by the shuffle method instead of sorting it directly.
235,564
<p>I am using a mock object in RhinoMocks to represent a class that makes calls to MessageQueue.GetPublicQueues. I want to simulate the exception thrown when message queueing is operating in workgroup mode, which is a MessageQueueException, to ensure that I am catching the exception correctly</p> <p>The MessageQueueException has no public constructor, only the standard protected constructor for an exception. Is there an appropriate way to throw this exception from the mock object / Expect.Call statement?</p>
[ { "answer_id": 235703, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 4, "selected": true, "text": "<p>Reflection can break the accessibility rulez. You <em>will</em> void the warranty, a .NET update can easily break your code. Try this:</p>\n\n<pre><code>using System.Reflection;\nusing System.Messaging;\n...\n Type t = typeof(MessageQueueException);\n ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, \n null, new Type[] { typeof(int) }, null);\n MessageQueueException ex = (MessageQueueException)ci.Invoke(new object[] { 911 });\n throw ex;\n</code></pre>\n" }, { "answer_id": 294573, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 2, "selected": false, "text": "<p>You can cause this by trying to create an invalid queue. Probably safer then being held captive by framework changes (through using private/protected constructors):</p>\n\n<pre><code>MessageQueue mq = MessageQueue.Create(\"\\\\invalid\");\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21862/" ]
I am using a mock object in RhinoMocks to represent a class that makes calls to MessageQueue.GetPublicQueues. I want to simulate the exception thrown when message queueing is operating in workgroup mode, which is a MessageQueueException, to ensure that I am catching the exception correctly The MessageQueueException has no public constructor, only the standard protected constructor for an exception. Is there an appropriate way to throw this exception from the mock object / Expect.Call statement?
Reflection can break the accessibility rulez. You *will* void the warranty, a .NET update can easily break your code. Try this: ``` using System.Reflection; using System.Messaging; ... Type t = typeof(MessageQueueException); ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(int) }, null); MessageQueueException ex = (MessageQueueException)ci.Invoke(new object[] { 911 }); throw ex; ```
235,608
<p>I have the following situation:</p> <p>A user will define a certain filter on a page, and on postback I will query the database using that filter and return a bunch of matching records to the user, each with a checkbox next to it, so he can choose whether to act on each of those records.</p> <p>In Classic ASP / PHP I can generate a lot of controls named "chk__*" and then on postback go through all the $<em>POST entries looking for the ones prefixed "chk</em>".</p> <p>What is the best way to do this in ASP.Net 2.0?</p> <p>I can do it easily by implementing a Repeater with a Template containing the checkbox, bind the Repeater to a Dataset, and then on the second Postback, I just do:</p> <pre><code>For Each it As RepeaterItem In repContacts.Items Dim chkTemp As CheckBox = DirectCast(it.FindControl("cbSelect"), CheckBox) If chkTemp.Checked Then End If Next </code></pre> <p>However this has the <em>slight</em> disadvantage of giving me a HUGE Viewstate, which is really bad because the client will need to re-upload the whole viewstate to the server, and these people will probably be using my site over a crappy connection.</p> <p>Any other ideas? (I can also create the controls dynamically and iterate through Request.Form as in the old days, however, I was looking for a cleaner </p>
[ { "answer_id": 235624, "author": "Ramesh", "author_id": 30594, "author_profile": "https://Stackoverflow.com/users/30594", "pm_score": 0, "selected": false, "text": "<p>Disable the ViewState. In case it cannot be done try using <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.sessionpagestatepersister.aspx\" rel=\"nofollow noreferrer\">Session to store the view state</a></p>\n" }, { "answer_id": 235641, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 2, "selected": false, "text": "<p>I recommend the classic ASP solution when faced with absurd Viewstate conditions. It is sad to lose the nice features it provides, but combining <em>some</em> Viewstate enabled controls (asp:*) with some classic techniques (input type=\"...\") has saved me a <em>lot</em> of headaches in the past.</p>\n\n<p>Sometimes you just want to do something simple, and the simple solution beats \"WYSIWYG\" form editing.</p>\n" }, { "answer_id": 235644, "author": "Josh Hinman", "author_id": 2527, "author_profile": "https://Stackoverflow.com/users/2527", "pm_score": 3, "selected": true, "text": "<p>Do it the same way you did it in classic ASP. Use &lt;input type=\"checkbox\"&gt; instead of &lt;asp:checkbox&gt;. You can access the raw post paramaters using Request.Form</p>\n" }, { "answer_id": 235652, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 3, "selected": false, "text": "<p>Have you looked at the CheckBoxList control? You can bind it to your data set, provide text member and value member items, and it will also allow you to easily see which items are checked. There is also the ability to dynamically add more checkbox items if needed.</p>\n" }, { "answer_id": 235849, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>One of the things that I have done is to record the state of a check via AJAX in the session, then on Postback (full or partial via AJAX), look in the session for the items to perform the selected action on.</p>\n\n<p>The basic idea is to add an onclick handler to the checkbox that knows the id of the associated item. In the on click handler communicate this id back to the server via AJAX and record it in the session -- you'll need to communicate checkbox status as well so you can uncheck items. Have the handler for the submit control use the data about which items were selected from the session.</p>\n\n<p>This way allows you to handle paged data as well, since you can set the initial value of the checkbox from the session when rendering (either full or partial) a page with checked items on it.</p>\n\n<p>It might look something like this. Assuming ASP.NET AJAX with PageMethods (and ScriptManager, of course).</p>\n\n<pre><code>&lt;script type='text/javascript'&gt;\n function record(checkbox,item)\n {\n var context = { ctl : checkbox };\n PageMethods.Record(item,checkbox.checked,onSuccess,onFailure,context);\n }\n\n function onSuccess(result,context)\n {\n // do something, maybe highlight the row, maybe nothing\n }\n\n function onFailure(error,context)\n {\n context.ctl.checked = false;\n alert(error.get_Message());\n }\n&lt;/script&gt;\n\n\n...\n&lt;tr&gt;&lt;td&gt;&lt;input type='checkbox' onclick='record(this,\"item_1\");'&gt;&lt;/td&gt;&lt;td&gt;Item 1&lt;/td&gt;&lt;/tr&gt;\n...\n\nCodebehind\n\n[WebMethod(EnableSessionState=true)]\npublic static void Record( string itemName, bool value )\n{\n List&lt;string&gt; itemList = (List&lt;string&gt;)Session[\"Items\"];\n if (itemList == null)\n {\n itemList = new List&lt;string&gt;();\n Session[\"Items\"] = itemList;\n }\n if (itemList.Contains(itemName) &amp;&amp; !value)\n {\n itemList.Remove(itemName);\n }\n else if (!itemList.Contains(itemName) &amp;&amp; value)\n {\n itemList.Add(itemName);\n } \n}\n\nprotected void button_OnClick( object sender, EventArgs e )\n{\n List&lt;string&gt; itemList = (List&lt;string&gt;)Session[\"Items\"];\n if (itemList != null)\n {\n foreach (string item in itemList)\n {\n // do something with the selected item\n }\n }\n}\n</code></pre>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
I have the following situation: A user will define a certain filter on a page, and on postback I will query the database using that filter and return a bunch of matching records to the user, each with a checkbox next to it, so he can choose whether to act on each of those records. In Classic ASP / PHP I can generate a lot of controls named "chk\_\_\*" and then on postback go through all the $*POST entries looking for the ones prefixed "chk*". What is the best way to do this in ASP.Net 2.0? I can do it easily by implementing a Repeater with a Template containing the checkbox, bind the Repeater to a Dataset, and then on the second Postback, I just do: ``` For Each it As RepeaterItem In repContacts.Items Dim chkTemp As CheckBox = DirectCast(it.FindControl("cbSelect"), CheckBox) If chkTemp.Checked Then End If Next ``` However this has the *slight* disadvantage of giving me a HUGE Viewstate, which is really bad because the client will need to re-upload the whole viewstate to the server, and these people will probably be using my site over a crappy connection. Any other ideas? (I can also create the controls dynamically and iterate through Request.Form as in the old days, however, I was looking for a cleaner
Do it the same way you did it in classic ASP. Use <input type="checkbox"> instead of <asp:checkbox>. You can access the raw post paramaters using Request.Form
235,616
<p>Suppose a header file defines a function template. Now suppose two implementation files <code>#include</code> this header, and each of them has a call to the function template. In both implementation files the function template is instantiated with the same type.</p> <pre><code>// header.hh template &lt;typename T&gt; void f(const T&amp; o) { // ... } // impl1.cc #include "header.hh" void fimpl1() { f(42); } // impl2.cc #include "header.hh" void fimpl2() { f(24); } </code></pre> <p>One may expect the linker would complain about multiple definitions of <code>f()</code>. Specifically, if <code>f()</code> wouldn't be a template then that would indeed be the case.</p> <ul> <li>How come the linker doesn't complain about multiple definitions of <code>f()</code>?</li> <li>Is it specified in the standard that the linker must handle this situation gracefully? In other words, can I always count on programs similar to the above to compile and link?</li> <li>If the linker can be clever enough to disambiguate a set of function template instantiations, why can't it do the same for regular functions, given they are identical as is the case for instantiated function templates?</li> </ul>
[ { "answer_id": 235623, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": true, "text": "<p>In order to support C++, the linker is smart enough to recognize that they are all the same function and throws out all but one.</p>\n\n<p>EDIT: clarification:\nThe linker doesn't compare function contents and determine that they are the same.\nTemplated functions are marked as such and the linker recognizes that they have the same signatures.</p>\n" }, { "answer_id": 235640, "author": "CAdaker", "author_id": 30579, "author_profile": "https://Stackoverflow.com/users/30579", "pm_score": 1, "selected": false, "text": "<p>This is more or less a special case just for templates.</p>\n\n<p>The compiler only generates the template instantiations that are actually used. Since it has no control over what code will be generated from other source files, it has to generate the template code once for each file, to make sure that the method gets generated at all.</p>\n\n<p>Since it's difficult to solve this (the standard has an <code>extern</code> keyword for templates, but g++ doesn't implement it) the linker simply accepts the multiple definitions.</p>\n" }, { "answer_id": 235954, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "<p>The Gnu C++ compiler's manual has <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html\" rel=\"noreferrer\">a good discussion of this</a>. An excerpt:</p>\n\n<blockquote>\n <p>C++ templates are the first language\n feature to require more intelligence\n from the environment than one usually\n finds on a UNIX system. Somehow the\n compiler and linker have to make sure\n that each template instance occurs\n exactly once in the executable if it\n is needed, and not at all otherwise.\n There are two basic approaches to this\n problem, which are referred to as the\n Borland model and the Cfront model.</p>\n \n <h2>Borland model</h2>\n \n <p>Borland C++ solved the template\n instantiation problem by adding the\n code equivalent of common blocks to\n their linker; the compiler emits\n template instances in each translation\n unit that uses them, and the linker\n collapses them together. The advantage\n of this model is that the linker only\n has to consider the object files\n themselves; there is no external\n complexity to worry about. This\n disadvantage is that compilation time\n is increased because the template code\n is being compiled repeatedly. Code\n written for this model tends to\n include definitions of all templates\n in the header file, since they must be\n seen to be instantiated.</p>\n \n <h2>Cfront model</h2>\n \n <p>The AT&amp;T C++ translator, Cfront,\n solved the template instantiation\n problem by creating the notion of a\n template repository, an automatically\n maintained place where template\n instances are stored. A more modern\n version of the repository works as\n follows: As individual object files\n are built, the compiler places any\n template definitions and\n instantiations encountered in the\n repository. At link time, the link\n wrapper adds in the objects in the\n repository and compiles any needed\n instances that were not previously\n emitted. The advantages of this model\n are more optimal compilation speed and\n the ability to use the system linker;\n to implement the Borland model a\n compiler vendor also needs to replace\n the linker. The disadvantages are\n vastly increased complexity, and thus\n potential for error; for some code\n this can be just as transparent, but\n in practice it can be very difficult\n to build multiple programs in one\n directory and one program in multiple\n directories. Code written for this\n model tends to separate definitions of\n non-inline member templates into a\n separate file, which should be\n compiled separately. </p>\n \n <p>When used with GNU ld version 2.8 or\n later on an ELF system such as\n GNU/Linux or Solaris 2, or on\n Microsoft Windows, G++ supports the\n Borland model. On other systems, G++\n implements neither automatic model.</p>\n</blockquote>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456/" ]
Suppose a header file defines a function template. Now suppose two implementation files `#include` this header, and each of them has a call to the function template. In both implementation files the function template is instantiated with the same type. ``` // header.hh template <typename T> void f(const T& o) { // ... } // impl1.cc #include "header.hh" void fimpl1() { f(42); } // impl2.cc #include "header.hh" void fimpl2() { f(24); } ``` One may expect the linker would complain about multiple definitions of `f()`. Specifically, if `f()` wouldn't be a template then that would indeed be the case. * How come the linker doesn't complain about multiple definitions of `f()`? * Is it specified in the standard that the linker must handle this situation gracefully? In other words, can I always count on programs similar to the above to compile and link? * If the linker can be clever enough to disambiguate a set of function template instantiations, why can't it do the same for regular functions, given they are identical as is the case for instantiated function templates?
In order to support C++, the linker is smart enough to recognize that they are all the same function and throws out all but one. EDIT: clarification: The linker doesn't compare function contents and determine that they are the same. Templated functions are marked as such and the linker recognizes that they have the same signatures.
235,618
<p>I received an error when an referenced .NET Framework 2.0 assembly tried to execute the following line of code in an IIS hosted WCF service:</p> <p>Error Message:</p> <blockquote> <p>exePath must be specified when not running inside a stand alone exe.</p> </blockquote> <p>Source Code:</p> <pre><code>ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); </code></pre> <p>Has anyone experienced this issue and do they know how to resolve it?</p> <p><b>EDIT:</b> My question is, what is the best way to open a configuration file (app.config and web.config) from a WCF service that is backwards compatible with a .NET 2.0 assembly?</p>
[ { "answer_id": 235791, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 1, "selected": false, "text": "<p>It depends on what you're trying to accomplish. On ASP.NET, you'd normally wouldn't use ConfigurationManager for stuff like this, but WebConfigurationManager instead. That said, there's no exact equivalent, since, in reality, the user/roaming/etc stuff that OpenExeConfiguration allows doesn't make sense on a web application.</p>\n\n<p>What do you need it for?</p>\n" }, { "answer_id": 252356, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 2, "selected": false, "text": "<p>The referenced .NET 2.0 assembly is part of a class library I developed for our enterprise library to handle common taskes. It was intended to be used in ASP.NET and WinForm applications. </p>\n\n<p>Here is the source code I used to determine which type of configuration file to open:</p>\n\n<pre><code>//Open app.config or web.config file\nif (HttpContext.Current != null)\n this.m_ConfigFile = WebConfigurationManager.OpenWebConfiguration(\"~\");\nelse\n this.m_ConfigFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n</code></pre>\n" }, { "answer_id": 273933, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 3, "selected": true, "text": "<p>I was able to resolve the configuration issue by removing the existing code from my provious answer and replacing it with the following ConfigurationManager implementation:</p>\n\n<pre><code>string MySetting = ConfigurationManager.AppSettings.Get(\"MyAppSetting\");\n</code></pre>\n\n<p>If works for ASP.NET applications, WinForms applications and WCF Services. I just over-engineered the initial implementation of my class library 3 years ago....</p>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
I received an error when an referenced .NET Framework 2.0 assembly tried to execute the following line of code in an IIS hosted WCF service: Error Message: > > exePath must be specified when not > running inside a stand alone exe. > > > Source Code: ``` ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ``` Has anyone experienced this issue and do they know how to resolve it? **EDIT:** My question is, what is the best way to open a configuration file (app.config and web.config) from a WCF service that is backwards compatible with a .NET 2.0 assembly?
I was able to resolve the configuration issue by removing the existing code from my provious answer and replacing it with the following ConfigurationManager implementation: ``` string MySetting = ConfigurationManager.AppSettings.Get("MyAppSetting"); ``` If works for ASP.NET applications, WinForms applications and WCF Services. I just over-engineered the initial implementation of my class library 3 years ago....
235,651
<p>I have the following string expression in a PowerShell script:</p> <pre><code>"select count(*) cnt from ${schema}.${table} where ${col.column_name} is null" </code></pre> <p>The schema and table resolve to the values of $schema and $table, respectively. However, an empty string is supplied for ${col.column_name}. How can I dot into the member of a variable as part of a string substitution?</p>
[ { "answer_id": 235669, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": true, "text": "<p>How about:</p>\n\n<pre><code>\"select count(*) cnt from $schema.$table where $($col.column_name) is null\"\n</code></pre>\n" }, { "answer_id": 235679, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>One way would be:</p>\n\n<pre><code>\"select count(*) cnt from $schema.$table where $($col.column_name) is null\"\n</code></pre>\n\n<p>Another option would be</p>\n\n<pre><code>\"select count(*) cnt from {0}.{1} where {2} is null\" -f $schema, $table, $col.column_name\n</code></pre>\n" }, { "answer_id": 282138, "author": "Mike Shepard", "author_id": 36429, "author_profile": "https://Stackoverflow.com/users/36429", "pm_score": 2, "selected": false, "text": "<p>I think the problem you're having is mainly syntax related. If you have a variable named $foo, ${foo} references the same variable. So, the ${table} and ${schema} references in your sql string work ok. </p>\n\n<p>The issue is with ${col.column_name}. Your variable (I assume) is called $col, and has a member named column_name. As Robert and Steven both indicate in their answers, to refer to this, you should use $($col.column_name). In general, $(expression) will be replaced with the value of the expression.</p>\n\n<p>The reason for allowing braces in variable names is so that variables can have unusual characters in their names. I would recommend not using the ${} syntax (unless you have a compelling reason), and replacing it with straight $var references for variables and $($var.member) for member references in strings.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20625/" ]
I have the following string expression in a PowerShell script: ``` "select count(*) cnt from ${schema}.${table} where ${col.column_name} is null" ``` The schema and table resolve to the values of $schema and $table, respectively. However, an empty string is supplied for ${col.column\_name}. How can I dot into the member of a variable as part of a string substitution?
How about: ``` "select count(*) cnt from $schema.$table where $($col.column_name) is null" ```
235,664
<p>After looking at another question on SO (<a href="https://stackoverflow.com/questions/235386/using-nan-in-c">Using NaN in C++</a>) I became curious about <code>std::numeric_limits&lt;double&gt;::signaling_NaN()</code>.</p> <p>I could not get signaling_NaN to throw an exception. I thought perhaps by signaling it really meant a signal so I tried catching SIGFPE but nope...</p> <p>Here is my code:</p> <pre><code>double my_nan = numeric_limits&lt;double&gt;::signaling_NaN(); my_nan++; my_nan += 5; my_nan = my_nan / 10; my_nan = 15 / my_nan; cout &lt;&lt; my_nan &lt;&lt; endl; </code></pre> <p><code>numeric_limits&lt;double&gt;::has_signaling_NaN</code> evaluates to true, so it is implemented on my system.</p> <p>Any ideas?</p> <p>I am using ms visual studio .net 2003's C++ compiler. I want to test it on another when I get home.</p> <p>Thanks!</p>
[ { "answer_id": 235677, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 1, "selected": false, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/hf16y784.aspx\" rel=\"nofollow noreferrer\">TFM</a>:</p>\n\n<pre><code>cout &lt;&lt; \"The signaling NaN for type float is: \"\n &lt;&lt; numeric_limits&lt;float&gt;::signaling_NaN( )\n &lt;&lt; endl;\n</code></pre>\n\n<p>-></p>\n\n<blockquote>\n <p>The signaling NaN for type float is: 1.#QNAN</p>\n</blockquote>\n\n<p>where the 'Q' stands for 'Quiet'. Dunno why it would return that, but that's why it doesn't throw an exception for you.</p>\n\n<p>Out of curiosity, does this work better?</p>\n\n<pre><code>const double &amp;real_snan( void )\n{\n static const long long snan = 0x7ff0000080000001LL;\n return *(double*)&amp;snan;\n}\n</code></pre>\n" }, { "answer_id": 236025, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 4, "selected": true, "text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/e9b52ceh.aspx\" rel=\"noreferrer\"><code>_control87()</code></a> function to enable floating-point exceptions. From the MSDN documentation on <code>_control87()</code>:</p>\n\n<blockquote>\n <p>Note: </p>\n \n <p>The run-time libraries mask all floating-point exceptions by default. </p>\n</blockquote>\n\n<p>When floating point exceptions are enabled, you can use <a href=\"http://msdn.microsoft.com/en-us/library/xdkz3x12.aspx\" rel=\"noreferrer\"><code>signal()</code></a> or <a href=\"http://msdn.microsoft.com/en-us/library/ms680657(VS.85).aspx\" rel=\"noreferrer\">SEH (Structured Exception Handling)</a> to catch them.</p>\n" }, { "answer_id": 236717, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>The key lies in <a href=\"http://msdn.microsoft.com/en-us/library/1b2b997k%28VS.80%29.aspx\" rel=\"nofollow noreferrer\"><code>numeric_limits&lt;T&gt;::has_signaling_NaN</code></a>. Which value does this have for you? (The MSDN seems to suggest that it's always <code>false</code> for MSVC?)</p>\n" }, { "answer_id": 237391, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 3, "selected": false, "text": "<p>A word of warning: \nUsing 3rd party DLLs may silently enable these exceptions. This is especially true for loading DLL's that are written in a language that enables them by default.</p>\n\n<p>I've had that happen in two instances: Printing from an embedded browser control to a HP printer, and registering my DLL (that sets some initial values to NaN) from InnoSetup which is written in Delphi.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29703/" ]
After looking at another question on SO ([Using NaN in C++](https://stackoverflow.com/questions/235386/using-nan-in-c)) I became curious about `std::numeric_limits<double>::signaling_NaN()`. I could not get signaling\_NaN to throw an exception. I thought perhaps by signaling it really meant a signal so I tried catching SIGFPE but nope... Here is my code: ``` double my_nan = numeric_limits<double>::signaling_NaN(); my_nan++; my_nan += 5; my_nan = my_nan / 10; my_nan = 15 / my_nan; cout << my_nan << endl; ``` `numeric_limits<double>::has_signaling_NaN` evaluates to true, so it is implemented on my system. Any ideas? I am using ms visual studio .net 2003's C++ compiler. I want to test it on another when I get home. Thanks!
You can use the [`_control87()`](http://msdn.microsoft.com/en-us/library/e9b52ceh.aspx) function to enable floating-point exceptions. From the MSDN documentation on `_control87()`: > > Note: > > > The run-time libraries mask all floating-point exceptions by default. > > > When floating point exceptions are enabled, you can use [`signal()`](http://msdn.microsoft.com/en-us/library/xdkz3x12.aspx) or [SEH (Structured Exception Handling)](http://msdn.microsoft.com/en-us/library/ms680657(VS.85).aspx) to catch them.
235,671
<p>I wanted to add a UTF-8 font in Gvim but I could not find out how to do this. I tried to follow the step on this manual but it still did not work. <a href="http://www.inter-locale.com/whitepaper/learn/learn_to_type.html" rel="noreferrer">http://www.inter-locale.com/whitepaper/learn/learn_to_type.html</a> (vim section halfway the page)</p> <p>Can anyone tell me how to add a font in Vim so I can have Japanese characters displayed ?</p>
[ { "answer_id": 237002, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 3, "selected": false, "text": "<p>Quote from the <a href=\"http://vimdoc.sourceforge.net/htmldoc/usr_45.html#45.1\" rel=\"noreferrer\">vim documentation</a>:</p>\n\n<blockquote>For MS-Windows, some fonts have a limited number of Unicode characters. Try\nusing the \"Courier New\" font. You can use the Edit/Select Font... menu to\nselect and try out the fonts available. Only fixed-width fonts can be used\nthough. Example:</blockquote>\n\n<pre><code> :set guifont=courier_new:h12\n</code></pre>\n\n<p>So, I guess, unless you find a fixed width font containing the characters you want to display, then you are out of luck.</p>\n" }, { "answer_id": 243943, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 4, "selected": false, "text": "<p>As others note, you must use a fixed-width font. Vim is a text editor, not a WYSIWYG editor.</p>\n\n<p>If you have a fixed-width font with the characters you need then:</p>\n\n<pre><code>:set guifont=*\n</code></pre>\n\n<p>Select the font you want to use, the size, etc. Once you're happy with it, do:</p>\n\n<pre><code>:set guifont?\n</code></pre>\n\n<p>And it will output the current setting of the value. Put the <code>set guifont=foo</code> in your <code>.gvimrc</code> (or in <code>.vimrc</code> with a <code>if has(\"gui_running\")</code> block).</p>\n\n<pre><code>set guifont=&lt;C-R&gt;=&amp;guifont&lt;CR&gt;\n</code></pre>\n\n<p>That will put the current value into the file.</p>\n" }, { "answer_id": 680363, "author": "George V. Reilly", "author_id": 6364, "author_profile": "https://Stackoverflow.com/users/6364", "pm_score": 2, "selected": false, "text": "<p>You have to use a fixed-width font for Gvim under Windows.</p>\n\n<p>There are several relevant pages at the Vim Tips Wiki:</p>\n\n<ul>\n<li><a href=\"http://vim.wikia.com/wiki/Working_with_Unicode\" rel=\"nofollow noreferrer\">Working with Unicode</a></li>\n<li><a href=\"http://vim.wikia.com/wiki/Setting_the_font_in_the_GUI\" rel=\"nofollow noreferrer\">Setting the guifont</a></li>\n<li><a href=\"http://vim.wikia.com/wiki/The_perfect_programming_font\" rel=\"nofollow noreferrer\">The perfect programming font</a></li>\n</ul>\n" }, { "answer_id": 4828071, "author": "atomicules", "author_id": 208793, "author_profile": "https://Stackoverflow.com/users/208793", "pm_score": 4, "selected": false, "text": "<p>For Windows, I found using the <a href=\"http://vimdoc.sourceforge.net/htmldoc/options.html#%27guifontwide%27\">guifontwide</a> setting provided the expected functionality (i.e. mixed character display: Japanese, Chinese and English in the same file). This is not intuitive or obvious (at least not to me!) from the Vim help files, but having something like this in your startup settings will work:</p>\n\n<pre><code>set guifont=Consolas:h10 \nset guifontwide=MingLiU:h10 \"For windows to display mixed character sets\nset encoding=utf-8 \n</code></pre>\n" }, { "answer_id": 14613767, "author": "ThomasJ", "author_id": 2026997, "author_profile": "https://Stackoverflow.com/users/2026997", "pm_score": 2, "selected": false, "text": "<p>This is what I use...</p>\n\n<pre><code>set gfn=MingLiU:h16:cDEFAULT\nset fenc=utf-8\nset encoding=utf-8\n</code></pre>\n\n<p>Put this in your _vimrc file, exit and reopen. Works like a charm for me.\n+T</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18383/" ]
I wanted to add a UTF-8 font in Gvim but I could not find out how to do this. I tried to follow the step on this manual but it still did not work. <http://www.inter-locale.com/whitepaper/learn/learn_to_type.html> (vim section halfway the page) Can anyone tell me how to add a font in Vim so I can have Japanese characters displayed ?
As others note, you must use a fixed-width font. Vim is a text editor, not a WYSIWYG editor. If you have a fixed-width font with the characters you need then: ``` :set guifont=* ``` Select the font you want to use, the size, etc. Once you're happy with it, do: ``` :set guifont? ``` And it will output the current setting of the value. Put the `set guifont=foo` in your `.gvimrc` (or in `.vimrc` with a `if has("gui_running")` block). ``` set guifont=<C-R>=&guifont<CR> ``` That will put the current value into the file.
235,694
<p>In the filesystem I have</p> <pre> /file.aspx /directory/default.aspx </pre> <p>I want to configure IIS so that it returns the appropriate file (add the aspx extension) or directory (default content page) as follows:</p> <pre> /file -> /file.aspx /directory -> /directory/default.aspx /directory/ -> /directory/default.aspx </pre> <p>I have configured the Wildcard application mapping set to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll. When the "Verify that file exists" is unchecked, the the file request works but not the directory request (returns 404). When the "Verify that file exists" is checked, the directory request works but not the file request.</p> <p>How can I configure it so that both the file and directory requests will work?</p>
[ { "answer_id": 235697, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 0, "selected": false, "text": "<p>You'll have to add an ASP.NET global.asax or HttpModule that maps the / request to default.aspx.</p>\n" }, { "answer_id": 248777, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<p>I recommend using UrlRewriter:</p>\n\n<p><a href=\"http://urlrewriter.net/\" rel=\"nofollow noreferrer\">http://urlrewriter.net/</a></p>\n\n<p>This allows you to create all the mappings above that you desire. One thing that you'll have to do (if you're using IIS 6 or earlier) is configure IIS so that all extensions are handled by asp.net. The documentation explains how to do this. Then you create a bunch of rules in your web.config (or separate rewriter.config as I use) in the form of regular expressions to create your mappings.</p>\n\n<p>Incidentally, for the above example, you probably don't need to do anything for the last two rules. IIS will take care of those automatically. For the first rule it will be something like:</p>\n\n<pre><code>&lt;rewrite url=\"^/file$\" to=\"/file.aspx\" /&gt;\n</code></pre>\n\n<p>You could get more clever and write generalized rules so you don't have to write one rule per file.</p>\n" }, { "answer_id": 326040, "author": "g .", "author_id": 6944, "author_profile": "https://Stackoverflow.com/users/6944", "pm_score": 1, "selected": true, "text": "<p>I looked at url rewriting, but ultimately decided on a simpler solution. I just moved the file.aspx into a directory and renamed it to default.aspx.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6944/" ]
In the filesystem I have ``` /file.aspx /directory/default.aspx ``` I want to configure IIS so that it returns the appropriate file (add the aspx extension) or directory (default content page) as follows: ``` /file -> /file.aspx /directory -> /directory/default.aspx /directory/ -> /directory/default.aspx ``` I have configured the Wildcard application mapping set to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet\_isapi.dll. When the "Verify that file exists" is unchecked, the the file request works but not the directory request (returns 404). When the "Verify that file exists" is checked, the directory request works but not the file request. How can I configure it so that both the file and directory requests will work?
I looked at url rewriting, but ultimately decided on a simpler solution. I just moved the file.aspx into a directory and renamed it to default.aspx.
235,695
<p>I have a script that slides a div down from behind the menu, when people click on the tab. However its in jquery and I want to use mootools (lots of reasons I wont go into here). However im stuck with mootools 1.1 at present. But for some reason my attempt is not working :(</p> <p>The html</p> <pre><code>print("code sample"); &lt;div id="panel"&gt; &lt;form action=""&gt; &lt; form here &gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="slide"&gt; &lt;p class="sl"&gt;&lt;a href="#" class="btn-slide" id="toggle"&gt;&lt;span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt; </code></pre> <p>Div id panel holds the form which slides down, div class slide and the P tag is replaced by a tab/button which hangs down via css, clicking on this slides the tab down.</p> <p>The jquery (which works fine)</p> <pre><code>print("code sample"); &lt;script type="text/javascript"&gt; $j(document).ready(function(){ $j(".btn-slide").click(function(){ $j("#panel").slideToggle("slow"); $j(this).toggleClass("active"); return false; }); }); &lt;/script&gt; </code></pre> <p>My moo attempt</p> <pre><code>print("code sample"); &lt;script type="text/javascript"&gt; window.addEvent('domready', function(){ var mySlide = new Fx.Slide('panel'); $('toggle').addEvent('click', function(e){ e = new Event(e); mySlide.toggle(); e.stop(); }); }); &lt;/script&gt; </code></pre> <p>Like I said above I am restricted to moo 1.1 at present, but if there is a answer that will work with both 1.1 and 1.2 or if its a similar change I would be grateful to hear, as it will be updated at some point.</p>
[ { "answer_id": 235697, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 0, "selected": false, "text": "<p>You'll have to add an ASP.NET global.asax or HttpModule that maps the / request to default.aspx.</p>\n" }, { "answer_id": 248777, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<p>I recommend using UrlRewriter:</p>\n\n<p><a href=\"http://urlrewriter.net/\" rel=\"nofollow noreferrer\">http://urlrewriter.net/</a></p>\n\n<p>This allows you to create all the mappings above that you desire. One thing that you'll have to do (if you're using IIS 6 or earlier) is configure IIS so that all extensions are handled by asp.net. The documentation explains how to do this. Then you create a bunch of rules in your web.config (or separate rewriter.config as I use) in the form of regular expressions to create your mappings.</p>\n\n<p>Incidentally, for the above example, you probably don't need to do anything for the last two rules. IIS will take care of those automatically. For the first rule it will be something like:</p>\n\n<pre><code>&lt;rewrite url=\"^/file$\" to=\"/file.aspx\" /&gt;\n</code></pre>\n\n<p>You could get more clever and write generalized rules so you don't have to write one rule per file.</p>\n" }, { "answer_id": 326040, "author": "g .", "author_id": 6944, "author_profile": "https://Stackoverflow.com/users/6944", "pm_score": 1, "selected": true, "text": "<p>I looked at url rewriting, but ultimately decided on a simpler solution. I just moved the file.aspx into a directory and renamed it to default.aspx.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
I have a script that slides a div down from behind the menu, when people click on the tab. However its in jquery and I want to use mootools (lots of reasons I wont go into here). However im stuck with mootools 1.1 at present. But for some reason my attempt is not working :( The html ``` print("code sample"); <div id="panel"> <form action=""> < form here > </form> </div> <div class="slide"> <p class="sl"><a href="#" class="btn-slide" id="toggle"><span></span></a></p> ``` Div id panel holds the form which slides down, div class slide and the P tag is replaced by a tab/button which hangs down via css, clicking on this slides the tab down. The jquery (which works fine) ``` print("code sample"); <script type="text/javascript"> $j(document).ready(function(){ $j(".btn-slide").click(function(){ $j("#panel").slideToggle("slow"); $j(this).toggleClass("active"); return false; }); }); </script> ``` My moo attempt ``` print("code sample"); <script type="text/javascript"> window.addEvent('domready', function(){ var mySlide = new Fx.Slide('panel'); $('toggle').addEvent('click', function(e){ e = new Event(e); mySlide.toggle(); e.stop(); }); }); </script> ``` Like I said above I am restricted to moo 1.1 at present, but if there is a answer that will work with both 1.1 and 1.2 or if its a similar change I would be grateful to hear, as it will be updated at some point.
I looked at url rewriting, but ultimately decided on a simpler solution. I just moved the file.aspx into a directory and renamed it to default.aspx.
235,759
<p>I <em>think</em> I know how to create custom encrypted RSA keys, but how can I read one encrypted like ssh-keygen does?</p> <p>I know I can do this:</p> <pre><code>OpenSSL::PKey::RSA.new(File.read('private_key')) </code></pre> <p>But then OpenSSL asks me for the passphrase... How can I pass it to OpenSSL as a parameter?</p> <p>And, how can I create one compatible to the ones generated by ssh-keygen?</p> <p>I do something like this to create private encrypted keys:</p> <pre><code>pass = '123456' key = OpenSSL::PKey::RSA.new(1024) key = "0000000000000000#{key.to_der}" c = OpenSSL::Cipher::Cipher.new('aes-256-cbc') c.encrypt c.key = Digest::SHA1.hexdigest(pass).unpack('a2' * 32).map {|x| x.hex}.pack('c' * 32) c.iv = iv encrypted_key = c.update(key) encrypted_key &lt;&lt; c.final </code></pre> <p>Also, keys generated by OpenSSL::PKey::RSA.new(1024) (without encryption), don't work when I try password-less logins (i.e., I copy the public key to the server and use the private one to login).</p> <p>Also, when I open an ssh-keygen file via OpenSSL and then check its contents, it appears to have additional characters at the beginning and end of the key. Is this normal?</p> <p>I don't really understand some of this security stuff, but I'm trying to learn. What is it that I'm doing wrong?</p>
[ { "answer_id": 235847, "author": "Ivan", "author_id": 16957, "author_profile": "https://Stackoverflow.com/users/16957", "pm_score": -1, "selected": true, "text": "<p>I've made some progress on this. If I use the Net::SSH library, I can do this:</p>\n\n<pre><code>Net::SSH::KeyFactory.load_private_key 'keyfile', 'passphrase'\n</code></pre>\n\n<p>By reading the source code I have yet to figure out what the library does to OpenSSL's PKey::RSA.new to accomplish this... And then I go and test again, and sure enough, OpenSSL can open the private key just fine without Net::SSH... I've made so much tests that somehow I didn't test this correctly before.</p>\n\n<p>But I still have the issue of creating an SSH compatible key pair... and maybe I'll go test again and have the answer :P ... nah, I'm not that interested in that part</p>\n" }, { "answer_id": 862090, "author": "Andy Jeffries", "author_id": 2645935, "author_profile": "https://Stackoverflow.com/users/2645935", "pm_score": 3, "selected": false, "text": "<p>According to the blog post here:</p>\n\n<p><a href=\"http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/\" rel=\"noreferrer\">http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/</a></p>\n\n<p>You can simply do:</p>\n\n<p>OpenSSL::PKey::RSA.new(File.read('private_key'), 'passphrase')</p>\n\n<p>Best of luck.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957/" ]
I *think* I know how to create custom encrypted RSA keys, but how can I read one encrypted like ssh-keygen does? I know I can do this: ``` OpenSSL::PKey::RSA.new(File.read('private_key')) ``` But then OpenSSL asks me for the passphrase... How can I pass it to OpenSSL as a parameter? And, how can I create one compatible to the ones generated by ssh-keygen? I do something like this to create private encrypted keys: ``` pass = '123456' key = OpenSSL::PKey::RSA.new(1024) key = "0000000000000000#{key.to_der}" c = OpenSSL::Cipher::Cipher.new('aes-256-cbc') c.encrypt c.key = Digest::SHA1.hexdigest(pass).unpack('a2' * 32).map {|x| x.hex}.pack('c' * 32) c.iv = iv encrypted_key = c.update(key) encrypted_key << c.final ``` Also, keys generated by OpenSSL::PKey::RSA.new(1024) (without encryption), don't work when I try password-less logins (i.e., I copy the public key to the server and use the private one to login). Also, when I open an ssh-keygen file via OpenSSL and then check its contents, it appears to have additional characters at the beginning and end of the key. Is this normal? I don't really understand some of this security stuff, but I'm trying to learn. What is it that I'm doing wrong?
I've made some progress on this. If I use the Net::SSH library, I can do this: ``` Net::SSH::KeyFactory.load_private_key 'keyfile', 'passphrase' ``` By reading the source code I have yet to figure out what the library does to OpenSSL's PKey::RSA.new to accomplish this... And then I go and test again, and sure enough, OpenSSL can open the private key just fine without Net::SSH... I've made so much tests that somehow I didn't test this correctly before. But I still have the issue of creating an SSH compatible key pair... and maybe I'll go test again and have the answer :P ... nah, I'm not that interested in that part
235,822
<p>How can my vbscript detect whether or not it is running in a UAC elevated context?</p> <p>I have no problem detecting the user, and seeing if the user is within the Administrators group. But this still doesn't answer the question of whether the process has elevated privs or not, when running under Vista or Windows 2008. Please note, I need only to <em>detect</em> this status; not attempt to elevate or (err ..) de-elevate.</p>
[ { "answer_id": 258070, "author": "quux", "author_id": 2383, "author_profile": "https://Stackoverflow.com/users/2383", "pm_score": 4, "selected": true, "text": "<p>The method I finally settled on depends on the fact that Vista and Windows 2008 have the whoami.exe utility, and it detects the integrity level of the user who owns the process. A couple of screenshots help here:</p>\n\n<p><a href=\"http://lh3.ggpht.com/_Svunm47buj0/SQ6ql4iNjPI/AAAAAAAAAeA/iwbcSrAZqRg/whoami%20-%20adminuser%20-%20groups%20-%20cropped.png?imgmax=512\">WHOAMI, normal and elevated, on Vista http://lh3.ggpht.com/_Svunm47buj0/SQ6ql4iNjPI/AAAAAAAAAeA/iwbcSrAZqRg/whoami%20-%20adminuser%20-%20groups%20-%20cropped.png?imgmax=512</a></p>\n\n<p>You can see that when cmd is running elevated, whoami /groups reports a \"High\" mandatory integrity level and a different SID than when running non-elevated. In the pic, the top session is normal, the one underneath is running elevated after UAC prompt.</p>\n\n<p>Knowing that, here is the code I used. It essentially checks the OS version, and if it is Vista or Server 2008, calls CheckforElevation which runs whoami.exe /groups, and looks for the string S-1-16-12288 in the output. In this example I just echo status; in the real script I branch to different actions based on the result.</p>\n\n<pre><code>sub GetOSVersion\nDim strComputer, oWMIService, colOSInfo, oOSProperty, strCaption, strOSFamily\nstrComputer = \".\"\nSet oWMIService = GetObject(\"winmgmts:\\\\\" &amp; strComputer &amp; \"\\root\\cimv2\")\nSet colOSInfo = oWMIService.ExecQuery(\"Select * from Win32_OperatingSystem\")\n'I hate looping through just to get one property. But dunno another way!\nFor Each oOSProperty in colOSInfo \n strCaption = oOSProperty.Caption \nNext\nIf InStr(1,strCaption, \"Vista\", vbTextCompare) Then strOSFamily = \"Vista\"\nIf InStr(1,strCaption, \"2008\", vbTextCompare) Then strOSFamily = \"2008\"\nIf InStr(1,strCaption, \"XP\", vbTextCompare) Then strOSFamily = \"XP\"\nIf InStr(1,strCaption, \"2003\", vbTextCompare) Then strOSFamily = \"2003\"\nIf InStr(1,strCaption, \"2000\", vbTextCompare) Then strOSFamily = \"2000\"\nIf strOSFamily = \"\" Then \n Wscript.Echo \"No known OS found. (Script can detect Windows 2000, 2003, XP, Vista, 2008.)\" \nElse \n Wscript.Echo \"OS Family = \" &amp; strOSFamily\nEnd If\nSelect Case strOSFamily 'if Vista/2008 then call CheckforElevation\nCase \"Vista\"\n CheckforElevation\nCase \"2008\"\n CheckforElevation\nCase Else\n Exit Sub\nEnd Select\nend sub\n\nsub CheckforElevation 'test whether user has elevated token \nDim oShell, oExecWhoami, oWhoamiOutput, strWhoamiOutput, boolHasElevatedToken\nSet oShell = CreateObject(\"WScript.Shell\")\nSet oExecWhoami = oShell.Exec(\"whoami /groups\")\nSet oWhoamiOutput = oExecWhoami.StdOut\nstrWhoamiOutput = oWhoamiOutput.ReadAll\nIf InStr(1, strWhoamiOutput, \"S-1-16-12288\", vbTextCompare) Then boolHasElevatedToken = True\nIf boolHasElevatedToken Then\n Wscript.Echo \"Current script is running with elevated privs.\"\nElse\n Wscript.Echo \"Current script is NOT running with elevated privs.\"\nEnd If\nend sub\n</code></pre>\n" }, { "answer_id": 2905751, "author": "Darwin", "author_id": 259484, "author_profile": "https://Stackoverflow.com/users/259484", "pm_score": 2, "selected": false, "text": "<p>The solution I am posting is a couple production ready VBScripts that leverage whoami to find this information. One cool thing about them is that they work with XP (for information that is available on XP) if you place a copy of the Resource Kit version of whoami.exe next to the script (or in the system32 folder of each machine).</p>\n\n<p><a href=\"http://csi-windows.com/toolkit/csi-issession\" rel=\"nofollow noreferrer\">CSI_IsSession.vbs</a> contains a single function that can tell you almost anything you want to know about UAC or the current session the script is running under.</p>\n\n<p><a href=\"http://csi-windows.com/toolkit/vbscriptuackit\" rel=\"nofollow noreferrer\">VBScriptUACKit.vbs</a> (which uses CSI_IsSession.vbs) allows you to selectively prompt for UAC in a script by relaunching itself. Has been designed and debugged to work under many execution scenarios.</p>\n\n<p>Both scripts contain sample code that demonstrates how to use the core script code.</p>\n" }, { "answer_id": 19894732, "author": "Keith S Garner", "author_id": 2863832, "author_profile": "https://Stackoverflow.com/users/2863832", "pm_score": 3, "selected": false, "text": "<p>Here's my shorter solution:</p>\n\n<pre><code>Function IsElevated\n IsElevated = CreateObject(\"WScript.Shell\").Run(\"cmd.exe /c \"\"whoami /groups|findstr S-1-16-12288\"\"\", 0, true) = 0\nEnd function \n</code></pre>\n\n<p>This function is stand alone, and won't display any flashing Console Window when executed. </p>\n" }, { "answer_id": 30484751, "author": "Alexey", "author_id": 4945039, "author_profile": "https://Stackoverflow.com/users/4945039", "pm_score": 0, "selected": false, "text": "<p>a little bit shorter in WSH Jscript</p>\n\n<pre><code>function isElevated(){\n var strCaption = \"\";\n for (var enumItems=new Enumerator(GetObject(\"winmgmts:\\\\\\\\.\\\\root\\\\CIMV2\").ExecQuery(\"Select * from Win32_OperatingSystem\")); !enumItems.atEnd(); enumItems.moveNext()) {\n strCaption += enumItems.item().Caption;\n }\n if(/Vista|2008|Windows\\s7|Windows\\s8/.test(strCaption)){\n return (new ActiveXObject(\"WScript.Shell\").run('cmd.exe /c \"whoami /groups|findstr S-1-16-12288\"', 0, true)) == 0;\n }else{return true}\n} \n\nWScript.Echo(isElevated());\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2383/" ]
How can my vbscript detect whether or not it is running in a UAC elevated context? I have no problem detecting the user, and seeing if the user is within the Administrators group. But this still doesn't answer the question of whether the process has elevated privs or not, when running under Vista or Windows 2008. Please note, I need only to *detect* this status; not attempt to elevate or (err ..) de-elevate.
The method I finally settled on depends on the fact that Vista and Windows 2008 have the whoami.exe utility, and it detects the integrity level of the user who owns the process. A couple of screenshots help here: [WHOAMI, normal and elevated, on Vista http://lh3.ggpht.com/\_Svunm47buj0/SQ6ql4iNjPI/AAAAAAAAAeA/iwbcSrAZqRg/whoami%20-%20adminuser%20-%20groups%20-%20cropped.png?imgmax=512](http://lh3.ggpht.com/_Svunm47buj0/SQ6ql4iNjPI/AAAAAAAAAeA/iwbcSrAZqRg/whoami%20-%20adminuser%20-%20groups%20-%20cropped.png?imgmax=512) You can see that when cmd is running elevated, whoami /groups reports a "High" mandatory integrity level and a different SID than when running non-elevated. In the pic, the top session is normal, the one underneath is running elevated after UAC prompt. Knowing that, here is the code I used. It essentially checks the OS version, and if it is Vista or Server 2008, calls CheckforElevation which runs whoami.exe /groups, and looks for the string S-1-16-12288 in the output. In this example I just echo status; in the real script I branch to different actions based on the result. ``` sub GetOSVersion Dim strComputer, oWMIService, colOSInfo, oOSProperty, strCaption, strOSFamily strComputer = "." Set oWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colOSInfo = oWMIService.ExecQuery("Select * from Win32_OperatingSystem") 'I hate looping through just to get one property. But dunno another way! For Each oOSProperty in colOSInfo strCaption = oOSProperty.Caption Next If InStr(1,strCaption, "Vista", vbTextCompare) Then strOSFamily = "Vista" If InStr(1,strCaption, "2008", vbTextCompare) Then strOSFamily = "2008" If InStr(1,strCaption, "XP", vbTextCompare) Then strOSFamily = "XP" If InStr(1,strCaption, "2003", vbTextCompare) Then strOSFamily = "2003" If InStr(1,strCaption, "2000", vbTextCompare) Then strOSFamily = "2000" If strOSFamily = "" Then Wscript.Echo "No known OS found. (Script can detect Windows 2000, 2003, XP, Vista, 2008.)" Else Wscript.Echo "OS Family = " & strOSFamily End If Select Case strOSFamily 'if Vista/2008 then call CheckforElevation Case "Vista" CheckforElevation Case "2008" CheckforElevation Case Else Exit Sub End Select end sub sub CheckforElevation 'test whether user has elevated token Dim oShell, oExecWhoami, oWhoamiOutput, strWhoamiOutput, boolHasElevatedToken Set oShell = CreateObject("WScript.Shell") Set oExecWhoami = oShell.Exec("whoami /groups") Set oWhoamiOutput = oExecWhoami.StdOut strWhoamiOutput = oWhoamiOutput.ReadAll If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then boolHasElevatedToken = True If boolHasElevatedToken Then Wscript.Echo "Current script is running with elevated privs." Else Wscript.Echo "Current script is NOT running with elevated privs." End If end sub ```
235,855
<p>I'm trying to get a background image of a HTML element (body, div, etc.) to stretch its entire width and height.</p> <p>Not having much luck. Is it even possible or do I have to do it some other way besides it being a background image?</p> <p>My current css is:</p> <pre><code>body { background-position: left top; background-image: url(_images/home.jpg); background-repeat: no-repeat; } </code></pre> <p>Thanks in advance.</p> <p>Edit: I'm not keen on maintaining the CSS in Gabriel's suggestion so I'm changing the layout of the page instead. But that seems like the best answer so I'm marking it as such.</p>
[ { "answer_id": 235866, "author": "Travis Collins", "author_id": 30460, "author_profile": "https://Stackoverflow.com/users/30460", "pm_score": 3, "selected": false, "text": "<p>Not sure that stretching a background image is possible. If you find that it's not possible, or not reliable in all of your target browsers, you could try using a stretched img tag with z-index set lower, and position set to absolute so that other content appears on top of it.</p>\n\n<p>Let us know what you end up doing.</p>\n\n<p>Edit: What I suggested is basically what's in gabriel's link. So try that :)</p>\n" }, { "answer_id": 236460, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>You cannot in pure CSS. Having an image covering the whole page behind all other components is probably your best bet (looks like that's the solution given above). Anyway, chances are it will look awful anyway. I would try either an image big enough to cover most screen resolutions (say up to 1600x1200, above it is scarcer), to limit the width of the page, or just to use an image that tile.</p>\n" }, { "answer_id": 241082, "author": "Traingamer", "author_id": 27609, "author_profile": "https://Stackoverflow.com/users/27609", "pm_score": 3, "selected": false, "text": "<p>To expand on @PhiLho answer, you can center a very large image (or any size image) on a page with: </p>\n\n<pre><code>{ \nbackground-image: url(_images/home.jpg);\nbackground-repeat:no-repeat;\nbackground-position:center; \n}\n</code></pre>\n\n<p>Or you could use a smaller image with a background color that matches the background of the image (if it is a solid color). This may or may not suit your purposes.</p>\n\n<pre><code>{ \nbackground-color: green;\nbackground-image: url(_images/home.jpg);\nbackground-repeat:no-repeat;\nbackground-position:center; \n}\n</code></pre>\n" }, { "answer_id": 1103672, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": false, "text": "<p>Use the <code>background-size</code> property: <a href=\"http://www.w3.org/TR/css3-background/#the-background-size\" rel=\"noreferrer\">http://www.w3.org/TR/css3-background/#the-background-size</a></p>\n" }, { "answer_id": 5331272, "author": "Nathan", "author_id": 663232, "author_profile": "https://Stackoverflow.com/users/663232", "pm_score": 9, "selected": true, "text": "<pre><code>&lt;style&gt;\n { margin: 0; padding: 0; }\n\n html { \n background: url('images/yourimage.jpg') no-repeat center center fixed; \n -webkit-background-size: cover;\n -moz-background-size: cover;\n -o-background-size: cover;\n background-size: cover;\n }\n&lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 16417072, "author": "Tamal Samui", "author_id": 1331593, "author_profile": "https://Stackoverflow.com/users/1331593", "pm_score": 3, "selected": false, "text": "<p>In short you can try this....</p>\n\n<pre><code>&lt;div data-role=\"page\" style=\"background:url('backgrnd.png'); background-repeat: no-repeat; background-size: 100% 100%;\" &gt;\n</code></pre>\n\n<p></p>\n\n<p>Where I have used few css and js...</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"css/jquery.mobile-1.0.1.min.css\" /&gt;\n&lt;script src=\"js/jquery-1.7.1.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"js/jquery.mobile-1.0.1.min.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>And it is working fine for me.</p>\n" }, { "answer_id": 22166903, "author": "Behnam", "author_id": 3243488, "author_profile": "https://Stackoverflow.com/users/3243488", "pm_score": 2, "selected": false, "text": "<pre><code>background: url(images/bg.jpg) no-repeat center center fixed; \n-webkit-background-size: cover;\n-moz-background-size: cover;\n-o-background-size: cover;\nbackground-size: cover;\n</code></pre>\n" }, { "answer_id": 30811127, "author": "live-love", "author_id": 436341, "author_profile": "https://Stackoverflow.com/users/436341", "pm_score": 2, "selected": false, "text": "<p>If you have a large landscape image, this example here resizes the background in portrait mode, so that it displays on top, leaving blank on the bottom:</p>\n\n<pre><code>html, body {\n margin: 0;\n padding: 0;\n min-height: 100%;\n}\n\nbody {\n background-image: url('myimage.jpg');\n background-position-x: center;\n background-position-y: bottom;\n background-repeat: no-repeat;\n background-attachment: scroll;\n -webkit-background-size: cover;\n -moz-background-size: cover;\n -o-background-size: cover;\n background-size: cover;\n}\n\n@media screen and (orientation:portrait) {\n body {\n background-position-y: top;\n -webkit-background-size: contain;\n -moz-background-size: contain;\n -o-background-size: contain;\n background-size: contain;\n }\n}\n</code></pre>\n" }, { "answer_id": 31320603, "author": "Badar", "author_id": 576750, "author_profile": "https://Stackoverflow.com/users/576750", "pm_score": 2, "selected": false, "text": "<p>The following code I use mostly for achieving the asked effect:</p>\n\n<pre><code>body {\n background-image: url('../images/bg.jpg');\n background-repeat: no-repeat;\n background-size: 100%;\n}\n</code></pre>\n" }, { "answer_id": 41288038, "author": "leocborges", "author_id": 1358674, "author_profile": "https://Stackoverflow.com/users/1358674", "pm_score": 3, "selected": false, "text": "<p>If you need to stretch your background image while resizing the screen and you don't need compatibility with older browser versions this will do the work:</p>\n\n<pre><code>body {\n background-image: url('../images/image.jpg');\n background-repeat: no-repeat;\n background-size: cover;\n}\n</code></pre>\n" }, { "answer_id": 60347436, "author": "Ebele Nwaelene", "author_id": 12941444, "author_profile": "https://Stackoverflow.com/users/12941444", "pm_score": 0, "selected": false, "text": "<p>image{</p>\n\n<pre><code>background-size: cover;\n background-repeat: no-repeat;\n background-position: center;\n padding: 0 3em 0 3em; \nmargin: -1.5em -0.5em -0.5em -1em; \n width: absolute;\n max-width: 100%; \n</code></pre>\n" }, { "answer_id": 61490906, "author": "Salah Ayman", "author_id": 8916785, "author_profile": "https://Stackoverflow.com/users/8916785", "pm_score": 0, "selected": false, "text": "<p>Simply make a div to be the direct child of body (with the class name bg for example), encompassing all other elements in the body, and add this to the CSS file:</p>\n\n<pre><code>.bg {\n background-image: url('_images/home.jpg');//Put your appropriate image URL here\n background-size: 100% 100%; //You need to put 100% twice here to stretch width and height\n}\n</code></pre>\n\n<p>Refer to this link: <a href=\"https://www.w3schools.com/css/css_rwd_images.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/css/css_rwd_images.asp</a>\nScroll down to the part that says:</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>If the background-size property is set to \"100% 100%\", the background image will stretch to cover the entire content area</li>\n </ol>\n</blockquote>\n\n<p>There it shows the 'img_flowers.jpg' stretching to the size of the screen or browser regardless of how you resize it.</p>\n" }, { "answer_id": 62069614, "author": "msk_sureshkumar", "author_id": 970425, "author_profile": "https://Stackoverflow.com/users/970425", "pm_score": 1, "selected": false, "text": "<p>It works for me</p>\n\n<pre><code>.page-bg {\n background: url(\"res://background\");\n background-position: center center;\n background-repeat: no-repeat;\n background-size: 100% 100%;\n}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ]
I'm trying to get a background image of a HTML element (body, div, etc.) to stretch its entire width and height. Not having much luck. Is it even possible or do I have to do it some other way besides it being a background image? My current css is: ``` body { background-position: left top; background-image: url(_images/home.jpg); background-repeat: no-repeat; } ``` Thanks in advance. Edit: I'm not keen on maintaining the CSS in Gabriel's suggestion so I'm changing the layout of the page instead. But that seems like the best answer so I'm marking it as such.
``` <style> { margin: 0; padding: 0; } html { background: url('images/yourimage.jpg') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } </style> ```
235,868
<p>Given this algorithm, I would like to know if there exists an iterative version. Also, I want to know if the iterative version can be faster.</p> <p>This some kind of pseudo-python...</p> <p>the algorithm returns a reference to root of the tree</p> <pre><code>make_tree(array a) if len(a) == 0 return None; node = pick a random point from the array calculate distances of the point against the others calculate median of such distances node.left = make_tree(subset of the array, such that the distance of points is lower to the median of distances) node.right = make_tree(subset, such the distance is greater or equal to the median) return node </code></pre>
[ { "answer_id": 235873, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Making an iterative version is simply a matter of using your own stack instead of the normal language call stack. I doubt the iterative version would be faster, as the normal call stack is optimized for this purpose.</p>\n" }, { "answer_id": 235877, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 1, "selected": false, "text": "<p>Yes it is possible to make any recursive algorithm iterative. Implicitly, when you create a recursive algorithm each call places the prior call onto the stack. What you want to do is make the implicit call stack into an explicit one. The iterative version won't necessarily be faster, but you won't have to worry about a stack overflow. (do I get a badge for using the name of the site in my answer?</p>\n" }, { "answer_id": 235882, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "<p>While it is true in the general sense that directly converting a recursive algorithm into an iterative one will require an explicit stack, there is a specific sub-set of algorithms which render directly in iterative form (without the need for a stack). These renderings may not have the same performance guarantees (iterating over a functional list vs recursive deconstruction), but they do often exist.</p>\n" }, { "answer_id": 235894, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 2, "selected": false, "text": "<p>The data you're getting is random so the tree can be an arbitrary binary tree. For this case, you can use a threaded binary tree, which can be traversed and built w/o recursion and no stack. The nodes have a flag that indicate if the link is a link to another node or how to get to the &quot;next node&quot;.</p>\n<p>From <a href=\"http://en.wikipedia.org/wiki/Threaded_binary_tree\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Threaded_binary_tree</a>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/7/7a/Threaded_tree.svg/330px-Threaded_tree.svg.png\" alt=\"alt text\" /></p>\n" }, { "answer_id": 235939, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": true, "text": "<p>A recursive function with only one recursive call can usually be turned into a tail-recursive function without too much effort, and then it's trivial to convert it into an iterative function. The canonical example here is factorial:</p>\n\n<pre><code># naïve recursion\ndef fac(n):\n if n &lt;= 1:\n return 1\n else:\n return n * fac(n - 1)\n\n# tail-recursive with accumulator\ndef fac(n):\n def fac_helper(m, k):\n if m &lt;= 1:\n return k\n else:\n return fac_helper(m - 1, m * k)\n return fac_helper(n, 1)\n\n# iterative with accumulator\ndef fac(n):\n k = 1\n while n &gt; 1:\n n, k = n - 1, n * k\n return k\n</code></pre>\n\n<p>However, your case here involves two recursive calls, and unless you significantly rework your algorithm, you need to keep a stack. Managing your own stack may be a little faster than using Python's function call stack, but the added speed and depth will probably not be worth the complexity. The canonical example here would be the Fibonacci sequence:</p>\n\n<pre><code># naïve recursion\ndef fib(n):\n if n &lt;= 1:\n return 1\n else:\n return fib(n - 1) + fib(n - 2)\n\n# tail-recursive with accumulator and stack\ndef fib(n):\n def fib_helper(m, k, stack):\n if m &lt;= 1:\n if stack:\n m = stack.pop()\n return fib_helper(m, k + 1, stack)\n else:\n return k + 1\n else:\n stack.append(m - 2)\n return fib_helper(m - 1, k, stack)\n return fib_helper(n, 0, [])\n\n# iterative with accumulator and stack\ndef fib(n):\n k, stack = 0, []\n while 1:\n if n &lt;= 1:\n k = k + 1\n if stack:\n n = stack.pop()\n else:\n break\n else:\n stack.append(n - 2)\n n = n - 1\n return k\n</code></pre>\n\n<p>Now, your case is a lot tougher than this: a simple accumulator will have difficulties expressing a partly-built tree with a pointer to where a subtree needs to be generated. You'll want a <a href=\"http://www.haskell.org/haskellwiki/Zipper\" rel=\"noreferrer\">zipper</a> -- not easy to implement in a not-really-functional language like Python.</p>\n" }, { "answer_id": 236187, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "<p>Depending on how you define \"iterative\", there is another solution not mentioned by the previous answers. If \"iterative\" just means \"not subject to a stack overflow exception\" (but \"allowed to use 'let rec'\"), then in a language that supports tail calls, you can write a version using continuations (rather than an \"explicit stack\"). The F# code below illustrates this. It is similar to your original problem, in that it builds a BST out of an array. If the array is shuffled randomly, the tree is relatively balanced and the recursive version does not create too deep a stack. But turn off shuffling, and the tree gets unbalanced, and the recursive version stack-overflows whereas the iterative-with-continuations version continues along happily.</p>\n\n<pre><code>#light \nopen System\n\nlet printResults = false\nlet MAX = 20000\nlet shuffleIt = true\n\n// handy helper function\nlet rng = new Random(0)\nlet shuffle (arr : array&lt;'a&gt;) = // '\n let n = arr.Length\n for x in 1..n do\n let i = n-x\n let j = rng.Next(i+1)\n let tmp = arr.[i]\n arr.[i] &lt;- arr.[j]\n arr.[j] &lt;- tmp\n\n// Same random array\nlet sampleArray = Array.init MAX (fun x -&gt; x) \nif shuffleIt then\n shuffle sampleArray\n\nif printResults then\n printfn \"Sample array is %A\" sampleArray\n\n// Tree type\ntype Tree =\n | Node of int * Tree * Tree\n | Leaf\n\n// MakeTree1 is recursive\nlet rec MakeTree1 (arr : array&lt;int&gt;) lo hi = // [lo,hi)\n if lo = hi then\n Leaf\n else\n let pivot = arr.[lo]\n // partition\n let mutable storeIndex = lo + 1\n for i in lo + 1 .. hi - 1 do\n if arr.[i] &lt; pivot then\n let tmp = arr.[i]\n arr.[i] &lt;- arr.[storeIndex]\n arr.[storeIndex] &lt;- tmp \n storeIndex &lt;- storeIndex + 1\n Node(pivot, MakeTree1 arr (lo+1) storeIndex, MakeTree1 arr storeIndex hi)\n\n// MakeTree2 has all tail calls (uses continuations rather than a stack, see\n// http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!171.entry \n// for more explanation)\nlet MakeTree2 (arr : array&lt;int&gt;) lo hi = // [lo,hi)\n let rec MakeTree2Helper (arr : array&lt;int&gt;) lo hi k =\n if lo = hi then\n k Leaf\n else\n let pivot = arr.[lo]\n // partition\n let storeIndex = ref(lo + 1)\n for i in lo + 1 .. hi - 1 do\n if arr.[i] &lt; pivot then\n let tmp = arr.[i]\n arr.[i] &lt;- arr.[!storeIndex]\n arr.[!storeIndex] &lt;- tmp \n storeIndex := !storeIndex + 1\n MakeTree2Helper arr (lo+1) !storeIndex (fun lacc -&gt;\n MakeTree2Helper arr !storeIndex hi (fun racc -&gt;\n k (Node(pivot,lacc,racc))))\n MakeTree2Helper arr lo hi (fun x -&gt; x)\n\n// MakeTree2 never stack overflows\nprintfn \"calling MakeTree2...\"\nlet tree2 = MakeTree2 sampleArray 0 MAX\nif printResults then\n printfn \"MakeTree2 yields\"\n printfn \"%A\" tree2\n\n// MakeTree1 might stack overflow\nprintfn \"calling MakeTree1...\"\nlet tree1 = MakeTree1 sampleArray 0 MAX\nif printResults then\n printfn \"MakeTree1 yields\"\n printfn \"%A\" tree1\n\nprintfn \"Trees are equal: %A\" (tree1 = tree2)\n</code></pre>\n" }, { "answer_id": 34528629, "author": "Walid Da.", "author_id": 1251220, "author_profile": "https://Stackoverflow.com/users/1251220", "pm_score": 0, "selected": false, "text": "<p>Here is stack based iterative solution (Java):</p>\n\n<pre><code>public static Tree builtBSTFromSortedArray(int[] inputArray){\n\n Stack toBeDone=new Stack(\"sub trees to be created under these nodes\");\n\n //initialize start and end \n int start=0;\n int end=inputArray.length-1;\n\n //keep memoy of the position (in the array) of the previously created node\n int previous_end=end;\n int previous_start=start;\n\n //Create the result tree \n Node root=new Node(inputArray[(start+end)/2]);\n Tree result=new Tree(root);\n while(root!=null){\n System.out.println(\"Current root=\"+root.data);\n\n //calculate last middle (last node position using the last start and last end)\n int last_mid=(previous_start+previous_end)/2;\n\n //*********** add left node to the previously created node ***********\n //calculate new start and new end positions\n //end is the previous index position minus 1\n end=last_mid-1; \n //start will not change for left nodes generation\n start=previous_start; \n //check if the index exists in the array and add the left node\n if (end&gt;=start){\n root.left=new Node(inputArray[((start+end)/2)]);\n System.out.println(\"\\tCurrent root.left=\"+root.left.data);\n }\n else\n root.left=null;\n //save previous_end value (to be used in right node creation)\n int previous_end_bck=previous_end;\n //update previous end\n previous_end=end;\n\n //*********** add right node to the previously created node ***********\n //get the initial value (inside the current iteration) of previous end\n end=previous_end_bck;\n //start is the previous index position plus one\n start=last_mid+1;\n //check if the index exists in the array and add the right node\n if (start&lt;=end){\n root.right=new Node(inputArray[((start+end)/2)]);\n System.out.println(\"\\tCurrent root.right=\"+root.right.data);\n //save the created node and its index position (start &amp; end) in the array to toBeDone stack\n toBeDone.push(root.right);\n toBeDone.push(new Node(start));\n toBeDone.push(new Node(end)); \n }\n\n //*********** update the value of root ***********\n if (root.left!=null){\n root=root.left; \n }\n else{\n if (toBeDone.top!=null) previous_end=toBeDone.pop().data;\n if (toBeDone.top!=null) previous_start=toBeDone.pop().data;\n root=toBeDone.pop(); \n }\n }\n return result; \n}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
Given this algorithm, I would like to know if there exists an iterative version. Also, I want to know if the iterative version can be faster. This some kind of pseudo-python... the algorithm returns a reference to root of the tree ``` make_tree(array a) if len(a) == 0 return None; node = pick a random point from the array calculate distances of the point against the others calculate median of such distances node.left = make_tree(subset of the array, such that the distance of points is lower to the median of distances) node.right = make_tree(subset, such the distance is greater or equal to the median) return node ```
A recursive function with only one recursive call can usually be turned into a tail-recursive function without too much effort, and then it's trivial to convert it into an iterative function. The canonical example here is factorial: ``` # naïve recursion def fac(n): if n <= 1: return 1 else: return n * fac(n - 1) # tail-recursive with accumulator def fac(n): def fac_helper(m, k): if m <= 1: return k else: return fac_helper(m - 1, m * k) return fac_helper(n, 1) # iterative with accumulator def fac(n): k = 1 while n > 1: n, k = n - 1, n * k return k ``` However, your case here involves two recursive calls, and unless you significantly rework your algorithm, you need to keep a stack. Managing your own stack may be a little faster than using Python's function call stack, but the added speed and depth will probably not be worth the complexity. The canonical example here would be the Fibonacci sequence: ``` # naïve recursion def fib(n): if n <= 1: return 1 else: return fib(n - 1) + fib(n - 2) # tail-recursive with accumulator and stack def fib(n): def fib_helper(m, k, stack): if m <= 1: if stack: m = stack.pop() return fib_helper(m, k + 1, stack) else: return k + 1 else: stack.append(m - 2) return fib_helper(m - 1, k, stack) return fib_helper(n, 0, []) # iterative with accumulator and stack def fib(n): k, stack = 0, [] while 1: if n <= 1: k = k + 1 if stack: n = stack.pop() else: break else: stack.append(n - 2) n = n - 1 return k ``` Now, your case is a lot tougher than this: a simple accumulator will have difficulties expressing a partly-built tree with a pointer to where a subtree needs to be generated. You'll want a [zipper](http://www.haskell.org/haskellwiki/Zipper) -- not easy to implement in a not-really-functional language like Python.
235,880
<p>How can I convert an <code>Int64</code> to an <code>Int32</code> type in F# without using the <code>Microsoft.FSharp.Compatibility.Int32.of_int64</code>?</p> <p>I'm doing this because interactive doesn't seem to work when I try:</p> <pre><code>open Microsoft.FSharp.Compatibility </code></pre> <p>With <code>FSharp.PowerPack</code> added as a reference it says: </p> <blockquote> <p>error FS0039: The namespace 'Compatibility' is not defined.</p> </blockquote> <p><strong>Edit:</strong> Does anyone have an answer to the question? The suggestions about the int types are useful and informative, but I'm having the same issue opening the powerpack namespace in F# interactive.</p>
[ { "answer_id": 235893, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 5, "selected": false, "text": "<p>F# 1.9.6 has a type conversion function so you can do this: </p>\n\n<pre><code>let num = 1000\nlet num64 = int64(num)\n</code></pre>\n" }, { "answer_id": 235913, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "<p>Notice that in this type of conversion, when you reduce the size of a value, the most significant bytes are thrown away, so your data might be truncated:</p>\n\n<pre><code>&gt; let bignum = 4294967297L;;\nval bignum : int64\n\n&gt; let myint = int32(bignum);;\nval myint : int32\n\n&gt; myint;;\nval it : int32 = 1\n</code></pre>\n" }, { "answer_id": 236032, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 1, "selected": false, "text": "<p>Note that the functions for converting to each integer type have the same names as the types themselves, and are defined in the library spec (see below). (With the release of the CTP (1.9.6.2), a lot of the library and the namespaces changed a bit compared to previous releases, but it will probably be more 'stable' moving forward.)</p>\n\n<p><a href=\"http://research.microsoft.com/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html\" rel=\"nofollow noreferrer\">http://research.microsoft.com/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html</a></p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I convert an `Int64` to an `Int32` type in F# without using the `Microsoft.FSharp.Compatibility.Int32.of_int64`? I'm doing this because interactive doesn't seem to work when I try: ``` open Microsoft.FSharp.Compatibility ``` With `FSharp.PowerPack` added as a reference it says: > > error FS0039: The namespace 'Compatibility' is not defined. > > > **Edit:** Does anyone have an answer to the question? The suggestions about the int types are useful and informative, but I'm having the same issue opening the powerpack namespace in F# interactive.
F# 1.9.6 has a type conversion function so you can do this: ``` let num = 1000 let num64 = int64(num) ```
235,955
<p>I just downloaded MVC and I am going through a tutorial. Everything goes fine until I try to declare a DataContext object.</p> <p>My dbml is named <strong>db.dbml</strong> (tried another on named test.dbml) and when I try this:</p> <pre><code>public dbDataContext db = new dbDataContext(); </code></pre> <p>I get:</p> <blockquote> <p>The type or namespace name 'dbDataContext' could not be found ...</p> </blockquote> <p>Am I missing something? In webforms this is all I had to do, and in the tutorial that is all that is shown. I downloaded the newest MVC today...</p> <p>Thank you.</p> <p>**EDIT: I am using VS2008 SP1</p>
[ { "answer_id": 238847, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "<p>A few quick questiosn: Is the name of your data context \"dbDataContext\"?... also, is it in a namespace? (do you have that namespace referenced).</p>\n\n<p>Another question... is this a runtime error, or a compiletime error?</p>\n" }, { "answer_id": 238851, "author": "Aristotle Ucab", "author_id": 31445, "author_profile": "https://Stackoverflow.com/users/31445", "pm_score": 0, "selected": false, "text": "<p>try to add context to the namespace {ProjectName}.Models...</p>\n\n<p>because the models are stored in the models namespace.. try to check if you have include the namespace in your current context..</p>\n" }, { "answer_id": 403942, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>This is a sp1 bug if you are using partial classes, see the following and work-arounds:\n<a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361577\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361577</a></p>\n" }, { "answer_id": 1671493, "author": "pallavi", "author_id": 202289, "author_profile": "https://Stackoverflow.com/users/202289", "pm_score": -1, "selected": false, "text": "<p>once you add the class just build the solution.you ll find your classes in the list</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
I just downloaded MVC and I am going through a tutorial. Everything goes fine until I try to declare a DataContext object. My dbml is named **db.dbml** (tried another on named test.dbml) and when I try this: ``` public dbDataContext db = new dbDataContext(); ``` I get: > > The type or namespace name > 'dbDataContext' could not be found ... > > > Am I missing something? In webforms this is all I had to do, and in the tutorial that is all that is shown. I downloaded the newest MVC today... Thank you. \*\*EDIT: I am using VS2008 SP1
This is a sp1 bug if you are using partial classes, see the following and work-arounds: <https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361577>
235,959
<p>I have a (derived) Menu control, that displays a rather large list of items from a custom data source. I need to disable ViewState on the menu to avoid the very annoying "Can't select a disabled or unselectable menu item" when some other control causes the current selection to change on a postback.</p> <p>Unfortunately, when ViewState is disabled for the Menu, the postbacks generated <em>by</em> the menu aren't raising any events. If I enable ViewState, the OnMenuItemClick event is raised. If I disable ViewState, OnMenuItemClick is not raised. I'm perplexed.</p> <p>I need to leave ViewState off for the menu, so how can I handle postbacks from the actual menu?</p> <p>At this point I'm leaning towards using the Menu's Load event, parsing the __EVENTTARGET to see if it's the Menu, and going from there. This would technically process the postback event before it would normally but that's ok, I guess.</p> <p>Any better ideas?</p>
[ { "answer_id": 237490, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 1, "selected": true, "text": "<p>I've figured out the essence of the problem. Using Reflector we can see the important part(s) of the low level method that handles the actual postback and then raises the event:</p>\n\n<pre><code>string str = HttpUtility.HtmlDecode(eventArgument);\n...\nMenuItem item = this.Items.FindItem(str.Split(new char[] { '\\\\' }), 0);\nif (item != null)\n this.OnMenuItemClick(new MenuEventArgs(item));\n</code></pre>\n\n<p>As you can see the MenuEventArgs is handed a MenuItem. If one cannot be found in the current Items collection that matches the incoming post data, then the event is not raised. With ViewState disabled, the menu doesn't have any Items (they would have been rebuilt using ViewState). So the event won't be raised.</p>\n\n<p>To work around this, I've told the menu to build itself during Load using the not-yet-updated data (at this point it will be the same as it was at the end of the last request). This is essentially the same as rebuilding the menu from ViewState, so I don't feel bad in regards to performance, or whatever. OnMenuItemClick is then fired as expected. Lastly, during PreRender I tell the Menu to rebuild once again, so it reflects the changes that happened during the postback processing portion of the lifecycle.</p>\n\n<p>I wasted a lot of time on this, so hopefully this info can help somebody else in a similar situation.</p>\n" }, { "answer_id": 280394, "author": "AndreasKnudsen", "author_id": 36465, "author_profile": "https://Stackoverflow.com/users/36465", "pm_score": 1, "selected": false, "text": "<p>Yep, you can choose, either use viewstate to repopulate a bound control or you can databind it before events are fired (Page_Load is fine).</p>\n\n<p>I wouldn't necessarily always bind it afresh in Page_PreRender though, if nothing has changed on this postback (changes happened somewhere else on the page) then there is no reason to bind it again.</p>\n\n<p>Instead you might be able to bind only on certain events when you know it will have to change. </p>\n" }, { "answer_id": 24745490, "author": "Nicolò Beltrame", "author_id": 2713895, "author_profile": "https://Stackoverflow.com/users/2713895", "pm_score": 0, "selected": false, "text": "<p>In Page_Load rebind the control to the sitemapdata and check if IsPostBack.</p>\n\n<pre><code>if (IsPostBack) {\n Menu.DataBind();\n}\n</code></pre>\n\n<p>this work for me and reduce the viewstate.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31385/" ]
I have a (derived) Menu control, that displays a rather large list of items from a custom data source. I need to disable ViewState on the menu to avoid the very annoying "Can't select a disabled or unselectable menu item" when some other control causes the current selection to change on a postback. Unfortunately, when ViewState is disabled for the Menu, the postbacks generated *by* the menu aren't raising any events. If I enable ViewState, the OnMenuItemClick event is raised. If I disable ViewState, OnMenuItemClick is not raised. I'm perplexed. I need to leave ViewState off for the menu, so how can I handle postbacks from the actual menu? At this point I'm leaning towards using the Menu's Load event, parsing the \_\_EVENTTARGET to see if it's the Menu, and going from there. This would technically process the postback event before it would normally but that's ok, I guess. Any better ideas?
I've figured out the essence of the problem. Using Reflector we can see the important part(s) of the low level method that handles the actual postback and then raises the event: ``` string str = HttpUtility.HtmlDecode(eventArgument); ... MenuItem item = this.Items.FindItem(str.Split(new char[] { '\\' }), 0); if (item != null) this.OnMenuItemClick(new MenuEventArgs(item)); ``` As you can see the MenuEventArgs is handed a MenuItem. If one cannot be found in the current Items collection that matches the incoming post data, then the event is not raised. With ViewState disabled, the menu doesn't have any Items (they would have been rebuilt using ViewState). So the event won't be raised. To work around this, I've told the menu to build itself during Load using the not-yet-updated data (at this point it will be the same as it was at the end of the last request). This is essentially the same as rebuilding the menu from ViewState, so I don't feel bad in regards to performance, or whatever. OnMenuItemClick is then fired as expected. Lastly, during PreRender I tell the Menu to rebuild once again, so it reflects the changes that happened during the postback processing portion of the lifecycle. I wasted a lot of time on this, so hopefully this info can help somebody else in a similar situation.
235,967
<p>I am working on a web page that is using jQuery. I have an Ajax call that gets data from the server and updates a div. Inside that data there is a jQuery function, but the function is not being called after the data is loaded into the page. I have the proper js files included in the page already.</p> <p>This is what is returned from the Ajax call and placed into a div:</p> <pre><code>&lt;script type="text/javascript"&gt; $(function() { $('input').myFunction('param'); }); &lt;/script&gt; &lt;p&gt; other html &lt;/p&gt; </code></pre> <p>How do I get the returned javascript to run after the html is inserted into the page?</p> <p>(I am using Rails with the jRails plugin )</p>
[ { "answer_id": 235990, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": true, "text": "<p>If you want JavaScript tag evaluation, with html content, you should set the dataType option of the ajax call to \"html\":</p>\n\n<pre><code>$.ajax({\n type: \"GET\",\n url: \"yourPage.htm\",\n dataType: \"html\"\n});\n</code></pre>\n\n<p>Or dataType \"script\", if you want to load and execute a .js file:</p>\n\n<pre><code>$.ajax({\n type: \"GET\",\n url: \"test.js\",\n dataType: \"script\"\n});\n</code></pre>\n\n<p>more info here: <a href=\"http://docs.jquery.com/Ajax/jQuery.ajax#options\" rel=\"noreferrer\">Ajax/jQuery.ajax</a></p>\n" }, { "answer_id": 573484, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I had a similar problem where I wanted to add little jquery date pickers to a couple fields I was retrieving via ajax. here is what I did to get around it... just quick and dirty. Instead of returning this whole block from my ajax call:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n $(function() {\n $('input').myFunction('param'); \n }); \n&lt;/script&gt;\n&lt;p&gt; other html &lt;/p&gt;\n</code></pre>\n\n<p>I would return this (note the made up |x| separator)</p>\n\n<pre><code> $(function() {\n $('input').myFunction('param'); \n }); \n\n|x|\n\n&lt;p&gt; other html &lt;/p&gt;\n</code></pre>\n\n<p>Then when I received the data back via ajax, I split the return value into 2 parts: the javascript to be executed, and the html to display:</p>\n\n<pre><code> r = returnvalfromajax.split(\"|x|\"); \n document.getElementById('whatever').innerHTML = r[1]; \n eval(r[0]);\n</code></pre>\n" }, { "answer_id": 847480, "author": "ajitatif", "author_id": 104696, "author_profile": "https://Stackoverflow.com/users/104696", "pm_score": -1, "selected": false, "text": "<p>have you tried Sys.WebForms.PageRequestManager.add_endRequest method?</p>\n\n<pre><code> $(document).ready(function()\n {\n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler); \n }\n );\n function endRequestHandler(sender, args)\n {\n // whatever\n }\n</code></pre>\n" }, { "answer_id": 1143577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Well, you can use jQuery load() function: <a href=\"http://docs.jquery.com/Ajax/load#urldatacallback\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Ajax/load#urldatacallback</a>\nAs a callback you can define function which will be executed after loading new content\nexample:</p>\n\n<p>$(\"#feeds\").load(\"new_content.html\",, doSomething());</p>\n\n<p>and in new_content.html you can define function doSomething()...</p>\n" }, { "answer_id": 1833027, "author": "dc2009", "author_id": 167239, "author_profile": "https://Stackoverflow.com/users/167239", "pm_score": -1, "selected": false, "text": "<p>for ajax.net the <code>endRequestHandler(sender, args)</code> solution works fine though</p>\n" }, { "answer_id": 7677801, "author": "JimFing", "author_id": 700956, "author_profile": "https://Stackoverflow.com/users/700956", "pm_score": 1, "selected": false, "text": "<p>Changing </p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n...\n&lt;/script&gt;\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>&lt;script&gt;\n...\n&lt;/script&gt;\n</code></pre>\n\n<p>Fixed the issue for me.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
I am working on a web page that is using jQuery. I have an Ajax call that gets data from the server and updates a div. Inside that data there is a jQuery function, but the function is not being called after the data is loaded into the page. I have the proper js files included in the page already. This is what is returned from the Ajax call and placed into a div: ``` <script type="text/javascript"> $(function() { $('input').myFunction('param'); }); </script> <p> other html </p> ``` How do I get the returned javascript to run after the html is inserted into the page? (I am using Rails with the jRails plugin )
If you want JavaScript tag evaluation, with html content, you should set the dataType option of the ajax call to "html": ``` $.ajax({ type: "GET", url: "yourPage.htm", dataType: "html" }); ``` Or dataType "script", if you want to load and execute a .js file: ``` $.ajax({ type: "GET", url: "test.js", dataType: "script" }); ``` more info here: [Ajax/jQuery.ajax](http://docs.jquery.com/Ajax/jQuery.ajax#options)
235,972
<p>I have a windows application running at the backend. I have functions in this applications mapped to hot keys. Like if I put a message box into this function and give hot key as <kbd>Alt</kbd>+<kbd>Ctrl</kbd>+<kbd>D</kbd>. then on pressing <kbd>Alt</kbd>, <kbd>Ctrl</kbd> and <kbd>D</kbd> together the message box comes up. My application is working fine till this point. </p> <p>Now I want to write a code inside this function so that when I am using another application like notepad, I select a particular line of text and press the hot key <kbd>Alt</kbd> + <kbd>Ctrl</kbd> + <kbd>D</kbd> it is supposed to copy the selected text append it with "_copied" and paste it back to notepad. </p> <p>Anyone who has tried a similar application please help me with your valuable inputs.</p>
[ { "answer_id": 236175, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 1, "selected": false, "text": "<p>Use the <a href=\"http://msdn.microsoft.com/library/system.windows.forms.clipboard.aspx\" rel=\"nofollow noreferrer\">Clipboard</a> class to copy the contents to the clipboard, then paste in the notepad.</p>\n\n<p>You could also write the contents to a text file and open it with notepad by running the notepad.exe application with the text file's path as a command line parameter.</p>\n" }, { "answer_id": 236617, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>I think you can use <a href=\"http://msdn.microsoft.com/en-us/library/ms646310.aspx\" rel=\"nofollow noreferrer\" title=\"SendInput\">SendInput</a> function to send the text to the target window or just the command to paste it if you have put it in clipboard before.</p>\n" }, { "answer_id": 273163, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 5, "selected": true, "text": "<p>Your question has two answers</p>\n\n<h2>How can my app set a global hotkey</h2>\n\n<p>You have to call an API funcion called RegisterHotKey</p>\n\n<pre><code>BOOL RegisterHotKey(\n HWND hWnd, // window to receive hot-key notification\n int id, // identifier of hot key\n UINT fsModifiers, // key-modifier flags\n UINT vk // virtual-key code\n);\n</code></pre>\n\n<p>More info here: <a href=\"http://www.codeproject.com/KB/system/nishhotkeys01.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/system/nishhotkeys01.aspx</a></p>\n\n<h2>How to get the selected text from the foreground window</h2>\n\n<p>Easiest way is to send crl-C to the window and then capture the clipboard content.</p>\n\n<pre><code>[DllImport(\"User32.dll\")] \nprivate static extern bool SetForegroundWindow(IntPtr hWnd);\n\n[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\nstatic public extern IntPtr GetForegroundWindow();\n\n[DllImport(\"user32.dll\")]\nstatic extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);\n\n\n.....\n\nprivate void SendCtrlC(IntPtr hWnd)\n {\n uint KEYEVENTF_KEYUP = 2;\n byte VK_CONTROL = 0x11;\n SetForegroundWindow(hWnd);\n keybd_event(VK_CONTROL,0,0,0);\n keybd_event (0x43, 0, 0, 0 ); //Send the C key (43 is \"C\")\n keybd_event (0x43, 0, KEYEVENTF_KEYUP, 0);\n keybd_event (VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);// 'Left Control Up\n\n}\n</code></pre>\n\n<p>Disclaimer: Code by Marcus Peters from here: <a href=\"http://bytes.com/forum/post1029553-5.html\" rel=\"noreferrer\">http://bytes.com/forum/post1029553-5.html</a><br>\nPosted here for your convenience.</p>\n" }, { "answer_id": 59952641, "author": "DurkoMatko", "author_id": 3356517, "author_profile": "https://Stackoverflow.com/users/3356517", "pm_score": 2, "selected": false, "text": "<p><h2>UPDATE 2020</h2><h3>How to get the selected text from the foreground window</h3></p>\n\n<p>No idea for how long has this been possible but instead of fighting with Win32 programming (mostly <code>user32.dll</code> and various Windows messages like <code>WM_GETTEXT, WM_COPY</code> and various <code>SendMessage(handle, WM_GETTEXT, maxLength, sb)</code> calls) which is advised in most of SO threads on this topic, <strong>I easily managed to access selected text in any window in my C# code followingly</strong>:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// programatically copy selected text into clipboard\nawait System.Threading.Tasks.Task.Factory.StartNew(fetchSelectionToClipboard);\n\n// access clipboard which now contains selected text in foreground window (active application)\nawait System.Threading.Tasks.Task.Factory.StartNew(useClipBoardValue);\n</code></pre>\n\n<p>Here the methods being called:</p>\n\n<pre><code>static void fetchSelectionToClipboard()\n{\n Thread.Sleep(400);\n SendKeys.SendWait(\"^c\"); // magic line which copies selected text to clipboard\n Thread.Sleep(400);\n}\n\n// depends on the type of your app, you sometimes need to access clipboard from a Single Thread Appartment model..therefore I'm creating a new thread here\nstatic void useClipBoardValue()\n{\n Exception threadEx = null;\n // Single Thread Apartment model\n Thread staThread = new Thread(\n delegate ()\n {\n try\n {\n Console.WriteLine(Clipboard.GetText());\n }\n catch (Exception ex)\n {\n threadEx = ex;\n }\n });\n staThread.SetApartmentState(ApartmentState.STA);\n staThread.Start();\n staThread.Join();\n}\n</code></pre>\n" }, { "answer_id": 74170233, "author": "obviliontsk", "author_id": 18531761, "author_profile": "https://Stackoverflow.com/users/18531761", "pm_score": 0, "selected": false, "text": "<p>In addition to other comments. When you're using global hotkeys to send keystrokes you NEED to set delay (or to use more complex logic) as in DurkoMatko's example, before sending keystrokes or your pressed keys will overlap with sended keystrokes, also you may need to bring app window in focus with SetForegroundWindow() method, you'll need handle Process.MainWindowHandle from process or from FindWindow() method, depends on your use-case.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/desktop/winforms/input-keyboard/how-to-simulate-events?view=netdesktop-6.0\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/desktop/winforms/input-keyboard/how-to-simulate-events?view=netdesktop-6.0</a></p>\n<pre><code>[DllImport(&quot;USER32.DLL&quot;, CharSet = CharSet.Unicode)]\npublic static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n[DllImport(&quot;USER32.DLL&quot;)]\npublic static extern bool SetForegroundWindow(IntPtr hWnd);\n</code></pre>\n<p>Example:</p>\n<pre><code>Clipboard.Clear();\nawait Task.Delay(300);\nSendKeys.SendWait(&quot;^{c}&quot;);\nif (!Clipboard.ContainsText()) return;\nvar clipboard = Clipboard.GetText();\n... // modifying logic here\nClipboard.SetText(clipboard)\nSendKeys.SendWait(&quot;^{v}&quot;);\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
I have a windows application running at the backend. I have functions in this applications mapped to hot keys. Like if I put a message box into this function and give hot key as `Alt`+`Ctrl`+`D`. then on pressing `Alt`, `Ctrl` and `D` together the message box comes up. My application is working fine till this point. Now I want to write a code inside this function so that when I am using another application like notepad, I select a particular line of text and press the hot key `Alt` + `Ctrl` + `D` it is supposed to copy the selected text append it with "\_copied" and paste it back to notepad. Anyone who has tried a similar application please help me with your valuable inputs.
Your question has two answers How can my app set a global hotkey ---------------------------------- You have to call an API funcion called RegisterHotKey ``` BOOL RegisterHotKey( HWND hWnd, // window to receive hot-key notification int id, // identifier of hot key UINT fsModifiers, // key-modifier flags UINT vk // virtual-key code ); ``` More info here: <http://www.codeproject.com/KB/system/nishhotkeys01.aspx> How to get the selected text from the foreground window ------------------------------------------------------- Easiest way is to send crl-C to the window and then capture the clipboard content. ``` [DllImport("User32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo); ..... private void SendCtrlC(IntPtr hWnd) { uint KEYEVENTF_KEYUP = 2; byte VK_CONTROL = 0x11; SetForegroundWindow(hWnd); keybd_event(VK_CONTROL,0,0,0); keybd_event (0x43, 0, 0, 0 ); //Send the C key (43 is "C") keybd_event (0x43, 0, KEYEVENTF_KEYUP, 0); keybd_event (VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);// 'Left Control Up } ``` Disclaimer: Code by Marcus Peters from here: <http://bytes.com/forum/post1029553-5.html> Posted here for your convenience.
235,982
<p>The most favorite feature of StackOverflow for me is that it can automatically detect code in post and set appropriate color to the code.</p> <p>I'm wondering how the color is set. When I do a <kbd>Ctrl</kbd>+<kbd>F5</kbd> on a page, the code seems first be black text, then change to be colorful. Is it done by jQuery?</p>
[ { "answer_id": 235987, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": false, "text": "<p>From <a href=\"https://stackoverflow.fogbugz.com/default.asp?W12621\" rel=\"noreferrer\">Stack Overflow Podcast #11</a>:</p>\n<blockquote>\n<p><strong>Atwood:</strong> It is. Okay, so that comes from, that's a project some Google engineer, I think, wrote it--it's called &quot;Prettify.&quot; And it's a little interesting in that it actually infers all the syntax highlighting, which sounds like it couldn't possibly work--it sounds actually insane, if you think about it. But it actually kind of works. Now, he only supports it for, there's certain dialects that just don't really work well with it, but for all the dialects that sort of, you'd find on Google. I think it comes from Google's Google Code. It's the actual code, it's the actual JavaScript which is on Google Code that highlights that the code that comes back when you're hosting projects on Google Code. And you, and you, um, 'cause I think they use Subversion so you can actually click through...</p>\n<p><strong>Spolsky:</strong> How do they know, how do they even know what language you're writing in? And therefore, what a comment is and...</p>\n<p><strong>Atwood:</strong> I don't know. It's crazy. It's prettify.js, so if anyone's interested in looking at this, just do a web search for &quot;prettify.js,&quot; and you'll find it.</p>\n</blockquote>\n<p>And here's where you can find prettify.js: <a href=\"http://code.google.com/p/google-code-prettify/\" rel=\"noreferrer\">http://code.google.com/p/google-code-prettify/</a></p>\n" }, { "answer_id": 236062, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 5, "selected": true, "text": "<p>In reply to..</p>\n\n<blockquote>\n <p>Spolsky: How do they know, how do they even know what language you're writing in?</p>\n</blockquote>\n\n<p>It doesn't. The highlighter is very dumb, but manages to gets away with it because most programming languages are so similar. Nearly everything uses syntax close-enough to..</p>\n\n<pre><code>AFunction(\"a string\")\n1 + 4 # &lt;- numbers\n # /\\ a comment\n // also a comment..\n</code></pre>\n\n<p>..that most stuff highlights properly. The above isn't an actuall programming language, but it highlights perfectly.</p>\n\n<p>There are exceptions, for example, it can sometimes treat a <code>/</code> as the start of a regex (as in Perl/Ruby). when it is not:</p>\n\n<pre><code>this [^\\s&gt;/] # is highlighted as a regex, not a comment\n</code></pre>\n\n<p>..but these are fairly rare, and it does a good job of working out most stuff, like..</p>\n\n<pre><code>/*\nthis is a multi-line comment\n\"with a string\" =~ /and a regex/\n*/\nbut =~ /this is a regex with a [/*] multiline comment\nmarkers in it! */\n</code></pre>\n" }, { "answer_id": 236450, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>As said by dbr, it does a dummy highlight of most common constructs of languages. Which doesn't work well with some exotic syntaxes. I wonder if we can do code sections without highlighting, BTW.</p>\n\n<pre><code>For id = 1 To 10 Do\n CallSomething() // It likes CamelCase identifiers...\nEnd\n\nfor id = 1 to 10 do # Also highlight some common keywords...\n if id % 2 then call_something(); x++; end\nend\n\n'str' \"str\" 12 + 15.6 * -7e+9 /* Some common constant forms */\n=/regex/ ~/regex/ +/RE/ !/regexpr/ but not /[^regex]/ (no operator before it)\n\n(* Some comment conventions are overlooked... *)\n-- Lua's (and some other languages')\n; So are these comments...\n' And these (Basic)\n</code></pre>\n\n<p>Works well enough for common code to make illusion, and better than loading dozen of syntaxes in the browser.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/235982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
The most favorite feature of StackOverflow for me is that it can automatically detect code in post and set appropriate color to the code. I'm wondering how the color is set. When I do a `Ctrl`+`F5` on a page, the code seems first be black text, then change to be colorful. Is it done by jQuery?
In reply to.. > > Spolsky: How do they know, how do they even know what language you're writing in? > > > It doesn't. The highlighter is very dumb, but manages to gets away with it because most programming languages are so similar. Nearly everything uses syntax close-enough to.. ``` AFunction("a string") 1 + 4 # <- numbers # /\ a comment // also a comment.. ``` ..that most stuff highlights properly. The above isn't an actuall programming language, but it highlights perfectly. There are exceptions, for example, it can sometimes treat a `/` as the start of a regex (as in Perl/Ruby). when it is not: ``` this [^\s>/] # is highlighted as a regex, not a comment ``` ..but these are fairly rare, and it does a good job of working out most stuff, like.. ``` /* this is a multi-line comment "with a string" =~ /and a regex/ */ but =~ /this is a regex with a [/*] multiline comment markers in it! */ ```
236,031
<p>How can I implement a <code>diff</code> function, such as Stack Overflow's question revision history?</p>
[ { "answer_id": 236034, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "<p>You have here a <a href=\"http://ejohn.org/projects/javascript-diff-algorithm/\" rel=\"nofollow noreferrer\">javascript example</a> of the implementation of a diff algorithm.</p>\n\n<p>Based on:</p>\n\n<p><a href=\"http://www.scribd.com/doc/1461552/A-technique-for-isolating-differences-between-files\" rel=\"nofollow noreferrer\">P. Heckel, A technique for isolating differences between files</a>\nComm. ACM, 21, (4), 264--268 (1978).</p>\n\n<p>The implementation, itself, has two functions, one of which is recommended for use:</p>\n\n<pre><code>diffString( String oldFile, String newFile )\n</code></pre>\n\n<p>This method takes two strings and calculates the differences in each. The final result is the 'newFile' marked up with HTML (to signify both deletions from the oldFile and additions to the newFile). </p>\n" }, { "answer_id": 236041, "author": "Vhaerun", "author_id": 11234, "author_profile": "https://Stackoverflow.com/users/11234", "pm_score": 0, "selected": false, "text": "<p>I guess the only way would be to compare each character forming the 2 strings . Something like this :</p>\n\n<pre><code>\nvoid diff(String first,String second) {\n int biggest = (first.length() > second.length()) ? first.length() : second.length();\n for(int i = 0;i &lt biggest;i++) {\n //compare each char from the longest string with each char from the shorter\n // do something with them if they're not equal\n }\n}\n</code></pre>\n\n<p>This is just a sketch of how I would do it . Everything depends on what you want to do with the data .</p>\n" }, { "answer_id": 236059, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>I would find the code for the FreeBSD diff utility and use that as the baseline. There's no point in re-inventing wheels when the licence allows for this sort of copying.</p>\n" }, { "answer_id": 236067, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 0, "selected": false, "text": "<p>If what you want is revision history, don't reinvent the wheel starting at diff. Just throw everything into version control and use its diff and logging facilities. For simple, linear history something as simple as <a href=\"http://www.gnu.org/software/rcs/\" rel=\"nofollow noreferrer\">RCS</a> will do. Or you can throw the latest cannon at it and use <a href=\"http://git.or.cz/\" rel=\"nofollow noreferrer\">git</a>.</p>\n\n<p>Most diff utilities do a line-by-line diff. Stack overflow does a word-by-word diff. For that something like <a href=\"http://www.gnu.org/software/wdiff/\" rel=\"nofollow noreferrer\">wdiff</a> is necessary. Most version control systems let you plug in the diff utility. Out of the box, <code>git diff --color-words</code> comes remarkably close to what is done here. With a little fiddling with the settings you can probably get it to spit out something you can then make into a pretty web page.</p>\n" }, { "answer_id": 236434, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>Most algorithms are based on LCS: <a href=\"http://en.wikipedia.org/wiki/Longest_common_subsequence_problem\" rel=\"nofollow noreferrer\" title=\"Longest common subsequence problem - Wikipedia, the free encyclopedia\">Longest common subsequence</a>. It isn't obvious to implement it in an efficient way. You will probably find various implementations on the Net, for various languages.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20191/" ]
How can I implement a `diff` function, such as Stack Overflow's question revision history?
You have here a [javascript example](http://ejohn.org/projects/javascript-diff-algorithm/) of the implementation of a diff algorithm. Based on: [P. Heckel, A technique for isolating differences between files](http://www.scribd.com/doc/1461552/A-technique-for-isolating-differences-between-files) Comm. ACM, 21, (4), 264--268 (1978). The implementation, itself, has two functions, one of which is recommended for use: ``` diffString( String oldFile, String newFile ) ``` This method takes two strings and calculates the differences in each. The final result is the 'newFile' marked up with HTML (to signify both deletions from the oldFile and additions to the newFile).
236,035
<p>I've been reading many a tutorial/article on unmanaged DLLs in C++. For the life of me, however, I cannot seem to grasp the concept. I'm easily confused by the seeming disagreement about whether it needs a header file, how to export it, whether I need a .lib file and what have you.</p> <p>So, let's assume I have just a function like so:</p> <pre><code>public int calculateSquare(int num) { return num*num; } </code></pre> <p>Ignoring the actual code, what do I require to make this simple function, by itself, into a DLL which I can then call? Do I just add __dllexport or whatever it is to the first line or do I require a header? I am perplexed by all of this.</p>
[ { "answer_id": 236052, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 5, "selected": true, "text": "<p>I cannot stress this enough, the C++ compiler does not see header files, after the preprocessor is done, there's just one big source file ( also called the compilation unit ). So strictly you don't need a header to export this function from a dll.\nWhat you do need is some form of conditional compilation to export the function in the dll that you are compiling and to import it in the client code.</p>\n\n<p>Typically this is done with a combination of macros and header files. You create a macro called MYIMPORTEXPORT and through the use of macro conditional statements you make it work like __declspec ( dllexport ) in the dll, and __declspec( dllimport ) in the client code.</p>\n\n<p>in file MYIMPORTEXPORT.h</p>\n\n<pre><code>#ifdef SOME_CONDITION\n#define MYIMPORTEXPORT __declspec( dllexport )\n#else\n#define MYIMPORTEXPORT __declspec( dllimport )\n#endif\n</code></pre>\n\n<p>in file MyHeader.h</p>\n\n<pre><code>#include &lt;MyImportExport.h&gt;\n\nMYIMPORTEXPORT public int calculateSquare(int num)\n{\n return num*num;\n}\n</code></pre>\n\n<p>in dll .cpp file</p>\n\n<pre><code>#define SOME_CONDITION\n\n#include &lt;MyHeader.h&gt;\n</code></pre>\n\n<p>in client code .cpp file</p>\n\n<pre><code>#include &lt;MyHeader.h&gt;\n</code></pre>\n\n<p>Of course you also need to signal to the linker that you are building a dll with the <a href=\"http://msdn.microsoft.com/en-us/library/y0zzbyt4(VS.80).aspx\" rel=\"nofollow noreferrer\">/DLL option</a>.</p>\n\n<p>The build process will also make a .lib file, this is a static lib - called the stub in this case - which the client code needs to link to as if it were linking to a real static lib. Automagically, the dll will be loaded when the client code is run. Of course the dll needs to be found by the OS through its lookup mechanism, which means you cannot put the dll just anywhere, but in a specific location. <a href=\"http://msdn.microsoft.com/en-us/library/ms682586.aspx\" rel=\"nofollow noreferrer\">Here</a> is more on that.</p>\n\n<p>A very handy tool to see whether you exported the correct function from the dll, and whether the client code is correctly importing is <a href=\"http://support.microsoft.com/kb/177429\" rel=\"nofollow noreferrer\">dumpbin</a>. Run it with /EXPORTS and /IMPORTS respectively.</p>\n" }, { "answer_id": 236053, "author": "Roman Plášil", "author_id": 16590, "author_profile": "https://Stackoverflow.com/users/16590", "pm_score": 0, "selected": false, "text": "<p>You need to export the function using either<code>__declspec( dllexport )</code> or adding the function to a module definition file (.def). Then compile tho project as a DLL. </p>\n\n<p>On the client side, you have two options. Either use an import library (.lib) which is generated when compiling the DLL. Simply linking with your client project with this library will give you access to the functions exported from the DLL. And you need a header file, because the compiler needs to know the signature of your function - that it returns int and takes an int. To recap, you need to link with an import library (.lib) and a header file which contains the header of your function.</p>\n\n<p>Another way is to load the DLL dynamically using <code>WinAPI</code> call <code>LoadLibrary</code> and then <code>GetProcAddress</code> to obtain a pointer to the function. The pointer to function must have the correct type, so that the compiler can give it it the correct parameters and the correct calling convention is used.</p>\n" }, { "answer_id": 236126, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "<p>QBziZ' answer is right enough. See <a href=\"https://stackoverflow.com/questions/236035/unmanaged-dlls-in-c#236052\">Unmanaged DLLs in C++</a></p>\n<p>To complete it: <em>In C++, if you need to use a symbol, you must tell the compiler it exists, and often, its prototype</em>.</p>\n<p>In other languages, the compiler will just explore the library on its own, and find the symbol, <em>et voilà</em>.</p>\n<p>In C++, you must tell the compiler.</p>\n<h2>See a C/C++ header as a book table of contents</h2>\n<p>The best way is to put in some common place the needed code. The &quot;interface&quot;, if you want. This is usually done in an header file, called header because this is usually not an independent source file. The header is only a file whose aim is to be included (i.e. copy/pasted by the preprocessor) into true source files.</p>\n<p>In substance, it seems you have to declare twice a symbol (function, class, whatever). Which is almost an heresy when compared to other languages.</p>\n<p>You should see it as a book, with a summary table, or an index. In the table, you have all the chapters. In the text, you have the chapters and their content.</p>\n<p>And sometimes, you're just happy you have the chapter list.</p>\n<p>In C++, this is the header.</p>\n<h2>What about the DLL?</h2>\n<p>So, back to the DLL problem: The aim of a DLL is to export symbols that your code will use.</p>\n<p>So, in a C++ way, you must both export the code at compilation (i.e., in Windows, use the __declspec, for example) and &quot;publish&quot; a table of what is exported (i.e. have &quot;public&quot; headers containing the exported declarations).</p>\n" }, { "answer_id": 236167, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 1, "selected": false, "text": "<p>Checklist for exporting functions:</p>\n\n<ul>\n<li>Is the calling convention suitable for the caller? (this determines how parameters and results are passed, and who is responsible for cleaning up the stack). You should state your calling convention explicitely. </li>\n<li>Under which name the symbol will be exported? C++ usually needs to decorate (\"mangle\") the names of symbols, e.g. to distinguish between different overloads. </li>\n<li>Tell the linker to make the function visible as DLL Export</li>\n</ul>\n\n<p>On MSVC:</p>\n\n<ul>\n<li><code>__stdcall</code> (which is pascal calling convention) is the typical calling convention for exported symbols - supported by most clients I guess.</li>\n<li>extern \"C\" allows you to export the symbol C-style without name mangling</li>\n<li>use <code>__declspec(dllexport)</code> to mark a symbol to be exported, or link a separate .def file where the symbols to be exported are listed. With a .def file you can also export by ordinal only (not by name), and change the name of the symbol that is exported.</li>\n</ul>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31389/" ]
I've been reading many a tutorial/article on unmanaged DLLs in C++. For the life of me, however, I cannot seem to grasp the concept. I'm easily confused by the seeming disagreement about whether it needs a header file, how to export it, whether I need a .lib file and what have you. So, let's assume I have just a function like so: ``` public int calculateSquare(int num) { return num*num; } ``` Ignoring the actual code, what do I require to make this simple function, by itself, into a DLL which I can then call? Do I just add \_\_dllexport or whatever it is to the first line or do I require a header? I am perplexed by all of this.
I cannot stress this enough, the C++ compiler does not see header files, after the preprocessor is done, there's just one big source file ( also called the compilation unit ). So strictly you don't need a header to export this function from a dll. What you do need is some form of conditional compilation to export the function in the dll that you are compiling and to import it in the client code. Typically this is done with a combination of macros and header files. You create a macro called MYIMPORTEXPORT and through the use of macro conditional statements you make it work like \_\_declspec ( dllexport ) in the dll, and \_\_declspec( dllimport ) in the client code. in file MYIMPORTEXPORT.h ``` #ifdef SOME_CONDITION #define MYIMPORTEXPORT __declspec( dllexport ) #else #define MYIMPORTEXPORT __declspec( dllimport ) #endif ``` in file MyHeader.h ``` #include <MyImportExport.h> MYIMPORTEXPORT public int calculateSquare(int num) { return num*num; } ``` in dll .cpp file ``` #define SOME_CONDITION #include <MyHeader.h> ``` in client code .cpp file ``` #include <MyHeader.h> ``` Of course you also need to signal to the linker that you are building a dll with the [/DLL option](http://msdn.microsoft.com/en-us/library/y0zzbyt4(VS.80).aspx). The build process will also make a .lib file, this is a static lib - called the stub in this case - which the client code needs to link to as if it were linking to a real static lib. Automagically, the dll will be loaded when the client code is run. Of course the dll needs to be found by the OS through its lookup mechanism, which means you cannot put the dll just anywhere, but in a specific location. [Here](http://msdn.microsoft.com/en-us/library/ms682586.aspx) is more on that. A very handy tool to see whether you exported the correct function from the dll, and whether the client code is correctly importing is [dumpbin](http://support.microsoft.com/kb/177429). Run it with /EXPORTS and /IMPORTS respectively.
236,038
<p>I am facing this peculiar problem. My webapp, works fine on my localhost. Its a JSP/Struts-Tomcat-MySQL app. However, when I host it on hostjava.net (shared tomcat), it is unable to connect to the database.</p> <p>After some debugging, I have identified the problem, to be with JNDI lookup for datasource. If you want, you can take a look at the log at <a href="http://rohitesh.hostjava.net/MapsDummyLog.htm" rel="nofollow noreferrer">http://rohitesh.hostjava.net/MapsDummyLog.htm</a></p> <p>Some details on the context information location : /META-INF/context.xml contains :</p> <pre><code>&lt;Context path="" docBase="" debug="5" reloadable="true" crossContext="true" override="true"&gt; &lt;Resource name="jdbc/ConnectionPooling" auth="Container" type="javax.sql.DataSource" maxActive="10" maxIdle="5" username="[username]" password="[password]" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/[db name]?autoReconnect=true" /&gt; &lt;/Context&gt; </code></pre> <p>Can anyone help me find out, where am going wrong, please?</p> <p>Cheers, Rohitesh.</p>
[ { "answer_id": 236049, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>\"java.lang.NullPointerException \n at com.DAO.UserDAO.userLogin(UserDAO.java:109) \n at com.Actions.UserAction.execute(UserAction.java:66) \n at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) \n at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) \n at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) \n\"</p>\n\n<p>This tells me that something is NOT being initialized properly. on what object are you invoking in line 109 of UserDAO.java ? </p>\n\n<p>\"10/25/08 (2:08 AM) ajp-127.0.0.1-8015-1 ERROR UserDAO.java:104 Cannot create JDBC driver of class '' for connect URL 'null'<br>\n10/25/08 (2:08 AM) ajp-127.0.0.1-8015-1 ERROR UserDAO.java:105 org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'\n\"</p>\n\n<p>Did you check the URL for the DB. it appears that the URL is invalid or NULL. Can you give a manual value for the JDBC connection URL ?</p>\n" }, { "answer_id": 236482, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 2, "selected": false, "text": "<p>Shouldn't this:</p>\n\n<pre><code>url=\"jdbc:mysql://localhost/[db name]?autoReconnect=true\"\n</code></pre>\n\n<p>really point at the name of the server on which the database is hosted? On th remote host the database server may not be the same machine as the tomcat instance. I would think that you have to say </p>\n\n<p>url=\"jdbc:mysql://[Server_Name]/[db name]?autoReconnect=true\"</p>\n" }, { "answer_id": 236540, "author": "RD.", "author_id": 8056, "author_profile": "https://Stackoverflow.com/users/8056", "pm_score": 0, "selected": false, "text": "<p>The peculiar thing is, that another part of the same application, accesses the database, with a hardcoded url (using DriverManager, and <strong>NOT</strong> datasource from the JNDI lookup), and that works just fine (check out the first two lines in the log, and the next couple of lines with cuisine names, which are read from the database). So, it is certain, that the database is also on the same server.</p>\n\n<p>Cheers,\nR</p>\n" }, { "answer_id": 237055, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "<ul>\n<li>is the driver available? Try Class.forName(\"com.mysql.jdbc.Driver\"); - and it can't be located in your webapps WEB-INF/lib because you are asking for the container (tomcat) to instantiate it for you: It needs to be in the servers classpath</li>\n<li>Are you running Tomcat 5.5.x or 6.0.x? On 5.0.x the context.xml syntax, especially resource definition, has been different: Way more xml tags instead of the nicer and simpler attributes since 5.5.</li>\n</ul>\n" }, { "answer_id": 237437, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 2, "selected": false, "text": "<p>Here goes my guess:</p>\n\n<p>You said it's a shared hosting. Then shouldn't </p>\n\n<pre><code>&lt;Context path=\"\" \n</code></pre>\n\n<p>contain the context path of your particular application?</p>\n\n<p><a href=\"http://tomcat.apache.org/tomcat-5.5-doc/config/context.html\" rel=\"nofollow noreferrer\">http://tomcat.apache.org/tomcat-5.5-doc/config/context.html</a>\n<em>The context path of this web application, which is matched against the beginning of each request URI to select the appropriate web application for processing. All of the context paths within a particular Host must be unique. If you specify a context path of an empty string (\"\"), you are defining the default web application for this Host, which will process all requests not assigned to other Contexts.</em></p>\n\n<p>So you context is invalid and, I presume, simply invisible (that's why null driver and null url).</p>\n\n<p>It would work on your local as \"\" is a shared context for all apps deployed, including yours.</p>\n" }, { "answer_id": 237982, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 1, "selected": false, "text": "<p>How about this restriction:</p>\n\n<p><a href=\"http://wiki.hostjava.net/index.php/HostJava.net_FAQ\" rel=\"nofollow noreferrer\">http://wiki.hostjava.net/index.php/HostJava.net_FAQ</a>\n<em>With Shared Tomcat access to server.xml file is restricted. Only support staff can add Realm (for example JDBC Realm)to server.xml file.</em> </p>\n\n<p>Looks like you need to ask support to add your datasource.</p>\n" }, { "answer_id": 238426, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 1, "selected": false, "text": "<p>Rohitesh,</p>\n\n<p>Per Vladimir's answer and comments, you may want to consider requesting the server context (server.xml, or the more globally scoped context.xml) be updated.</p>\n\n<p>If nothing else, this is, in my opinion, a best practice. While Tomcat does allow you to define the context (including JNDI resources) from within the web application itself, the only place you should use this feature is in a developer's local test server. It makes your web application more portable, as it allows to change the configuration of your external resources (in this case, the database, but it could be a mail server, or content server, rules engine etc) independently of your application.</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 238431, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 0, "selected": false, "text": "<p>Another note:\nDo you have access to any other log files besides the one you posted? If you have access to the server logs/catalina.out file, it may show you the exact problem Tomcat is having setting up the data source (this would be right when you start up Tomcat).</p>\n" }, { "answer_id": 241084, "author": "RD.", "author_id": 8056, "author_profile": "https://Stackoverflow.com/users/8056", "pm_score": 0, "selected": false, "text": "<p>Sorry everyone. It was a problem of miscommunication between me and the Support team of the hosting facility. There was a clash of configs. They had set some old settings in server.xml. As that takes precedence over any other context information, I was facing those issues. Now it is taken care of.</p>\n\n<p>But I still feel, that to allow people on a shared configuration, to have their context information in META-INF/context.xml file, is a better option. That way, they have more control over it.</p>\n\n<p>But I Thank everyone, who took the time out, to respond. I learnt a lot from you. Thank you again.</p>\n\n<p>Cheers,\nR</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8056/" ]
I am facing this peculiar problem. My webapp, works fine on my localhost. Its a JSP/Struts-Tomcat-MySQL app. However, when I host it on hostjava.net (shared tomcat), it is unable to connect to the database. After some debugging, I have identified the problem, to be with JNDI lookup for datasource. If you want, you can take a look at the log at <http://rohitesh.hostjava.net/MapsDummyLog.htm> Some details on the context information location : /META-INF/context.xml contains : ``` <Context path="" docBase="" debug="5" reloadable="true" crossContext="true" override="true"> <Resource name="jdbc/ConnectionPooling" auth="Container" type="javax.sql.DataSource" maxActive="10" maxIdle="5" username="[username]" password="[password]" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/[db name]?autoReconnect=true" /> </Context> ``` Can anyone help me find out, where am going wrong, please? Cheers, Rohitesh.
Shouldn't this: ``` url="jdbc:mysql://localhost/[db name]?autoReconnect=true" ``` really point at the name of the server on which the database is hosted? On th remote host the database server may not be the same machine as the tomcat instance. I would think that you have to say url="jdbc:mysql://[Server\_Name]/[db name]?autoReconnect=true"
236,070
<p>How can I check the version of my script against an online file to see if it's the latest version?</p> <p><em>For clarification, I'm talking about a script I wrote, not the version of PHP. I'd like to incorporate a way for the end user to tell when I've updated the script.</em></p>
[ { "answer_id": 236098, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 0, "selected": false, "text": "<p>Have an RSS or Atom <strong>feed</strong> with update info. Wordpress does something similar. Then you can locally save information which updates have been shown to the user etc.</p>\n\n<p>For even simpler solution, have a file on project website that would contain just the version number. Then compare it with a version number stored in your program, probably within a constant.</p>\n" }, { "answer_id": 236100, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>Per comments on <a href=\"https://stackoverflow.com/questions/236070/php-version-checking#236084\">this answer</a></p>\n\n<pre><code>// Substitue path to script with the version information in place of __FILE__ if necessary\n$script = file_get_contents(__FILE__);\n$version = SOME_SENSIBLE_DEFAULT_IN_CASE_OF_FAILURE;\nif(preg_match('/&lt;!-- Script version (\\d*(\\.\\d+)*) --&gt;/', $script, $version_match)) {\n $version = $version_match[1];\n}\n</code></pre>\n" }, { "answer_id": 236115, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 5, "selected": true, "text": "<p>To specify the second (more simple) solution <a href=\"https://stackoverflow.com/questions/236070/php-version-checking#236098\">phjr</a> proposed:</p>\n\n<p>Have a file <code>version.txt</code> on your own public server and include the following function into your deployed project/script:</p>\n\n<pre><code>define('REMOTE_VERSION', 'http://your.public.server/version.txt');\n\n// this is the version of the deployed script\ndefine('VERSION', '1.0.1');\n\nfunction isUpToDate()\n{\n $remoteVersion=trim(file_get_contents(REMOTE_VERSION));\n return version_compare(VERSION, $remoteVersion, 'ge');\n}\n</code></pre>\n\n<p><code>version.txt</code> should just contain the most recent version number, e.g.:</p>\n\n<pre><code>1.0.2\n</code></pre>\n" }, { "answer_id": 4807515, "author": "Nick Winstanley", "author_id": 590983, "author_profile": "https://Stackoverflow.com/users/590983", "pm_score": 2, "selected": false, "text": "<pre><code>define('REMOTE_VERSION', 'http://your.public.server/version.txt');\ndefine('VERSION', '1.0.1');\n$script = file_get_contents(REMOTE_VERSION);\n$version = VERSION;\nif($version == $script) {\n echo \"&lt;div class=success&gt; \n&lt;p&gt;You have the latest version!&lt;/p&gt; \n&lt;/div&gt;\";\n} else {\n echo \"&lt;div class=error&gt; \n&lt;p&gt;There is a update available!&lt;/p&gt; \n&lt;/div&gt;\";\n}\n</code></pre>\n" }, { "answer_id": 69425740, "author": "Mukesh Yadav", "author_id": 11812099, "author_profile": "https://Stackoverflow.com/users/11812099", "pm_score": -1, "selected": false, "text": "<p>Change</p>\n<pre><code>if($version == $script) \n</code></pre>\n<p>to</p>\n<pre><code>if($version &gt;= $script)` \n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
How can I check the version of my script against an online file to see if it's the latest version? *For clarification, I'm talking about a script I wrote, not the version of PHP. I'd like to incorporate a way for the end user to tell when I've updated the script.*
To specify the second (more simple) solution [phjr](https://stackoverflow.com/questions/236070/php-version-checking#236098) proposed: Have a file `version.txt` on your own public server and include the following function into your deployed project/script: ``` define('REMOTE_VERSION', 'http://your.public.server/version.txt'); // this is the version of the deployed script define('VERSION', '1.0.1'); function isUpToDate() { $remoteVersion=trim(file_get_contents(REMOTE_VERSION)); return version_compare(VERSION, $remoteVersion, 'ge'); } ``` `version.txt` should just contain the most recent version number, e.g.: ``` 1.0.2 ```
236,073
<p>Why do some sites (or advertisers that give clients javascript code) employ a technique of splitting the <code>&lt;script&gt;</code> and/or <code>&lt;/script&gt;</code> tags up within <code>document.write()</code> calls?</p> <p>I noticed that Amazon does this as well, for example:</p> <pre><code>&lt;script type='text/javascript'&gt; if (typeof window['jQuery'] == 'undefined') document.write('&lt;scr'+'ipt type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"&gt;&lt;/sc'+'ript&gt;'); &lt;/script&gt; </code></pre>
[ { "answer_id": 236083, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "<p>I think is for prevent the browser's HTML parser from interpreting the &lt;script&gt;, and mainly the &lt;/script&gt; as the closing tag of the actual script, however I don't think that using document.write is a excellent idea for evaluating script blocks, why don't use the DOM...</p>\n\n<pre><code>var newScript = document.createElement(\"script\");\n...\n</code></pre>\n" }, { "answer_id": 236106, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 10, "selected": true, "text": "<p><code>&lt;/script&gt;</code> has to be broken up because otherwise it would end the enclosing <code>&lt;script&gt;&lt;/script&gt;</code> block too early. Really it should be split between the <code>&lt;</code> and the <code>/</code>, because a script block is supposed (according to SGML) to be <a href=\"http://www.w3.org/TR/html4/types.html#type-cdata\" rel=\"noreferrer\">terminated by any end-tag open (ETAGO) sequence (i.e. <code>&lt;/</code>)</a>:</p>\n\n<blockquote>\n <p>Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence \"<code>&lt;/</code>\" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.</p>\n</blockquote>\n\n<p>However in practice browsers only end parsing a CDATA script block on an actual <code>&lt;/script&gt;</code> close-tag.</p>\n\n<p>In XHTML there is no such special handling for script blocks, so any <code>&lt;</code> (or <code>&amp;</code>) character inside them must be <code>&amp;escaped;</code> like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n document.write('\\x3Cscript type=\"text/javascript\" src=\"foo.js\"&gt;\\x3C/script&gt;');\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 18832826, "author": "Stoffe", "author_id": 134276, "author_profile": "https://Stackoverflow.com/users/134276", "pm_score": 5, "selected": false, "text": "<p>Here's another variation I've used when wanting to generate a script tag inline (so it executes immediately) without needing any form of escapes:</p>\n\n<pre><code>&lt;script&gt;\n var script = document.createElement('script');\n script.src = '/path/to/script.js';\n document.write(script.outerHTML);\n&lt;/script&gt;\n</code></pre>\n\n<p>(Note: contrary to most examples on the net, I'm not setting <code>type=\"text/javascript\"</code> on neither the enclosing tag, nor the generated one: there is no browser not having that as the default, and so it is redundant, but will not hurt either, if you disagree).</p>\n" }, { "answer_id": 20376002, "author": "Jongosi", "author_id": 1330505, "author_profile": "https://Stackoverflow.com/users/1330505", "pm_score": 3, "selected": false, "text": "<p>The solution Bobince posted works perfectly for me. I wanted to offer an alternative method as well for future visitors:</p>\n\n<pre><code>if (typeof(jQuery) == 'undefined') {\n (function() {\n var sct = document.createElement('script');\n sct.src = ('https:' == document.location.protocol ? 'https' : 'http') +\n '://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';\n sct.type = 'text/javascript';\n sct.async = 'true';\n var domel = document.getElementsByTagName('script')[0];\n domel.parentNode.insertBefore(sct, domel);\n })();\n}\n</code></pre>\n\n<p>In this example, I've included a conditional load for jQuery to demonstrate use case. Hope that's useful for someone!</p>\n" }, { "answer_id": 27123725, "author": "Mathieu Rodic", "author_id": 734335, "author_profile": "https://Stackoverflow.com/users/734335", "pm_score": 4, "selected": false, "text": "<p>The <code>&lt;/script&gt;</code> inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (<a href=\"http://jsfiddle.net/8axv2quv/\" rel=\"noreferrer\">see example on JSFiddle</a>).</p>\n\n<p>To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (<a href=\"http://jsfiddle.net/aqgng3o4/1/\" rel=\"noreferrer\">see example in JSFiddle</a>):</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n &lt;!--\n if (jQuery === undefined) {\n document.write('&lt;script type=\"text/javascript\" src=\"http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js\"&gt;&lt;/script&gt;');\n }\n // --&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>...but to be honest, using <code>document.write</code> is not something I would consider best practice. Why not manipulating the DOM directly?</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n &lt;!--\n if (jQuery === undefined) {\n var script = document.createElement('script');\n script.setAttribute('type', 'text/javascript');\n script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');\n document.body.appendChild(script);\n }\n // --&gt;\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2929/" ]
Why do some sites (or advertisers that give clients javascript code) employ a technique of splitting the `<script>` and/or `</script>` tags up within `document.write()` calls? I noticed that Amazon does this as well, for example: ``` <script type='text/javascript'> if (typeof window['jQuery'] == 'undefined') document.write('<scr'+'ipt type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></sc'+'ript>'); </script> ```
`</script>` has to be broken up because otherwise it would end the enclosing `<script></script>` block too early. Really it should be split between the `<` and the `/`, because a script block is supposed (according to SGML) to be [terminated by any end-tag open (ETAGO) sequence (i.e. `</`)](http://www.w3.org/TR/html4/types.html#type-cdata): > > Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "`</`" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element. > > > However in practice browsers only end parsing a CDATA script block on an actual `</script>` close-tag. In XHTML there is no such special handling for script blocks, so any `<` (or `&`) character inside them must be `&escaped;` like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be: ``` <script type="text/javascript"> document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>'); </script> ```
236,097
<p>In XEmacs this is done by the calling the function char-to-ucs on a character. GNU Emacs does not seem to have this function. In GNU Emacs, characters seem to be ordinary integers. Running C-x = on a latin character reveals that the Emacs codepoint is different from the Unicode codepoint for the corresponding character. How do I find the Unicode codepoint of the character at point in GNU Emacs?</p>
[ { "answer_id": 236160, "author": "Dwight Holman", "author_id": 2667, "author_profile": "https://Stackoverflow.com/users/2667", "pm_score": 6, "selected": false, "text": "<p>In a modern Emacs, M-x describe-char will tell you about the character at point.<br>\nAn example:</p>\n\n<pre><code> character: ¢ (2210, #o4242, #x8a2, U+00A2)\n charset: latin-iso8859-1\n (Right-Hand Part of Latin Alphabet 1 (ISO/IEC 8859-1): ISO-IR-100.)\n code point: #x22\n syntax: w which means: word\n category: l:Latin\nbuffer code: #x81 #xA2\n file code: #xC2 #xA2 (encoded by coding system utf-8)\n display: by this font (glyph code)\n -apple-monaco-medium-r-normal--12-120-72-72-m-120-mac-roman (#xA2)\n</code></pre>\n\n<p>Note the U+00A2 in the first part, which gives the Unicode codepoint of the character.</p>\n" }, { "answer_id": 236176, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Thanks for the quick answers. I looked at the source code for describe-char, and found the following snippet which solves my problem. I tested it in both XEmacs 21.4.13 Mule and GNU Emacs 22.1.1 and it seems to work.</p>\n\n<pre><code>(or (get-char-property (point) 'untranslated-utf-8)\n (encode-char (char-after) 'ucs))\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In XEmacs this is done by the calling the function char-to-ucs on a character. GNU Emacs does not seem to have this function. In GNU Emacs, characters seem to be ordinary integers. Running C-x = on a latin character reveals that the Emacs codepoint is different from the Unicode codepoint for the corresponding character. How do I find the Unicode codepoint of the character at point in GNU Emacs?
In a modern Emacs, M-x describe-char will tell you about the character at point. An example: ``` character: ¢ (2210, #o4242, #x8a2, U+00A2) charset: latin-iso8859-1 (Right-Hand Part of Latin Alphabet 1 (ISO/IEC 8859-1): ISO-IR-100.) code point: #x22 syntax: w which means: word category: l:Latin buffer code: #x81 #xA2 file code: #xC2 #xA2 (encoded by coding system utf-8) display: by this font (glyph code) -apple-monaco-medium-r-normal--12-120-72-72-m-120-mac-roman (#xA2) ``` Note the U+00A2 in the first part, which gives the Unicode codepoint of the character.
236,125
<p>Suppose I have this Windows wchar_t string:</p> <pre><code>L"\x4f60\x597d" </code></pre> <p>and</p> <pre><code>L"\x00e4\x00a0\x597d" </code></pre> <p>and would like to convert it (not necessarily programmatically; it will be a one-time thing) to GCC/Linux wchar_t format, which is UTF-32 AFAIK. How do I do it? (a general explanation would be nice, but example based on this concrete case would be helpful as well)</p> <p><em>Please don't direct me to character conversion sites. I would like to convert from L"\x(something)" form and not "end character" form.</em></p>
[ { "answer_id": 236574, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 2, "selected": false, "text": "<p>Would converting from UTF-16 (the Visual C++ <code>wchar_t</code> form) to UTF-8, then possibly from UTF-8 to UCS-4 (the GCC <code>wchar_t</code> form), be an acceptable answer?</p>\n\n<p>If so, then in Windows you could use the <code>WideCharToMultiByte</code> function (with <code>CP_UTF8</code> for the <code>CodePage</code> parameter), for the first part of the conversion. Then you could either paste the resulting UTF-8 strings directly into your program, or convert them further. <a href=\"http://osdir.com/ml/org.user-groups.slug.coders/2006-12/msg00006.html\" rel=\"nofollow noreferrer\">Here</a> is a message showing how one person did it; you can also write your own code or do it manually (the official spec, with a section on exactly how to convert UTF-8 to UCS-4, can be found <a href=\"http://www.cl.cam.ac.uk/~mgk25/ucs/ISO-10646-UTF-8.html\" rel=\"nofollow noreferrer\">here</a>). There may be an easier way, I'm not overly familiar with the conversion stuff in Linux yet.</p>\n" }, { "answer_id": 237667, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 2, "selected": false, "text": "<p>You only need to worry about characters <a href=\"http://en.wikipedia.org/wiki/UTF-16#Encoding_of_characters_outside_the_BMP\" rel=\"nofollow noreferrer\">between \\xD800 and \\xDFFF inclusive</a>. Every other character should map exactly the same from UTF-16 to UCS-4 when zero-filled.</p>\n" }, { "answer_id": 351292, "author": "lothar", "author_id": 44434, "author_profile": "https://Stackoverflow.com/users/44434", "pm_score": 1, "selected": true, "text": "<p>One of the most used libraries to do character conversion is the ICU library <a href=\"http://icu-project.org/\" rel=\"nofollow noreferrer\">http://icu-project.org/</a> It is e.g. used by some boost <a href=\"http://www.boost.org/\" rel=\"nofollow noreferrer\">http://www.boost.org/</a> libraries.</p>\n" }, { "answer_id": 1176478, "author": "Mihai Nita", "author_id": 53276, "author_profile": "https://Stackoverflow.com/users/53276", "pm_score": 0, "selected": false, "text": "<p>Ignacio is right, if you don't use some rare Chinese characters (or some extinct scripts), then the mapping is one to one. (the official \"lingo\" is \"if you don't have characters outside BMP\")</p>\n\n<p>This is the algorithm, just in case:\n <a href=\"http://unicode.org/faq/utf_bom.html#utf16-3\" rel=\"nofollow noreferrer\">http://unicode.org/faq/utf_bom.html#utf16-3</a>\nBut again, most likely useless for your real case.</p>\n\n<p>You can also use the free sources from Unicode (<a href=\"ftp://ftp.unicode.org/Public/PROGRAMS/CVTUTF\" rel=\"nofollow noreferrer\">ftp://ftp.unicode.org/Public/PROGRAMS/CVTUTF</a>)</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
Suppose I have this Windows wchar\_t string: ``` L"\x4f60\x597d" ``` and ``` L"\x00e4\x00a0\x597d" ``` and would like to convert it (not necessarily programmatically; it will be a one-time thing) to GCC/Linux wchar\_t format, which is UTF-32 AFAIK. How do I do it? (a general explanation would be nice, but example based on this concrete case would be helpful as well) *Please don't direct me to character conversion sites. I would like to convert from L"\x(something)" form and not "end character" form.*
One of the most used libraries to do character conversion is the ICU library <http://icu-project.org/> It is e.g. used by some boost <http://www.boost.org/> libraries.
236,129
<p>How do I iterate over the words of a string composed of words separated by whitespace?</p> <p>Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; using namespace std; int main() { string s = &quot;Somewhere down the road&quot;; istringstream iss(s); do { string subs; iss &gt;&gt; subs; cout &lt;&lt; &quot;Substring: &quot; &lt;&lt; subs &lt;&lt; endl; } while (iss); } </code></pre>
[ { "answer_id": 236137, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>The STL does not have such a method available already.</p>\n\n<p>However, you can either use C's <a href=\"http://en.cppreference.com/w/c/string/byte/strtok\" rel=\"noreferrer\"><code>strtok()</code></a> function by using the <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/c_str\" rel=\"noreferrer\"><code>std::string::c_str()</code></a> member, or you can write your own. Here is a code sample I found after a quick Google search (<strong>\"STL string split\"</strong>):</p>\n\n<pre><code>void Tokenize(const string&amp; str,\n vector&lt;string&gt;&amp; tokens,\n const string&amp; delimiters = \" \")\n{\n // Skip delimiters at beginning.\n string::size_type lastPos = str.find_first_not_of(delimiters, 0);\n // Find first \"non-delimiter\".\n string::size_type pos = str.find_first_of(delimiters, lastPos);\n\n while (string::npos != pos || string::npos != lastPos)\n {\n // Found a token, add it to the vector.\n tokens.push_back(str.substr(lastPos, pos - lastPos));\n // Skip delimiters. Note the \"not_of\"\n lastPos = str.find_first_not_of(delimiters, pos);\n // Find next \"non-delimiter\"\n pos = str.find_first_of(delimiters, lastPos);\n }\n}\n</code></pre>\n\n<p>Taken from: <a href=\"http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html\" rel=\"noreferrer\">http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html</a></p>\n\n<p>If you have questions about the code sample, leave a comment and I will explain.</p>\n\n<p>And just because it does not implement a <code>typedef</code> called iterator or overload the <code>&lt;&lt;</code> operator does not mean it is bad code. I use C functions quite frequently. For example, <a href=\"http://en.cppreference.com/w/c/io/fprintf\" rel=\"noreferrer\"><code>printf</code></a> and <a href=\"http://en.cppreference.com/w/c/io/fscanf\" rel=\"noreferrer\"><code>scanf</code></a> both are faster than <a href=\"http://en.cppreference.com/w/cpp/io/cin\" rel=\"noreferrer\"><code>std::cin</code></a> and <a href=\"http://en.cppreference.com/w/cpp/io/cout\" rel=\"noreferrer\"><code>std::cout</code></a> (significantly), the <a href=\"http://en.cppreference.com/w/c/io/fopen\" rel=\"noreferrer\"><code>fopen</code></a> syntax is a lot more friendly for binary types, and they also tend to produce smaller EXEs.</p>\n\n<p>Don't get sold on this <strong>\"Elegance over performance\"</strong> deal.</p>\n" }, { "answer_id": 236146, "author": "gnomed", "author_id": 27739, "author_profile": "https://Stackoverflow.com/users/27739", "pm_score": 7, "selected": false, "text": "<p>This is my favorite way to iterate through a string. You can do whatever you want per word.</p>\n\n<pre><code>string line = \"a line of text to iterate through\";\nstring word;\n\nistringstream iss(line, istringstream::in);\n\nwhile( iss &gt;&gt; word ) \n{\n // Do something on `word` here...\n}\n</code></pre>\n" }, { "answer_id": 236153, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 5, "selected": false, "text": "<p>Using <code>std::stringstream</code> as you have works perfectly fine, and do exactly what you wanted. If you're just looking for different way of doing things though, you can use <a href=\"http://en.cppreference.com/w/cpp/algorithm/find\" rel=\"noreferrer\"><code>std::find()</code></a>/<a href=\"http://en.cppreference.com/w/cpp/algorithm/find_first_of\" rel=\"noreferrer\"><code>std::find_first_of()</code></a> and <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/substr\" rel=\"noreferrer\"><code>std::string::substr()</code></a>.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nint main()\n{\n std::string s(\"Somewhere down the road\");\n std::string::size_type prev_pos = 0, pos = 0;\n\n while( (pos = s.find(' ', pos)) != std::string::npos )\n {\n std::string substring( s.substr(prev_pos, pos-prev_pos) );\n\n std::cout &lt;&lt; substring &lt;&lt; '\\n';\n\n prev_pos = ++pos;\n }\n\n std::string substring( s.substr(prev_pos, pos-prev_pos) ); // Last word\n std::cout &lt;&lt; substring &lt;&lt; '\\n';\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 236158, "author": "Peter C.", "author_id": 31389, "author_profile": "https://Stackoverflow.com/users/31389", "pm_score": -1, "selected": false, "text": "<p>For a ridiculously large and probably redundant version, try a lot of for loops.</p>\n\n<pre><code>string stringlist[10];\nint count = 0;\n\nfor (int i = 0; i &lt; sequence.length(); i++)\n{\n if (sequence[i] == ' ')\n {\n stringlist[count] = sequence.substr(0, i);\n sequence.erase(0, i+1);\n i = 0;\n count++;\n }\n else if (i == sequence.length()-1) // Last word\n {\n stringlist[count] = sequence.substr(0, i+1);\n }\n}\n</code></pre>\n\n<p>It isn't pretty, but by and large (Barring punctuation and a slew of other bugs) it works!</p>\n" }, { "answer_id": 236180, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 6, "selected": false, "text": "<p>I like the following because it puts the results into a vector, supports a string as a delim and gives control over keeping empty values. But, it doesn't look as good then.</p>\n\n<pre><code>#include &lt;ostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\nusing namespace std;\n\nvector&lt;string&gt; split(const string&amp; s, const string&amp; delim, const bool keep_empty = true) {\n vector&lt;string&gt; result;\n if (delim.empty()) {\n result.push_back(s);\n return result;\n }\n string::const_iterator substart = s.begin(), subend;\n while (true) {\n subend = search(substart, s.end(), delim.begin(), delim.end());\n string temp(substart, subend);\n if (keep_empty || !temp.empty()) {\n result.push_back(temp);\n }\n if (subend == s.end()) {\n break;\n }\n substart = subend + delim.size();\n }\n return result;\n}\n\nint main() {\n const vector&lt;string&gt; words = split(\"So close no matter how far\", \" \");\n copy(words.begin(), words.end(), ostream_iterator&lt;string&gt;(cout, \"\\n\"));\n}\n</code></pre>\n\n<p>Of course, Boost has a <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/string_algo/usage.html#id3483755\" rel=\"noreferrer\"><code>split()</code></a> that works partially like that. And, if by 'white-space', you really do mean any type of white-space, using Boost's split with <code>is_any_of()</code> works great.</p>\n" }, { "answer_id": 236234, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 6, "selected": false, "text": "<p>This is similar to Stack Overflow question <em><a href=\"https://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c\">How do I tokenize a string in C++?</a></em>. <strong>Requires Boost external library</strong></p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;boost/tokenizer.hpp&gt;\n\nusing namespace std;\nusing namespace boost;\n\nint main(int argc, char** argv)\n{\n string text = &quot;token test\\tstring&quot;;\n\n char_separator&lt;char&gt; sep(&quot; \\t&quot;);\n tokenizer&lt;char_separator&lt;char&gt;&gt; tokens(text, sep);\n for (const string&amp; t : tokens)\n {\n cout &lt;&lt; t &lt;&lt; &quot;.&quot; &lt;&lt; endl;\n }\n}\n</code></pre>\n" }, { "answer_id": 236803, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 11, "selected": false, "text": "<p>I use this to split string by a delimiter. The first puts the results in a pre-constructed vector, the second returns a new vector.</p>\n\n\n\n<pre class=\"lang-c++ prettyprint-override\"><code>#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;vector&gt;\n#include &lt;iterator&gt;\n\ntemplate &lt;typename Out&gt;\nvoid split(const std::string &amp;s, char delim, Out result) {\n std::istringstream iss(s);\n std::string item;\n while (std::getline(iss, item, delim)) {\n *result++ = item;\n }\n}\n\nstd::vector&lt;std::string&gt; split(const std::string &amp;s, char delim) {\n std::vector&lt;std::string&gt; elems;\n split(s, delim, std::back_inserter(elems));\n return elems;\n}\n</code></pre>\n\n<hr>\n\n<p>Note that this solution does not skip empty tokens, so the following will find 4 items, one of which is empty:</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>std::vector&lt;std::string&gt; x = split(\"one:two::three\", ':');\n</code></pre>\n" }, { "answer_id": 236976, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 10, "selected": false, "text": "<p>A possible solution using Boost might be:</p>\n\n<pre><code>#include &lt;boost/algorithm/string.hpp&gt;\nstd::vector&lt;std::string&gt; strs;\nboost::split(strs, \"string to split\", boost::is_any_of(\"\\t \"));\n</code></pre>\n\n<p>This approach might be even faster than the <code>stringstream</code> approach. And since this is a generic template function it can be used to split other types of strings (wchar, etc. or UTF-8) using all kinds of delimiters.</p>\n\n<p>See the <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/string_algo/usage.html\" rel=\"noreferrer\">documentation</a> for details.</p>\n" }, { "answer_id": 237280, "author": "Zunino", "author_id": 30767, "author_profile": "https://Stackoverflow.com/users/30767", "pm_score": 12, "selected": true, "text": "<p>For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n\nint main() {\n using namespace std;\n string sentence = \"And I feel fine...\";\n istringstream iss(sentence);\n copy(istream_iterator&lt;string&gt;(iss),\n istream_iterator&lt;string&gt;(),\n ostream_iterator&lt;string&gt;(cout, \"\\n\"));\n}\n</code></pre>\n\n<p>Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic <a href=\"https://en.cppreference.com/w/cpp/algorithm/copy\" rel=\"noreferrer\"><code>copy</code></a> algorithm.</p>\n\n<pre><code>vector&lt;string&gt; tokens;\ncopy(istream_iterator&lt;string&gt;(iss),\n istream_iterator&lt;string&gt;(),\n back_inserter(tokens));\n</code></pre>\n\n<p>... or create the <code>vector</code> directly:</p>\n\n<pre><code>vector&lt;string&gt; tokens{istream_iterator&lt;string&gt;{iss},\n istream_iterator&lt;string&gt;{}};\n</code></pre>\n" }, { "answer_id": 1493195, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 8, "selected": false, "text": "<p>For those with whom it does not sit well to sacrifice all efficiency for code size and see \"efficient\" as a type of elegance, the following should hit a sweet spot (and I think the template container class is an awesomely elegant addition.):</p>\n\n<pre><code>template &lt; class ContainerT &gt;\nvoid tokenize(const std::string&amp; str, ContainerT&amp; tokens,\n const std::string&amp; delimiters = \" \", bool trimEmpty = false)\n{\n std::string::size_type pos, lastPos = 0, length = str.length();\n\n using value_type = typename ContainerT::value_type;\n using size_type = typename ContainerT::size_type;\n\n while(lastPos &lt; length + 1)\n {\n pos = str.find_first_of(delimiters, lastPos);\n if(pos == std::string::npos)\n {\n pos = length;\n }\n\n if(pos != lastPos || !trimEmpty)\n tokens.push_back(value_type(str.data()+lastPos,\n (size_type)pos-lastPos ));\n\n lastPos = pos + 1;\n }\n}\n</code></pre>\n\n<p>I usually choose to use <code>std::vector&lt;std::string&gt;</code> types as my second parameter (<code>ContainerT</code>)... but <code>list&lt;&gt;</code> is way faster than <code>vector&lt;&gt;</code> for when direct access is not needed, and you can even create your own string class and use something like <code>std::list&lt;subString&gt;</code> where <code>subString</code> does not do any copies for incredible speed increases.</p>\n\n<p>It's more than double as fast as the fastest tokenize on this page and almost 5 times faster than some others. Also with the perfect parameter types you can eliminate all string and list copies for additional speed increases.</p>\n\n<p>Additionally it does not do the (extremely inefficient) return of result, but rather it passes the tokens as a reference, thus also allowing you to build up tokens using multiple calls if you so wished.</p>\n\n<p>Lastly it allows you to specify whether to trim empty tokens from the results via a last optional parameter.</p>\n\n<p>All it needs is <code>std::string</code>... the rest are optional. It does not use streams or the boost library, but is flexible enough to be able to accept some of these foreign types naturally.</p>\n" }, { "answer_id": 2025273, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Here's another way of doing it..</p>\n\n<pre><code>void split_string(string text,vector&lt;string&gt;&amp; words)\n{\n int i=0;\n char ch;\n string word;\n\n while(ch=text[i++])\n {\n if (isspace(ch))\n {\n if (!word.empty())\n {\n words.push_back(word);\n }\n word = \"\";\n }\n else\n {\n word += ch;\n }\n }\n if (!word.empty())\n {\n words.push_back(word);\n }\n}\n</code></pre>\n" }, { "answer_id": 2560993, "author": "Robert", "author_id": 255635, "author_profile": "https://Stackoverflow.com/users/255635", "pm_score": 5, "selected": false, "text": "<p>Yet another flexible and fast way</p>\n\n<pre><code>template&lt;typename Operator&gt;\nvoid tokenize(Operator&amp; op, const char* input, const char* delimiters) {\n const char* s = input;\n const char* e = s;\n while (*e != 0) {\n e = s;\n while (*e != 0 &amp;&amp; strchr(delimiters, *e) == 0) ++e;\n if (e - s &gt; 0) {\n op(s, e - s);\n }\n s = e + 1;\n }\n}\n</code></pre>\n\n<p>To use it with a vector of strings (Edit: Since someone pointed out not to inherit STL classes... hrmf ;) ) :</p>\n\n<pre><code>template&lt;class ContainerType&gt;\nclass Appender {\npublic:\n Appender(ContainerType&amp; container) : container_(container) {;}\n void operator() (const char* s, unsigned length) { \n container_.push_back(std::string(s,length));\n }\nprivate:\n ContainerType&amp; container_;\n};\n\nstd::vector&lt;std::string&gt; strVector;\nAppender v(strVector);\ntokenize(v, \"A number of words to be tokenized\", \" \\t\");\n</code></pre>\n\n<p>That's it! And that's just one way to use the tokenizer, like how to just \ncount words:</p>\n\n<pre><code>class WordCounter {\npublic:\n WordCounter() : noOfWords(0) {}\n void operator() (const char*, unsigned) {\n ++noOfWords;\n }\n unsigned noOfWords;\n};\n\nWordCounter wc;\ntokenize(wc, \"A number of words to be counted\", \" \\t\"); \nASSERT( wc.noOfWords == 7 );\n</code></pre>\n\n<p>Limited by imagination ;)</p>\n" }, { "answer_id": 3037106, "author": "Pratik Deoghare", "author_id": 58737, "author_profile": "https://Stackoverflow.com/users/58737", "pm_score": 5, "selected": false, "text": "<p>There is a function named <a href=\"http://www.cplusplus.com/reference/clibrary/cstring/strtok/\" rel=\"noreferrer\"><code>strtok</code></a>.</p>\n\n<pre><code>#include&lt;string&gt;\nusing namespace std;\n\nvector&lt;string&gt; split(char* str,const char* delim)\n{\n char* saveptr;\n char* token = strtok_r(str,delim,&amp;saveptr);\n\n vector&lt;string&gt; result;\n\n while(token != NULL)\n {\n result.push_back(token);\n token = strtok_r(NULL,delim,&amp;saveptr);\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 3616605, "author": "Abe", "author_id": 436795, "author_profile": "https://Stackoverflow.com/users/436795", "pm_score": 3, "selected": false, "text": "<p>I use this simpleton because we got our String class \"special\" (i.e. not standard):</p>\n\n<pre><code>void splitString(const String &amp;s, const String &amp;delim, std::vector&lt;String&gt; &amp;result) {\n const int l = delim.length();\n int f = 0;\n int i = s.indexOf(delim,f);\n while (i&gt;=0) {\n String token( i-f &gt; 0 ? s.substring(f,i-f) : \"\");\n result.push_back(token);\n f=i+l;\n i = s.indexOf(delim,f);\n }\n String token = s.substring(f);\n result.push_back(token);\n}\n</code></pre>\n" }, { "answer_id": 4081331, "author": "lemic", "author_id": 495167, "author_profile": "https://Stackoverflow.com/users/495167", "pm_score": 1, "selected": false, "text": "<p>Loop on <code>getline</code> with ' ' as the token.</p>\n" }, { "answer_id": 4689579, "author": "Goran", "author_id": 575461, "author_profile": "https://Stackoverflow.com/users/575461", "pm_score": 4, "selected": false, "text": "<p>So far I used the one in <a href=\"http://en.wikipedia.org/wiki/Boost_C++_Libraries\" rel=\"noreferrer\">Boost</a>, but I needed something that doesn't depends on it, so I came to this:</p>\n\n<pre><code>static void Split(std::vector&lt;std::string&gt;&amp; lst, const std::string&amp; input, const std::string&amp; separators, bool remove_empty = true)\n{\n std::ostringstream word;\n for (size_t n = 0; n &lt; input.size(); ++n)\n {\n if (std::string::npos == separators.find(input[n]))\n word &lt;&lt; input[n];\n else\n {\n if (!word.str().empty() || !remove_empty)\n lst.push_back(word.str());\n word.str(\"\");\n }\n }\n if (!word.str().empty() || !remove_empty)\n lst.push_back(word.str());\n}\n</code></pre>\n\n<p>A good point is that in <code>separators</code> you can pass more than one character.</p>\n" }, { "answer_id": 5208977, "author": "kev", "author_id": 348785, "author_profile": "https://Stackoverflow.com/users/348785", "pm_score": 9, "selected": false, "text": "<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\n\nint main()\n{\n std::string str(\"Split me by whitespaces\");\n std::string buf; // Have a buffer string\n std::stringstream ss(str); // Insert the string into a stream\n\n std::vector&lt;std::string&gt; tokens; // Create vector to hold our words\n\n while (ss &gt;&gt; buf)\n tokens.push_back(buf);\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 5419348, "author": "zerm", "author_id": 359335, "author_profile": "https://Stackoverflow.com/users/359335", "pm_score": 5, "selected": false, "text": "<p>If you like to use boost, but want to use a whole string as delimiter (instead of single characters as in most of the previously proposed solutions), you can use the <code>boost_split_iterator</code>.</p>\n\n<p>Example code including convenient template:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;boost/algorithm/string.hpp&gt;\n\ntemplate&lt;typename _OutputIterator&gt;\ninline void split(\n const std::string&amp; str, \n const std::string&amp; delim, \n _OutputIterator result)\n{\n using namespace boost::algorithm;\n typedef split_iterator&lt;std::string::const_iterator&gt; It;\n\n for(It iter=make_split_iterator(str, first_finder(delim, is_equal()));\n iter!=It();\n ++iter)\n {\n *(result++) = boost::copy_range&lt;std::string&gt;(*iter);\n }\n}\n\nint main(int argc, char* argv[])\n{\n using namespace std;\n\n vector&lt;string&gt; splitted;\n split(\"HelloFOOworldFOO!\", \"FOO\", back_inserter(splitted));\n\n // or directly to console, for example\n split(\"HelloFOOworldFOO!\", \"FOO\", ostream_iterator&lt;string&gt;(cout, \"\\n\"));\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 6010463, "author": "Kelly Elton", "author_id": 222054, "author_profile": "https://Stackoverflow.com/users/222054", "pm_score": 3, "selected": false, "text": "<p>The following is a much better way to do this. It can take any character, and doesn't split lines unless you want. No special libraries needed (well, besides std, but who really considers that an extra library), no pointers, no references, and it's static. Just simple plain C++.</p>\n\n<pre><code>#pragma once\n#include &lt;vector&gt;\n#include &lt;sstream&gt;\nusing namespace std;\nclass Helpers\n{\n public:\n static vector&lt;string&gt; split(string s, char delim)\n {\n stringstream temp (stringstream::in | stringstream::out);\n vector&lt;string&gt; elems(0);\n if (s.size() == 0 || delim == 0)\n return elems;\n for(char c : s)\n {\n if(c == delim)\n {\n elems.push_back(temp.str());\n temp = stringstream(stringstream::in | stringstream::out);\n }\n else\n temp &lt;&lt; c;\n }\n if (temp.str().size() &gt; 0)\n elems.push_back(temp.str());\n return elems;\n }\n\n //Splits string s with a list of delimiters in delims (it's just a list, like if we wanted to\n //split at the following letters, a, b, c we would make delims=\"abc\".\n static vector&lt;string&gt; split(string s, string delims)\n {\n stringstream temp (stringstream::in | stringstream::out);\n vector&lt;string&gt; elems(0);\n bool found;\n if(s.size() == 0 || delims.size() == 0)\n return elems;\n for(char c : s)\n {\n found = false;\n for(char d : delims)\n {\n if (c == d)\n {\n elems.push_back(temp.str());\n temp = stringstream(stringstream::in | stringstream::out);\n found = true;\n break;\n }\n }\n if(!found)\n temp &lt;&lt; c;\n }\n if(temp.str().size() &gt; 0)\n elems.push_back(temp.str());\n return elems;\n }\n};\n</code></pre>\n" }, { "answer_id": 6321203, "author": "Marty B", "author_id": 790360, "author_profile": "https://Stackoverflow.com/users/790360", "pm_score": 3, "selected": false, "text": "<p>I like to use the boost/regex methods for this task since they provide maximum flexibility for specifying the splitting criteria.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;boost/regex.hpp&gt;\n\nint main() {\n std::string line(\"A:::line::to:split\");\n const boost::regex re(\":+\"); // one or more colons\n\n // -1 means find inverse matches aka split\n boost::sregex_token_iterator tokens(line.begin(),line.end(),re,-1);\n boost::sregex_token_iterator end;\n\n for (; tokens != end; ++tokens)\n std::cout &lt;&lt; *tokens &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 6461136, "author": "gibbz", "author_id": 813184, "author_profile": "https://Stackoverflow.com/users/813184", "pm_score": 4, "selected": false, "text": "<p>What about this:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n\nusing namespace std;\n\nvector&lt;string&gt; split(string str, const char delim) {\n vector&lt;string&gt; v;\n string tmp;\n\n for(string::const_iterator i; i = str.begin(); i &lt;= str.end(); ++i) {\n if(*i != delim &amp;&amp; i != str.end()) {\n tmp += *i; \n } else {\n v.push_back(tmp);\n tmp = \"\"; \n } \n } \n\n return v;\n}\n</code></pre>\n" }, { "answer_id": 6859092, "author": "Jairo Abdiel Toribio Cisneros", "author_id": 867443, "author_profile": "https://Stackoverflow.com/users/867443", "pm_score": 2, "selected": false, "text": "<p>This is my versión taken the source of Kev:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\nvoid split(vector&lt;string&gt; &amp;result, string str, char delim ) {\n string tmp;\n string::iterator i;\n result.clear();\n\n for(i = str.begin(); i &lt;= str.end(); ++i) {\n if((const char)*i != delim &amp;&amp; i != str.end()) {\n tmp += *i;\n } else {\n result.push_back(tmp);\n tmp = \"\";\n }\n }\n}\n</code></pre>\n\n<p>After, call the function and do something with it:</p>\n\n<pre><code>vector&lt;string&gt; hosts;\nsplit(hosts, \"192.168.1.2,192.168.1.3\", ',');\nfor( size_t i = 0; i &lt; hosts.size(); i++){\n cout &lt;&lt; \"Connecting host : \" &lt;&lt; hosts.at(i) &lt;&lt; \"...\" &lt;&lt; endl;\n}\n</code></pre>\n" }, { "answer_id": 7045104, "author": "lukmac", "author_id": 555951, "author_profile": "https://Stackoverflow.com/users/555951", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://www.cplusplus.com/reference/sstream/stringstream/\" rel=\"noreferrer\">stringstream</a> can be convenient if you need to parse the string by non-space symbols:</p>\n\n<pre><code>string s = \"Name:JAck; Spouse:Susan; ...\";\nstring dummy, name, spouse;\n\nistringstream iss(s);\ngetline(iss, dummy, ':');\ngetline(iss, name, ';');\ngetline(iss, dummy, ':');\ngetline(iss, spouse, ';')\n</code></pre>\n" }, { "answer_id": 7408245, "author": "Alec Thomas", "author_id": 7980, "author_profile": "https://Stackoverflow.com/users/7980", "pm_score": 7, "selected": false, "text": "<p>Here's another solution. It's compact and reasonably efficient:</p>\n\n<pre><code>std::vector&lt;std::string&gt; split(const std::string &amp;text, char sep) {\n std::vector&lt;std::string&gt; tokens;\n std::size_t start = 0, end = 0;\n while ((end = text.find(sep, start)) != std::string::npos) {\n tokens.push_back(text.substr(start, end - start));\n start = end + 1;\n }\n tokens.push_back(text.substr(start));\n return tokens;\n}\n</code></pre>\n\n<p>It can easily be templatised to handle string separators, wide strings, etc.</p>\n\n<p>Note that splitting <code>\"\"</code> results in a single empty string and splitting <code>\",\"</code> (ie. sep) results in two empty strings.</p>\n\n<p>It can also be easily expanded to skip empty tokens:</p>\n\n<pre><code>std::vector&lt;std::string&gt; split(const std::string &amp;text, char sep) {\n std::vector&lt;std::string&gt; tokens;\n std::size_t start = 0, end = 0;\n while ((end = text.find(sep, start)) != std::string::npos) {\n if (end != start) {\n tokens.push_back(text.substr(start, end - start));\n }\n start = end + 1;\n }\n if (end != start) {\n tokens.push_back(text.substr(start));\n }\n return tokens;\n}\n</code></pre>\n\n<hr>\n\n<p>If splitting a string at multiple delimiters while skipping empty tokens is desired, this version may be used:</p>\n\n<pre><code>std::vector&lt;std::string&gt; split(const std::string&amp; text, const std::string&amp; delims)\n{\n std::vector&lt;std::string&gt; tokens;\n std::size_t start = text.find_first_not_of(delims), end = 0;\n\n while((end = text.find_first_of(delims, start)) != std::string::npos)\n {\n tokens.push_back(text.substr(start, end - start));\n start = text.find_first_not_of(delims, end);\n }\n if(start != std::string::npos)\n tokens.push_back(text.substr(start));\n\n return tokens;\n}\n</code></pre>\n" }, { "answer_id": 7414250, "author": "Andreas Spindler", "author_id": 887771, "author_profile": "https://Stackoverflow.com/users/887771", "pm_score": 3, "selected": false, "text": "<p>Recently I had to split a camel-cased word into subwords. There are no delimiters, just upper characters. </p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;list&gt;\n#include &lt;locale&gt; // std::isupper\n\ntemplate&lt;class String&gt;\nconst std::list&lt;String&gt; split_camel_case_string(const String &amp;s)\n{\n std::list&lt;String&gt; R;\n String w;\n\n for (String::const_iterator i = s.begin(); i &lt; s.end(); ++i) { {\n if (std::isupper(*i)) {\n if (w.length()) {\n R.push_back(w);\n w.clear();\n }\n }\n w += *i;\n }\n\n if (w.length())\n R.push_back(w);\n return R;\n}\n</code></pre>\n\n<p>For example, this splits \"AQueryTrades\" into \"A\", \"Query\" and \"Trades\". The function works with narrow and wide strings. Because it respects the current locale it splits \"RaumfahrtÜberwachungsVerordnung\" into \"Raumfahrt\", \"Überwachungs\" and \"Verordnung\".</p>\n\n<p>Note <code>std::upper</code> should be really passed as function template argument. Then the more generalized from of this function can split at delimiters like <code>\",\"</code>, <code>\";\"</code> or <code>\" \"</code> too.</p>\n" }, { "answer_id": 8457004, "author": "Software_Designer", "author_id": 999884, "author_profile": "https://Stackoverflow.com/users/999884", "pm_score": 3, "selected": false, "text": "<p>The code below uses <code>strtok()</code> to split a string into tokens and stores the tokens in a vector.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;vector&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\n\nchar one_line_string[] = \"hello hi how are you nice weather we are having ok then bye\";\nchar seps[] = \" ,\\t\\n\";\nchar *token;\n\n\n\nint main()\n{\n vector&lt;string&gt; vec_String_Lines;\n token = strtok( one_line_string, seps );\n\n cout &lt;&lt; \"Extracting and storing data in a vector..\\n\\n\\n\";\n\n while( token != NULL )\n {\n vec_String_Lines.push_back(token);\n token = strtok( NULL, seps );\n }\n cout &lt;&lt; \"Displaying end result in vector line storage..\\n\\n\";\n\n for ( int i = 0; i &lt; vec_String_Lines.size(); ++i)\n cout &lt;&lt; vec_String_Lines[i] &lt;&lt; \"\\n\";\n cout &lt;&lt; \"\\n\\n\\n\";\n\n\nreturn 0;\n}\n</code></pre>\n" }, { "answer_id": 9385486, "author": "landen", "author_id": 1224414, "author_profile": "https://Stackoverflow.com/users/1224414", "pm_score": 2, "selected": false, "text": "<p>Quick version which uses <code>vector</code> as the base class, giving full access to all of its operators:</p>\n\n<pre><code> // Split string into parts.\n class Split : public std::vector&lt;std::string&gt;\n {\n public:\n Split(const std::string&amp; str, char* delimList)\n {\n size_t lastPos = 0;\n size_t pos = str.find_first_of(delimList);\n\n while (pos != std::string::npos)\n {\n if (pos != lastPos)\n push_back(str.substr(lastPos, pos-lastPos));\n lastPos = pos + 1;\n pos = str.find_first_of(delimList, lastPos);\n }\n if (lastPos &lt; str.length())\n push_back(str.substr(lastPos, pos-lastPos));\n }\n };\n</code></pre>\n\n<p>Example used to populate an STL set:</p>\n\n<pre><code>std::set&lt;std::string&gt; words;\nSplit split(\"Hello,World\", \",\");\nwords.insert(split.begin(), split.end());\n</code></pre>\n" }, { "answer_id": 9619583, "author": "ManiP", "author_id": 576294, "author_profile": "https://Stackoverflow.com/users/576294", "pm_score": 2, "selected": false, "text": "<p>I use the following</p>\n\n<pre><code>void split(string in, vector&lt;string&gt;&amp; parts, char separator) {\n string::iterator ts, curr;\n ts = curr = in.begin();\n for(; curr &lt;= in.end(); curr++ ) {\n if( (curr == in.end() || *curr == separator) &amp;&amp; curr &gt; ts )\n parts.push_back( string( ts, curr ));\n if( curr == in.end() )\n break;\n if( *curr == separator ) ts = curr + 1; \n }\n}\n</code></pre>\n\n<p>PlasmaHH, I forgot to include the extra check( curr > ts) for removing tokens with whitespace. </p>\n" }, { "answer_id": 9676623, "author": "Marco M.", "author_id": 140311, "author_profile": "https://Stackoverflow.com/users/140311", "pm_score": 6, "selected": false, "text": "<p>Here is a split function that:</p>\n\n<ul>\n<li>is generic</li>\n<li>uses standard C++ (no boost)</li>\n<li>accepts multiple delimiters</li>\n<li><p>ignores empty tokens (can easily be changed)</p>\n\n<pre><code>template&lt;typename T&gt;\nvector&lt;T&gt; \nsplit(const T &amp; str, const T &amp; delimiters) {\n vector&lt;T&gt; v;\n typename T::size_type start = 0;\n auto pos = str.find_first_of(delimiters, start);\n while(pos != T::npos) {\n if(pos != start) // ignore empty tokens\n v.emplace_back(str, start, pos - start);\n start = pos + 1;\n pos = str.find_first_of(delimiters, start);\n }\n if(start &lt; str.length()) // ignore trailing delimiter\n v.emplace_back(str, start, str.length() - start); // add what's left of the string\n return v;\n}\n</code></pre></li>\n</ul>\n\n<p>Example usage:</p>\n\n<pre><code> vector&lt;string&gt; v = split&lt;string&gt;(\"Hello, there; World\", \";,\");\n vector&lt;wstring&gt; v = split&lt;wstring&gt;(L\"Hello, there; World\", L\";,\");\n</code></pre>\n" }, { "answer_id": 9688149, "author": "doicanhden", "author_id": 1178154, "author_profile": "https://Stackoverflow.com/users/1178154", "pm_score": 0, "selected": false, "text": "<p><strong>My code is:</strong></p>\n\n<pre><code>#include &lt;list&gt;\n#include &lt;string&gt;\ntemplate&lt;class StringType = std::string, class ContainerType = std::list&lt;StringType&gt; &gt;\nclass DSplitString:public ContainerType\n{\npublic:\n explicit DSplitString(const StringType&amp; strString, char cChar, bool bSkipEmptyParts = true)\n {\n size_t iPos = 0;\n size_t iPos_char = 0;\n while(StringType::npos != (iPos_char = strString.find(cChar, iPos)))\n {\n StringType strTemp = strString.substr(iPos, iPos_char - iPos);\n if((bSkipEmptyParts &amp;&amp; !strTemp.empty()) || (!bSkipEmptyParts))\n push_back(strTemp);\n iPos = iPos_char + 1;\n }\n }\n explicit DSplitString(const StringType&amp; strString, const StringType&amp; strSub, bool bSkipEmptyParts = true)\n {\n size_t iPos = 0;\n size_t iPos_char = 0;\n while(StringType::npos != (iPos_char = strString.find(strSub, iPos)))\n {\n StringType strTemp = strString.substr(iPos, iPos_char - iPos);\n if((bSkipEmptyParts &amp;&amp; !strTemp.empty()) || (!bSkipEmptyParts))\n push_back(strTemp);\n iPos = iPos_char + strSub.length();\n }\n }\n};\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\nint _tmain(int argc, _TCHAR* argv[])\n{\n DSplitString&lt;&gt; aa(\"doicanhden1;doicanhden2;doicanhden3;\", ';');\n for each (std::string var in aa)\n {\n std::cout &lt;&lt; var &lt;&lt; std::endl;\n }\n std::cin.get();\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 11652347, "author": "Dmitry", "author_id": 1551989, "author_profile": "https://Stackoverflow.com/users/1551989", "pm_score": 2, "selected": false, "text": "<p>I use the following code:</p>\n\n<pre><code>namespace Core\n{\n typedef std::wstring String;\n\n void SplitString(const Core::String&amp; input, const Core::String&amp; splitter, std::list&lt;Core::String&gt;&amp; output)\n {\n if (splitter.empty())\n {\n throw std::invalid_argument(); // for example\n }\n\n std::list&lt;Core::String&gt; lines;\n\n Core::String::size_type offset = 0;\n\n for (;;)\n {\n Core::String::size_type splitterPos = input.find(splitter, offset);\n\n if (splitterPos != Core::String::npos)\n {\n lines.push_back(input.substr(offset, splitterPos - offset));\n offset = splitterPos + splitter.size();\n }\n else\n {\n lines.push_back(input.substr(offset));\n break;\n }\n }\n\n lines.swap(output);\n }\n}\n\n// gtest:\n\nclass SplitStringTest: public testing::Test\n{\n};\n\nTEST_F(SplitStringTest, EmptyStringAndSplitter)\n{\n std::list&lt;Core::String&gt; result;\n ASSERT_ANY_THROW(Core::SplitString(Core::String(), Core::String(), result));\n}\n\nTEST_F(SplitStringTest, NonEmptyStringAndEmptySplitter)\n{\n std::list&lt;Core::String&gt; result;\n ASSERT_ANY_THROW(Core::SplitString(L\"xy\", Core::String(), result));\n}\n\nTEST_F(SplitStringTest, EmptyStringAndNonEmptySplitter)\n{\n std::list&lt;Core::String&gt; result;\n Core::SplitString(Core::String(), Core::String(L\",\"), result);\n ASSERT_EQ(1, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n}\n\nTEST_F(SplitStringTest, OneCharSplitter)\n{\n std::list&lt;Core::String&gt; result;\n\n Core::SplitString(L\"x,y\", L\",\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\"y\", *result.rbegin());\n\n Core::SplitString(L\",xy\", L\",\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n ASSERT_EQ(L\"xy\", *result.rbegin());\n\n Core::SplitString(L\"xy,\", L\",\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"xy\", *result.begin());\n ASSERT_EQ(Core::String(), *result.rbegin());\n}\n\nTEST_F(SplitStringTest, TwoCharsSplitter)\n{\n std::list&lt;Core::String&gt; result;\n\n Core::SplitString(L\"x,.y,z\", L\",.\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\"y,z\", *result.rbegin());\n\n Core::SplitString(L\"x,,y,z\", L\",,\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\"y,z\", *result.rbegin());\n}\n\nTEST_F(SplitStringTest, RecursiveSplitter)\n{\n std::list&lt;Core::String&gt; result;\n\n Core::SplitString(L\",,,\", L\",,\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n ASSERT_EQ(L\",\", *result.rbegin());\n\n Core::SplitString(L\",.,.,\", L\",.,\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n ASSERT_EQ(L\".,\", *result.rbegin());\n\n Core::SplitString(L\"x,.,.,y\", L\",.,\", result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\".,y\", *result.rbegin());\n\n Core::SplitString(L\",.,,.,\", L\",.,\", result);\n ASSERT_EQ(3, result.size());\n ASSERT_EQ(Core::String(), *result.begin());\n ASSERT_EQ(Core::String(), *(++result.begin()));\n ASSERT_EQ(Core::String(), *result.rbegin());\n}\n\nTEST_F(SplitStringTest, NullTerminators)\n{\n std::list&lt;Core::String&gt; result;\n\n Core::SplitString(L\"xy\", Core::String(L\"\\0\", 1), result);\n ASSERT_EQ(1, result.size());\n ASSERT_EQ(L\"xy\", *result.begin());\n\n Core::SplitString(Core::String(L\"x\\0y\", 3), Core::String(L\"\\0\", 1), result);\n ASSERT_EQ(2, result.size());\n ASSERT_EQ(L\"x\", *result.begin());\n ASSERT_EQ(L\"y\", *result.rbegin());\n}\n</code></pre>\n" }, { "answer_id": 12221291, "author": "Steve Dell", "author_id": 1639427, "author_profile": "https://Stackoverflow.com/users/1639427", "pm_score": 4, "selected": false, "text": "<p>I made this because I needed an easy way to split strings and c-based strings... Hopefully someone else can find it useful as well. Also it doesn't rely on tokens and you can use fields as delimiters, which is another key I needed.</p>\n\n<p>I'm sure there's improvements that can be made to even further improve its elegance and please do by all means</p>\n\n<p>StringSplitter.hpp:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;string.h&gt;\n\nusing namespace std;\n\nclass StringSplit\n{\nprivate:\n void copy_fragment(char*, char*, char*);\n void copy_fragment(char*, char*, char);\n bool match_fragment(char*, char*, int);\n int untilnextdelim(char*, char);\n int untilnextdelim(char*, char*);\n void assimilate(char*, char);\n void assimilate(char*, char*);\n bool string_contains(char*, char*);\n long calc_string_size(char*);\n void copy_string(char*, char*);\n\npublic:\n vector&lt;char*&gt; split_cstr(char);\n vector&lt;char*&gt; split_cstr(char*);\n vector&lt;string&gt; split_string(char);\n vector&lt;string&gt; split_string(char*);\n char* String;\n bool do_string;\n bool keep_empty;\n vector&lt;char*&gt; Container;\n vector&lt;string&gt; ContainerS;\n\n StringSplit(char * in)\n {\n String = in;\n }\n\n StringSplit(string in)\n {\n size_t len = calc_string_size((char*)in.c_str());\n String = new char[len + 1];\n memset(String, 0, len + 1);\n copy_string(String, (char*)in.c_str());\n do_string = true;\n }\n\n ~StringSplit()\n {\n for (int i = 0; i &lt; Container.size(); i++)\n {\n if (Container[i] != NULL)\n {\n delete[] Container[i];\n }\n }\n if (do_string)\n {\n delete[] String;\n }\n }\n};\n</code></pre>\n\n<p>StringSplitter.cpp:</p>\n\n<pre><code>#include &lt;string.h&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include \"StringSplit.hpp\"\n\nusing namespace std;\n\nvoid StringSplit::assimilate(char*src, char delim)\n{\n int until = untilnextdelim(src, delim);\n if (until &gt; 0)\n {\n char * temp = new char[until + 1];\n memset(temp, 0, until + 1);\n copy_fragment(temp, src, delim);\n if (keep_empty || *temp != 0)\n {\n if (!do_string)\n {\n Container.push_back(temp);\n }\n else\n {\n string x = temp;\n ContainerS.push_back(x);\n }\n\n }\n else\n {\n delete[] temp;\n }\n }\n}\n\nvoid StringSplit::assimilate(char*src, char* delim)\n{\n int until = untilnextdelim(src, delim);\n if (until &gt; 0)\n {\n char * temp = new char[until + 1];\n memset(temp, 0, until + 1);\n copy_fragment(temp, src, delim);\n if (keep_empty || *temp != 0)\n {\n if (!do_string)\n {\n Container.push_back(temp);\n }\n else\n {\n string x = temp;\n ContainerS.push_back(x);\n }\n }\n else\n {\n delete[] temp;\n }\n }\n}\n\nlong StringSplit::calc_string_size(char* _in)\n{\n long i = 0;\n while (*_in++)\n {\n i++;\n }\n return i;\n}\n\nbool StringSplit::string_contains(char* haystack, char* needle)\n{\n size_t len = calc_string_size(needle);\n size_t lenh = calc_string_size(haystack);\n while (lenh--)\n {\n if (match_fragment(haystack + lenh, needle, len))\n {\n return true;\n }\n }\n return false;\n}\n\nbool StringSplit::match_fragment(char* _src, char* cmp, int len)\n{\n while (len--)\n {\n if (*(_src + len) != *(cmp + len))\n {\n return false;\n }\n }\n return true;\n}\n\nint StringSplit::untilnextdelim(char* _in, char delim)\n{\n size_t len = calc_string_size(_in);\n if (*_in == delim)\n {\n _in += 1;\n return len - 1;\n }\n\n int c = 0;\n while (*(_in + c) != delim &amp;&amp; c &lt; len)\n {\n c++;\n }\n\n return c;\n}\n\nint StringSplit::untilnextdelim(char* _in, char* delim)\n{\n int s = calc_string_size(delim);\n int c = 1 + s;\n\n if (!string_contains(_in, delim))\n {\n return calc_string_size(_in);\n }\n else if (match_fragment(_in, delim, s))\n {\n _in += s;\n return calc_string_size(_in);\n }\n\n while (!match_fragment(_in + c, delim, s))\n {\n c++;\n }\n\n return c;\n}\n\nvoid StringSplit::copy_fragment(char* dest, char* src, char delim)\n{\n if (*src == delim)\n {\n src++;\n }\n\n int c = 0;\n while (*(src + c) != delim &amp;&amp; *(src + c))\n {\n *(dest + c) = *(src + c);\n c++;\n }\n *(dest + c) = 0;\n}\n\nvoid StringSplit::copy_string(char* dest, char* src)\n{\n int i = 0;\n while (*(src + i))\n {\n *(dest + i) = *(src + i);\n i++;\n }\n}\n\nvoid StringSplit::copy_fragment(char* dest, char* src, char* delim)\n{\n size_t len = calc_string_size(delim);\n size_t lens = calc_string_size(src);\n\n if (match_fragment(src, delim, len))\n {\n src += len;\n lens -= len;\n }\n\n int c = 0;\n while (!match_fragment(src + c, delim, len) &amp;&amp; (c &lt; lens))\n {\n *(dest + c) = *(src + c);\n c++;\n }\n *(dest + c) = 0;\n}\n\nvector&lt;char*&gt; StringSplit::split_cstr(char Delimiter)\n{\n int i = 0;\n while (*String)\n {\n if (*String != Delimiter &amp;&amp; i == 0)\n {\n assimilate(String, Delimiter);\n }\n if (*String == Delimiter)\n {\n assimilate(String, Delimiter);\n }\n i++;\n String++;\n }\n\n String -= i;\n delete[] String;\n\n return Container;\n}\n\nvector&lt;string&gt; StringSplit::split_string(char Delimiter)\n{\n do_string = true;\n\n int i = 0;\n while (*String)\n {\n if (*String != Delimiter &amp;&amp; i == 0)\n {\n assimilate(String, Delimiter);\n }\n if (*String == Delimiter)\n {\n assimilate(String, Delimiter);\n }\n i++;\n String++;\n }\n\n String -= i;\n delete[] String;\n\n return ContainerS;\n}\n\nvector&lt;char*&gt; StringSplit::split_cstr(char* Delimiter)\n{\n int i = 0;\n size_t LenDelim = calc_string_size(Delimiter);\n\n while(*String)\n {\n if (!match_fragment(String, Delimiter, LenDelim) &amp;&amp; i == 0)\n {\n assimilate(String, Delimiter);\n }\n if (match_fragment(String, Delimiter, LenDelim))\n {\n assimilate(String,Delimiter);\n }\n i++;\n String++;\n }\n\n String -= i;\n delete[] String;\n\n return Container;\n}\n\nvector&lt;string&gt; StringSplit::split_string(char* Delimiter)\n{\n do_string = true;\n int i = 0;\n size_t LenDelim = calc_string_size(Delimiter);\n\n while (*String)\n {\n if (!match_fragment(String, Delimiter, LenDelim) &amp;&amp; i == 0)\n {\n assimilate(String, Delimiter);\n }\n if (match_fragment(String, Delimiter, LenDelim))\n {\n assimilate(String, Delimiter);\n }\n i++;\n String++;\n }\n\n String -= i;\n delete[] String;\n\n return ContainerS;\n}\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>int main(int argc, char*argv[])\n{\n StringSplit ss = \"This:CUT:is:CUT:an:CUT:example:CUT:cstring\";\n vector&lt;char*&gt; Split = ss.split_cstr(\":CUT:\");\n\n for (int i = 0; i &lt; Split.size(); i++)\n {\n cout &lt;&lt; Split[i] &lt;&lt; endl;\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Will output:</p>\n\n<p>This<br>\nis<br>\nan<br>\nexample<br>\ncstring<br></p>\n\n<pre><code>int main(int argc, char*argv[])\n{\n StringSplit ss = \"This:is:an:example:cstring\";\n vector&lt;char*&gt; Split = ss.split_cstr(':');\n\n for (int i = 0; i &lt; Split.size(); i++)\n {\n cout &lt;&lt; Split[i] &lt;&lt; endl;\n }\n\n return 0;\n}\n\nint main(int argc, char*argv[])\n{\n string mystring = \"This[SPLIT]is[SPLIT]an[SPLIT]example[SPLIT]string\";\n StringSplit ss = mystring;\n vector&lt;string&gt; Split = ss.split_string(\"[SPLIT]\");\n\n for (int i = 0; i &lt; Split.size(); i++)\n {\n cout &lt;&lt; Split[i] &lt;&lt; endl;\n }\n\n return 0;\n}\n\nint main(int argc, char*argv[])\n{\n string mystring = \"This|is|an|example|string\";\n StringSplit ss = mystring;\n vector&lt;string&gt; Split = ss.split_string('|');\n\n for (int i = 0; i &lt; Split.size(); i++)\n {\n cout &lt;&lt; Split[i] &lt;&lt; endl;\n }\n\n return 0;\n}\n</code></pre>\n\n<p>To keep empty entries (by default empties will be excluded):</p>\n\n<pre><code>StringSplit ss = mystring;\nss.keep_empty = true;\nvector&lt;string&gt; Split = ss.split_string(\":DELIM:\");\n</code></pre>\n\n<p>The goal was to make it similar to C#'s Split() method where splitting a string is as easy as:</p>\n\n<pre><code>String[] Split = \n \"Hey:cut:what's:cut:your:cut:name?\".Split(new[]{\":cut:\"}, StringSplitOptions.None);\n\nforeach(String X in Split)\n{\n Console.Write(X);\n}\n</code></pre>\n\n<p>I hope someone else can find this as useful as I do.</p>\n" }, { "answer_id": 12447526, "author": "rhomu", "author_id": 1435414, "author_profile": "https://Stackoverflow.com/users/1435414", "pm_score": 5, "selected": false, "text": "<p>I have a 2 lines solution to this problem:</p>\n\n<pre><code>char sep = ' ';\nstd::string s=\"1 This is an example\";\n\nfor(size_t p=0, q=0; p!=s.npos; p=q)\n std::cout &lt;&lt; s.substr(p+(p!=0), (q=s.find(sep, p+1))-p-(p!=0)) &lt;&lt; std::endl;\n</code></pre>\n\n<p>Then instead of printing you can put it in a vector.</p>\n" }, { "answer_id": 12617462, "author": "User", "author_id": 1475556, "author_profile": "https://Stackoverflow.com/users/1475556", "pm_score": 2, "selected": false, "text": "<p>This is a function I wrote that helps me do a lot. It helped me when doing protocol for <code>WebSockets</code>. </p>\n\n<pre><code>using namespace std;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n\nvector&lt;string&gt; split ( string input , string split_id ) {\n vector&lt;string&gt; result;\n int i = 0;\n bool add;\n string temp;\n stringstream ss;\n size_t found;\n string real;\n int r = 0;\n while ( i != input.length() ) {\n add = false;\n ss &lt;&lt; input.at(i);\n temp = ss.str();\n found = temp.find(split_id);\n if ( found != string::npos ) {\n add = true;\n real.append ( temp , 0 , found );\n } else if ( r &gt; 0 &amp;&amp; ( i+1 ) == input.length() ) {\n add = true;\n real.append ( temp , 0 , found );\n }\n if ( add ) {\n result.push_back(real);\n ss.str(string());\n ss.clear();\n temp.clear();\n real.clear();\n r = 0;\n }\n i++;\n r++;\n }\n return result;\n}\n\nint main() {\n string s = \"S,o,m,e,w,h,e,r,e, down the road \\n In a really big C++ house. \\n Lives a little old lady. \\n That no one ever knew. \\n She comes outside. \\n In the very hot sun. \\n\\n\\n\\n\\n\\n\\n\\n And throws C++ at us. \\n The End. FIN.\";\n vector &lt; string &gt; Token;\n Token = split ( s , \",\" );\n for ( int i = 0 ; i &lt; Token.size(); i++) cout &lt;&lt; Token.at(i) &lt;&lt; endl;\n cout &lt;&lt; endl &lt;&lt; Token.size();\n int a;\n cin &gt;&gt; a;\n return a;\n}\n</code></pre>\n" }, { "answer_id": 12766351, "author": "Jim Huang", "author_id": 862149, "author_profile": "https://Stackoverflow.com/users/862149", "pm_score": 3, "selected": false, "text": "<p>I wrote the following piece of code. You can specify delimiter, which can be a string.\nThe result is similar to Java's String.split, with empty string in the result.</p>\n\n<p>For example, if we call split(\"ABCPICKABCANYABCTWO:ABC\", \"ABC\"), the result is as follows:</p>\n\n<pre><code>0 &lt;len:0&gt;\n1 PICK &lt;len:4&gt;\n2 ANY &lt;len:3&gt;\n3 TWO: &lt;len:4&gt;\n4 &lt;len:0&gt;\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>vector &lt;string&gt; split(const string&amp; str, const string&amp; delimiter = \" \") {\n vector &lt;string&gt; tokens;\n\n string::size_type lastPos = 0;\n string::size_type pos = str.find(delimiter, lastPos);\n\n while (string::npos != pos) {\n // Found a token, add it to the vector.\n cout &lt;&lt; str.substr(lastPos, pos - lastPos) &lt;&lt; endl;\n tokens.push_back(str.substr(lastPos, pos - lastPos));\n lastPos = pos + delimiter.size();\n pos = str.find(delimiter, lastPos);\n }\n\n tokens.push_back(str.substr(lastPos, str.size() - lastPos));\n return tokens;\n}\n</code></pre>\n" }, { "answer_id": 13125497, "author": "AJMansfield", "author_id": 1324631, "author_profile": "https://Stackoverflow.com/users/1324631", "pm_score": 5, "selected": false, "text": "<p>Heres a regex solution that only uses the standard regex library. (I'm a little rusty, so there may be a few syntax errors, but this is at least the general idea)</p>\n\n<pre><code>#include &lt;regex.h&gt;\n#include &lt;string.h&gt;\n#include &lt;vector.h&gt;\n\nusing namespace std;\n\nvector&lt;string&gt; split(string s){\n regex r (\"\\\\w+\"); //regex matches whole words, (greedy, so no fragment words)\n regex_iterator&lt;string::iterator&gt; rit ( s.begin(), s.end(), r );\n regex_iterator&lt;string::iterator&gt; rend; //iterators to iterate thru words\n vector&lt;string&gt; result&lt;regex_iterator&gt;(rit, rend);\n return result; //iterates through the matches to fill the vector\n}\n</code></pre>\n" }, { "answer_id": 13713420, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<pre><code>void splitString(string str, char delim, string array[], const int arraySize)\n{\n int delimPosition, subStrSize, subStrStart = 0;\n\n for (int index = 0; delimPosition != -1; index++)\n {\n delimPosition = str.find(delim, subStrStart);\n subStrSize = delimPosition - subStrStart;\n array[index] = str.substr(subStrStart, subStrSize);\n subStrStart =+ (delimPosition + 1);\n }\n}\n</code></pre>\n" }, { "answer_id": 15864515, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Get <a href=\"http://www.boost.org/\">Boost</a> ! : -)</p>\n\n<pre><code>#include &lt;boost/algorithm/string/split.hpp&gt;\n#include &lt;boost/algorithm/string.hpp&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nusing namespace std;\nusing namespace boost;\n\nint main(int argc, char**argv) {\n typedef vector &lt; string &gt; list_type;\n\n list_type list;\n string line;\n\n line = \"Somewhere down the road\";\n split(list, line, is_any_of(\" \"));\n\n for(int i = 0; i &lt; list.size(); i++)\n {\n cout &lt;&lt; list[i] &lt;&lt; endl;\n }\n\n return 0;\n}\n</code></pre>\n\n<p>This example gives the output - </p>\n\n<pre><code>Somewhere\ndown\nthe\nroad\n</code></pre>\n" }, { "answer_id": 17904439, "author": "LLLL", "author_id": 2261292, "author_profile": "https://Stackoverflow.com/users/2261292", "pm_score": 1, "selected": false, "text": "<p>I believe no one has posted this solution yet. Instead of using delimiters directly, it basically does the same as boost::split(), i.e., it allows you to pass a predicate that returns true if a char is a delimiter, and false otherwise. I think this gives the programmer a lot more control, and the great thing is you don't need boost.</p>\n\n<pre><code>template &lt;class Container, class String, class Predicate&gt;\nvoid split(Container&amp; output, const String&amp; input,\n const Predicate&amp; pred, bool trimEmpty = false) {\n auto it = begin(input);\n auto itLast = it;\n while (it = find_if(it, end(input), pred), it != end(input)) {\n if (not (trimEmpty and it == itLast)) {\n output.emplace_back(itLast, it);\n }\n ++it;\n itLast = it;\n }\n}\n</code></pre>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>struct Delim {\n bool operator()(char c) {\n return not isalpha(c);\n }\n}; \n\nint main() {\n string s(\"#include&lt;iostream&gt;\\n\"\n \"int main() { std::cout &lt;&lt; \\\"Hello world!\\\" &lt;&lt; std::endl; }\");\n\n vector&lt;string&gt; v;\n\n split(v, s, Delim(), true);\n /* Which is also the same as */\n split(v, s, [](char c) { return not isalpha(c); }, true);\n\n for (const auto&amp; i : v) {\n cout &lt;&lt; i &lt;&lt; endl;\n }\n}\n</code></pre>\n" }, { "answer_id": 18039502, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I have just written a fine example of how to split a char by symbol, which then places each array of chars (words seperated by your symbol) into a vector. For simplicity i made the vector type of std string.</p>\n\n<p>I hope this helps and is readable to you.</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nvoid push(std::vector&lt;std::string&gt; &amp;WORDS, std::string &amp;TMP){\n WORDS.push_back(TMP);\n TMP = \"\";\n}\nstd::vector&lt;std::string&gt; mySplit(char STRING[]){\n std::vector&lt;std::string&gt; words;\n std::string s;\n for(unsigned short i = 0; i &lt; strlen(STRING); i++){\n if(STRING[i] != ' '){\n s += STRING[i];\n }else{\n push(words, s);\n }\n }\n push(words, s);//Used to get last split\n return words;\n}\n\nint main(){\n char string[] = \"My awesome string.\";\n std::cout &lt;&lt; mySplit(string)[2];\n std::cin.get();\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 18151541, "author": "hkBattousai", "author_id": 245376, "author_profile": "https://Stackoverflow.com/users/245376", "pm_score": 0, "selected": false, "text": "<p>My implementation can be an alternative solution:</p>\n\n<pre><code>std::vector&lt;std::wstring&gt; SplitString(const std::wstring &amp; String, const std::wstring &amp; Seperator)\n{\n std::vector&lt;std::wstring&gt; Lines;\n size_t stSearchPos = 0;\n size_t stFoundPos;\n while (stSearchPos &lt; String.size() - 1)\n {\n stFoundPos = String.find(Seperator, stSearchPos);\n stFoundPos = (stFoundPos == std::string::npos) ? String.size() : stFoundPos;\n Lines.push_back(String.substr(stSearchPos, stFoundPos - stSearchPos));\n stSearchPos = stFoundPos + Seperator.size();\n }\n return Lines;\n}\n</code></pre>\n\n<p>Test code:</p>\n\n<pre><code>std::wstring MyString(L\"Part 1SEPsecond partSEPlast partSEPend\");\nstd::vector&lt;std::wstring&gt; Parts = IniFile::SplitString(MyString, L\"SEP\");\nstd::wcout &lt;&lt; L\"The string: \" &lt;&lt; MyString &lt;&lt; std::endl;\nfor (std::vector&lt;std::wstring&gt;::const_iterator it=Parts.begin(); it&lt;Parts.end(); ++it)\n{\n std::wcout &lt;&lt; *it &lt;&lt; L\"&lt;---\" &lt;&lt; std::endl;\n}\nstd::wcout &lt;&lt; std::endl;\nMyString = L\"this,time,a,comma separated,string\";\nstd::wcout &lt;&lt; L\"The string: \" &lt;&lt; MyString &lt;&lt; std::endl;\nParts = IniFile::SplitString(MyString, L\",\");\nfor (std::vector&lt;std::wstring&gt;::const_iterator it=Parts.begin(); it&lt;Parts.end(); ++it)\n{\n std::wcout &lt;&lt; *it &lt;&lt; L\"&lt;---\" &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>Output of the test code:</p>\n\n<pre><code>The string: Part 1SEPsecond partSEPlast partSEPend\nPart 1&lt;---\nsecond part&lt;---\nlast part&lt;---\nend&lt;---\n\nThe string: this,time,a,comma separated,string\nthis&lt;---\ntime&lt;---\na&lt;---\ncomma separated&lt;---\nstring&lt;---\n</code></pre>\n" }, { "answer_id": 19154603, "author": "san45", "author_id": 2673037, "author_profile": "https://Stackoverflow.com/users/2673037", "pm_score": 3, "selected": false, "text": "<pre><code>#include&lt;iostream&gt;\n#include&lt;string&gt;\n#include&lt;sstream&gt;\n#include&lt;vector&gt;\nusing namespace std;\n\n vector&lt;string&gt; split(const string &amp;s, char delim) {\n vector&lt;string&gt; elems;\n stringstream ss(s);\n string item;\n while (getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n }\n\nint main() {\n\n vector&lt;string&gt; x = split(\"thi is an sample test\",' ');\n unsigned int i;\n for(i=0;i&lt;x.size();i++)\n cout&lt;&lt;i&lt;&lt;\":\"&lt;&lt;x[i]&lt;&lt;endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 20807773, "author": "smac89", "author_id": 2089675, "author_profile": "https://Stackoverflow.com/users/2089675", "pm_score": 2, "selected": false, "text": "<p><strong>LazyStringSplitter:</strong></p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;algorithm&gt;\n#include &lt;unordered_set&gt;\n\nusing namespace std;\n\nclass LazyStringSplitter\n{\n string::const_iterator start, finish;\n unordered_set&lt;char&gt; chop;\n\npublic:\n\n // Empty Constructor\n explicit LazyStringSplitter()\n {}\n\n explicit LazyStringSplitter (const string cstr, const string delims)\n : start(cstr.begin())\n , finish(cstr.end())\n , chop(delims.begin(), delims.end())\n {}\n\n void operator () (const string cstr, const string delims)\n {\n chop.insert(delims.begin(), delims.end());\n start = cstr.begin();\n finish = cstr.end();\n }\n\n bool empty() const { return (start &gt;= finish); }\n\n string next()\n {\n // return empty string\n // if ran out of characters\n if (empty())\n return string(\"\");\n\n auto runner = find_if(start, finish, [&amp;](char c) {\n return chop.count(c) == 1;\n });\n\n // construct next string\n string ret(start, runner);\n start = runner + 1;\n\n // Never return empty string\n // + tail recursion makes this method efficient\n return !ret.empty() ? ret : next();\n }\n};\n</code></pre>\n\n<ul>\n<li>I call this method the <code>LazyStringSplitter</code> because of one reason - It does not split the string in one go.</li>\n<li>In essence it behaves like a python generator</li>\n<li>It exposes a method called <code>next</code> which returns the next string that is split from the original</li>\n<li>I made use of the <a href=\"http://en.cppreference.com/w/cpp/container/unordered_set\" rel=\"nofollow\">unordered_set</a> from c++11 STL, so that look up of delimiters is that much faster</li>\n<li>And here is how it works</li>\n</ul>\n\n<p><strong>TEST PROGRAM</strong></p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nint main()\n{\n LazyStringSplitter splitter;\n\n // split at the characters ' ', '!', '.', ','\n splitter(\"This, is a string. And here is another string! Let's test and see how well this does.\", \" !.,\");\n\n while (!splitter.empty())\n cout &lt;&lt; splitter.next() &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n\n<p><strong>OUTPUT</strong></p>\n\n<pre><code>This\nis\na\nstring\nAnd\nhere\nis\nanother\nstring\nLet's\ntest\nand\nsee\nhow\nwell\nthis\ndoes\n</code></pre>\n\n<p>Next plan to improve this is to implement <code>begin</code> and <code>end</code> methods so that one can do something like:</p>\n\n<pre><code>vector&lt;string&gt; split_string(splitter.begin(), splitter.end());\n</code></pre>\n" }, { "answer_id": 20981222, "author": "DannyK", "author_id": 969968, "author_profile": "https://Stackoverflow.com/users/969968", "pm_score": 4, "selected": false, "text": "<p>I've rolled my own using strtok and used boost to split a string. The best method I have found is the <a href=\"http://www.partow.net/programming/strtk/\">C++ String Toolkit Library</a>. It is incredibly flexible and fast.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;strtk.hpp&gt;\n\nconst char *whitespace = \" \\t\\r\\n\\f\";\nconst char *whitespace_and_punctuation = \" \\t\\r\\n\\f;,=\";\n\nint main()\n{\n { // normal parsing of a string into a vector of strings\n std::string s(\"Somewhere down the road\");\n std::vector&lt;std::string&gt; result;\n if( strtk::parse( s, whitespace, result ) )\n {\n for(size_t i = 0; i &lt; result.size(); ++i )\n std::cout &lt;&lt; result[i] &lt;&lt; std::endl;\n }\n }\n\n { // parsing a string into a vector of floats with other separators\n // besides spaces\n\n std::string s(\"3.0, 3.14; 4.0\");\n std::vector&lt;float&gt; values;\n if( strtk::parse( s, whitespace_and_punctuation, values ) )\n {\n for(size_t i = 0; i &lt; values.size(); ++i )\n std::cout &lt;&lt; values[i] &lt;&lt; std::endl;\n }\n }\n\n { // parsing a string into specific variables\n\n std::string s(\"angle = 45; radius = 9.9\");\n std::string w1, w2;\n float v1, v2;\n if( strtk::parse( s, whitespace_and_punctuation, w1, v1, w2, v2) )\n {\n std::cout &lt;&lt; \"word \" &lt;&lt; w1 &lt;&lt; \", value \" &lt;&lt; v1 &lt;&lt; std::endl;\n std::cout &lt;&lt; \"word \" &lt;&lt; w2 &lt;&lt; \", value \" &lt;&lt; v2 &lt;&lt; std::endl;\n }\n }\n\n return 0;\n}\n</code></pre>\n\n<p>The toolkit has much more flexibility than this simple example shows but its utility in parsing a string into useful elements is incredible.</p>\n" }, { "answer_id": 22460128, "author": "robcsi", "author_id": 3257292, "author_profile": "https://Stackoverflow.com/users/3257292", "pm_score": 2, "selected": false, "text": "<p>I've been searching for a way to split a string by a separator of any length, so I started writing it from scratch, as existing solutions didn't suit me.</p>\n\n<p>Here is my little algorithm, using only STL:</p>\n\n<pre><code>//use like this\n//std::vector&lt;std::wstring&gt; vec = Split&lt;std::wstring&gt; (L\"Hello##world##!\", L\"##\");\n\ntemplate &lt;typename valueType&gt;\nstatic std::vector &lt;valueType&gt; Split (valueType text, const valueType&amp; delimiter)\n{\n std::vector &lt;valueType&gt; tokens;\n size_t pos = 0;\n valueType token;\n\n while ((pos = text.find(delimiter)) != valueType::npos) \n {\n token = text.substr(0, pos);\n tokens.push_back (token);\n text.erase(0, pos + delimiter.length());\n }\n tokens.push_back (text);\n\n return tokens;\n}\n</code></pre>\n\n<p>It can be used with separator of any length and form, as far as I've tested.\nInstantiate with either string or wstring type.</p>\n\n<p>All the algorithm does is it searches for the delimiter, gets the part of the string that is up to the delimiter, deletes the delimiter and searches again until it finds it no more.</p>\n\n<p>Of course, you can use any number of whitespaces for the delimiter.</p>\n\n<p>I hope it helps.</p>\n" }, { "answer_id": 22925061, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 2, "selected": false, "text": "<p>No Boost, no string streams, just the standard C library cooperating together with <code>std::string</code> and <code>std::list</code>: C library functions for easy analysis, C++ data types for easy memory management.</p>\n\n<p>Whitespace is considered to be any combination of newlines, tabs and spaces. The set of whitespace characters is established by the <code>wschars</code> variable.</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;list&gt;\n#include &lt;iostream&gt;\n#include &lt;cstring&gt;\n\nusing namespace std;\n\nconst char *wschars = \"\\t\\n \";\n\nlist&lt;string&gt; split(const string &amp;str)\n{\n const char *cstr = str.c_str();\n list&lt;string&gt; out;\n\n while (*cstr) { // while remaining string not empty\n size_t toklen;\n cstr += strspn(cstr, wschars); // skip leading whitespace\n toklen = strcspn(cstr, wschars); // figure out token length\n if (toklen) // if we have a token, add to list\n out.push_back(string(cstr, toklen));\n cstr += toklen; // skip over token\n }\n\n // ran out of string; return list\n\n return out;\n}\n\nint main(int argc, char **argv)\n{\n list&lt;string&gt; li = split(argv[1]);\n for (list&lt;string&gt;::iterator i = li.begin(); i != li.end(); i++)\n cout &lt;&lt; \"{\" &lt;&lt; *i &lt;&lt; \"}\" &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n\n<p>Run:</p>\n\n<pre><code>$ ./split \"\"\n$ ./split \"a\"\n{a}\n$ ./split \" a \"\n{a}\n$ ./split \" a b\"\n{a}\n{b}\n$ ./split \" a b c\"\n{a}\n{b}\n{c}\n$ ./split \" a b c d \"\n{a}\n{b}\n{c}\n{d}\n</code></pre>\n\n<p>Tail-recursive version of <code>split</code> (itself split into two functions). All destructive manipulation of variables is gone, except for the pushing of strings into the list!</p>\n\n<pre><code>void split_rec(const char *cstr, list&lt;string&gt; &amp;li)\n{\n if (*cstr) {\n const size_t leadsp = strspn(cstr, wschars);\n const size_t toklen = strcspn(cstr + leadsp, wschars);\n\n if (toklen)\n li.push_back(string(cstr + leadsp, toklen));\n\n split_rec(cstr + leadsp + toklen, li);\n }\n}\n\nlist&lt;string&gt; split(const string &amp;str)\n{\n list&lt;string&gt; out;\n split_rec(str.c_str(), out);\n return out;\n}\n</code></pre>\n" }, { "answer_id": 23486832, "author": "dk123", "author_id": 1709725, "author_profile": "https://Stackoverflow.com/users/1709725", "pm_score": 5, "selected": false, "text": "<p>Here's a simple solution that uses only the standard regex library</p>\n\n<pre><code>#include &lt;regex&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nstd::vector&lt;string&gt; Tokenize( const string str, const std::regex regex )\n{\n using namespace std;\n\n std::vector&lt;string&gt; result;\n\n sregex_token_iterator it( str.begin(), str.end(), regex, -1 );\n sregex_token_iterator reg_end;\n\n for ( ; it != reg_end; ++it ) {\n if ( !it-&gt;str().empty() ) //token could be empty:check\n result.emplace_back( it-&gt;str() );\n }\n\n return result;\n}\n</code></pre>\n\n<p>The regex argument allows checking for multiple arguments (spaces, commas, etc.)</p>\n\n<p>I usually only check to split on spaces and commas, so I also have this default function:</p>\n\n<pre><code>std::vector&lt;string&gt; TokenizeDefault( const string str )\n{\n using namespace std;\n\n regex re( \"[\\\\s,]+\" );\n\n return Tokenize( str, re );\n}\n</code></pre>\n\n<p>The <code>\"[\\\\s,]+\"</code> checks for spaces (<code>\\\\s</code>) and commas (<code>,</code>).</p>\n\n<p>Note, if you want to split <code>wstring</code> instead of <code>string</code>,</p>\n\n<ul>\n<li>change all <code>std::regex</code> to <code>std::wregex</code></li>\n<li>change all <code>sregex_token_iterator</code> to <code>wsregex_token_iterator</code></li>\n</ul>\n\n<p>Note, you might also want to take the string argument by reference, depending on your compiler.</p>\n" }, { "answer_id": 23776789, "author": "Khaled.K", "author_id": 2128327, "author_profile": "https://Stackoverflow.com/users/2128327", "pm_score": -1, "selected": false, "text": "<p>Here's my approach, cut and split:</p>\n\n<pre><code>string cut (string&amp; str, const string&amp; del)\n{\n string f = str;\n\n if (in.find_first_of(del) != string::npos)\n {\n f = str.substr(0,str.find_first_of(del));\n str = str.substr(str.find_first_of(del)+del.length());\n }\n\n return f;\n}\n\nvector&lt;string&gt; split (const string&amp; in, const string&amp; del=\" \")\n{\n vector&lt;string&gt; out();\n string t = in;\n\n while (t.length() &gt; del.length())\n out.push_back(cut(t,del));\n\n return out;\n}\n</code></pre>\n\n<p>BTW, if there's something I can do to optimize this ..</p>\n" }, { "answer_id": 24964916, "author": "tony gil", "author_id": 1166727, "author_profile": "https://Stackoverflow.com/users/1166727", "pm_score": 1, "selected": false, "text": "<pre><code>// adapted from a \"regular\" csv parse\nstd::string stringIn = \"my csv is 10233478 NOTseparated by commas\";\nstd::vector&lt;std::string&gt; commaSeparated(1);\nint commaCounter = 0;\nfor (int i=0; i&lt;stringIn.size(); i++) {\n if (stringIn[i] == \" \") {\n commaSeparated.push_back(\"\");\n commaCounter++;\n } else {\n commaSeparated.at(commaCounter) += stringIn[i];\n }\n}\n</code></pre>\n\n<p>in the end you will have a vector of strings with every element in the sentence separated by spaces. only non-standard resource is std::vector (but since an std::string is involved, i figured it would be acceptable).</p>\n\n<p>empty strings are saved as a separate items.</p>\n" }, { "answer_id": 25383354, "author": "mchiasson", "author_id": 1620670, "author_profile": "https://Stackoverflow.com/users/1620670", "pm_score": 2, "selected": false, "text": "<p>Here is my version</p>\n\n<pre><code>#include &lt;vector&gt;\n\ninline std::vector&lt;std::string&gt; Split(const std::string &amp;str, const std::string &amp;delim = \" \")\n{\n std::vector&lt;std::string&gt; tokens;\n if (str.size() &gt; 0)\n {\n if (delim.size() &gt; 0)\n {\n std::string::size_type currPos = 0, prevPos = 0;\n while ((currPos = str.find(delim, prevPos)) != std::string::npos)\n {\n std::string item = str.substr(prevPos, currPos - prevPos);\n if (item.size() &gt; 0)\n {\n tokens.push_back(item);\n }\n prevPos = currPos + 1;\n }\n tokens.push_back(str.substr(prevPos));\n }\n else\n {\n tokens.push_back(str);\n }\n }\n return tokens;\n}\n</code></pre>\n\n<p>It works with multi-character delimiters. It prevents empty tokens to get in your results. It uses a single header. It returns the string as one single token when you provide no delimiter. It also returns an empty result if the string is empty. It is unfortunately inefficient because of the huge <code>std::vector</code> copy <em>UNLESS</em> you are compiling using C++11, which should be using the move schematic. In C++11, this code should be fast.</p>\n" }, { "answer_id": 27125803, "author": "Galik", "author_id": 3807729, "author_profile": "https://Stackoverflow.com/users/3807729", "pm_score": 3, "selected": false, "text": "<p>Here is my solution using <strong>C++11</strong> and the <strong>STL</strong>. It should be reasonably efficient:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;cstring&gt;\n#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;functional&gt;\n\nstd::vector&lt;std::string&gt; split(const std::string&amp; s)\n{\n std::vector&lt;std::string&gt; v;\n\n const auto end = s.end();\n auto to = s.begin();\n decltype(to) from;\n\n while((from = std::find_if(to, end,\n [](char c){ return !std::isspace(c); })) != end)\n {\n to = std::find_if(from, end, [](char c){ return std::isspace(c); });\n v.emplace_back(from, to);\n }\n\n return v;\n}\n\nint main()\n{\n std::string s = \"this is the string to split\";\n\n auto v = split(s);\n\n for(auto&amp;&amp; s: v)\n std::cout &lt;&lt; s &lt;&lt; '\\n';\n}\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>this\nis\nthe\nstring\nto\nsplit\n</code></pre>\n" }, { "answer_id": 27512317, "author": "Richard Hodges", "author_id": 2015579, "author_profile": "https://Stackoverflow.com/users/2015579", "pm_score": 0, "selected": false, "text": "<p>very late to the party here I know but I was thinking about the most elegant way of doing this if you were given a range of delimiters rather than whitespace, and using nothing more than the standard library.</p>\n\n<p>Here are my thoughts:</p>\n\n<p>To split words into a string vector by a sequence of delimiters:</p>\n\n<pre><code>template&lt;class Container&gt;\nstd::vector&lt;std::string&gt; split_by_delimiters(const std::string&amp; input, const Container&amp; delimiters)\n{\n std::vector&lt;std::string&gt; result;\n\n for (auto current = begin(input) ; current != end(input) ; )\n {\n auto first = find_if(current, end(input), not_in(delimiters));\n if (first == end(input)) break;\n auto last = find_if(first, end(input), is_in(delimiters));\n result.emplace_back(first, last);\n current = last;\n }\n return result;\n}\n</code></pre>\n\n<p>to split the other way, by providing a sequence of valid characters:</p>\n\n<pre><code>template&lt;class Container&gt;\nstd::vector&lt;std::string&gt; split_by_valid_chars(const std::string&amp; input, const Container&amp; valid_chars)\n{\n std::vector&lt;std::string&gt; result;\n\n for (auto current = begin(input) ; current != end(input) ; )\n {\n auto first = find_if(current, end(input), is_in(valid_chars));\n if (first == end(input)) break;\n auto last = find_if(first, end(input), not_in(valid_chars));\n result.emplace_back(first, last);\n current = last;\n }\n return result;\n}\n</code></pre>\n\n<p>is_in and not_in are defined thus:</p>\n\n<pre><code>namespace detail {\n template&lt;class Container&gt;\n struct is_in {\n is_in(const Container&amp; charset)\n : _charset(charset)\n {}\n\n bool operator()(char c) const\n {\n return find(begin(_charset), end(_charset), c) != end(_charset);\n }\n\n const Container&amp; _charset;\n };\n\n template&lt;class Container&gt;\n struct not_in {\n not_in(const Container&amp; charset)\n : _charset(charset)\n {}\n\n bool operator()(char c) const\n {\n return find(begin(_charset), end(_charset), c) == end(_charset);\n }\n\n const Container&amp; _charset;\n };\n\n}\n\ntemplate&lt;class Container&gt;\ndetail::not_in&lt;Container&gt; not_in(const Container&amp; c)\n{\n return detail::not_in&lt;Container&gt;(c);\n}\n\ntemplate&lt;class Container&gt;\ndetail::is_in&lt;Container&gt; is_in(const Container&amp; c)\n{\n return detail::is_in&lt;Container&gt;(c);\n}\n</code></pre>\n" }, { "answer_id": 27556071, "author": "Dietmar Kühl", "author_id": 1120273, "author_profile": "https://Stackoverflow.com/users/1120273", "pm_score": 3, "selected": false, "text": "<p>When dealing with whitespace as separator, the obvious answer of using <code>std::istream_iterator&lt;T&gt;</code> is already given and voted up a lot. Of course, elements may not be separated by whitespace but by some separator instead. I didn't spot any answer which just redefines the meaning of whitespace to be said separator and then uses the conventional approach.</p>\n\n<p>The way to change what streams consider whitespace, you'd simply change the stream's <code>std::locale</code> using (<code>std::istream::imbue()</code>) with a <code>std::ctype&lt;char&gt;</code> facet with its own definition of what whitespace means (it can be done for <code>std::ctype&lt;wchar_t&gt;</code>, too, but its is actually slightly different because <code>std::ctype&lt;char&gt;</code> is table-driven while <code>std::ctype&lt;wchar_t&gt;</code> is driven by virtual functions).</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;sstream&gt;\n#include &lt;locale&gt;\n\nstruct whitespace_mask {\n std::ctype_base::mask mask_table[std::ctype&lt;char&gt;::table_size];\n whitespace_mask(std::string const&amp; spaces) {\n std::ctype_base::mask* table = this-&gt;mask_table;\n std::ctype_base::mask const* tab\n = std::use_facet&lt;std::ctype&lt;char&gt;&gt;(std::locale()).table();\n for (std::size_t i(0); i != std::ctype&lt;char&gt;::table_size; ++i) {\n table[i] = tab[i] &amp; ~std::ctype_base::space;\n }\n std::for_each(spaces.begin(), spaces.end(), [=](unsigned char c) {\n table[c] |= std::ctype_base::space;\n });\n }\n};\nclass whitespace_facet\n : private whitespace_mask\n , public std::ctype&lt;char&gt; {\npublic:\n whitespace_facet(std::string const&amp; spaces)\n : whitespace_mask(spaces)\n , std::ctype&lt;char&gt;(this-&gt;mask_table) {\n }\n};\n\nstruct whitespace {\n std::string spaces;\n whitespace(std::string const&amp; spaces): spaces(spaces) {}\n};\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; in, whitespace const&amp; ws) {\n std::locale loc(in.getloc(), new whitespace_facet(ws.spaces));\n in.imbue(loc);\n return in;\n}\n// everything above would probably go into a utility library...\n\nint main() {\n std::istringstream in(\"a, b, c, d, e\");\n std::copy(std::istream_iterator&lt;std::string&gt;(in &gt;&gt; whitespace(\", \")),\n std::istream_iterator&lt;std::string&gt;(),\n std::ostream_iterator&lt;std::string&gt;(std::cout, \"\\n\"));\n\n std::istringstream pipes(\"a b c| d |e e\");\n std::copy(std::istream_iterator&lt;std::string&gt;(pipes &gt;&gt; whitespace(\"|\")),\n std::istream_iterator&lt;std::string&gt;(),\n std::ostream_iterator&lt;std::string&gt;(std::cout, \"\\n\")); \n}\n</code></pre>\n\n<p>Most of the code is for packaging up a general purpose tool providing <em>soft delimiters</em>: multiple delimiters in a row are merged. There is no way to produce an empty sequence. When different delimiters are needed within a stream, you'd probably use differently set up streams using a shared stream buffer:</p>\n\n<pre><code>void f(std::istream&amp; in) {\n std::istream pipes(in.rdbuf());\n pipes &gt;&gt; whitespace(\"|\");\n std::istream comma(in.rdbuf());\n comma &gt;&gt; whitespace(\",\");\n\n std::string s0, s1;\n if (pipes &gt;&gt; s0 &gt;&gt; std::ws // read up to first pipe and ignore sequence of pipes\n &amp;&amp; comma &gt;&gt; s1 &gt;&gt; std::ws) { // read up to first comma and ignore commas\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 29007199, "author": "Kakashi", "author_id": 2049325, "author_profile": "https://Stackoverflow.com/users/2049325", "pm_score": 0, "selected": false, "text": "<p>Thank you @Jairo Abdiel Toribio Cisneros. It works for me but your function return some empty element. So for return without empty I have edited with the following:</p>\n\n<pre><code>std::vector&lt;std::string&gt; split(std::string str, const char* delim) {\n std::vector&lt;std::string&gt; v;\n std::string tmp;\n\n for(std::string::const_iterator i = str.begin(); i &lt;= str.end(); ++i) {\n if(*i != *delim &amp;&amp; i != str.end()) {\n tmp += *i;\n } else {\n if (tmp.length() &gt; 0) {\n v.push_back(tmp);\n }\n tmp = \"\";\n }\n }\n\n return v;\n}\n</code></pre>\n\n<p>Using:</p>\n\n<pre><code>std::string s = \"one:two::three\";\nstd::string delim = \":\";\nstd::vector&lt;std::string&gt; vv = split(s, delim.c_str());\n</code></pre>\n" }, { "answer_id": 30619990, "author": "Venkata Naidu M", "author_id": 2119671, "author_profile": "https://Stackoverflow.com/users/2119671", "pm_score": 2, "selected": false, "text": "<p>We can use strtok in c++ ,</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cstring&gt;\nusing namespace std;\n\nint main()\n{\n char str[]=\"Mickey M;12034;911416313;M;01a;9001;NULL;0;13;12;0;CPP,C;MSC,3D;FEND,BEND,SEC;\";\n char *pch = strtok (str,\";,\");\n while (pch != NULL)\n {\n cout&lt;&lt;pch&lt;&lt;\"\\n\";\n pch = strtok (NULL, \";,\");\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 31170110, "author": "abe312", "author_id": 3719699, "author_profile": "https://Stackoverflow.com/users/3719699", "pm_score": -1, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;vector&gt;\n\nint main() {\n using namespace std;\n int n=8;\n string sentence = \"10 20 30 40 5 6 7 8\";\n istringstream iss(sentence);\n\n vector&lt;string&gt; tokens;\ncopy(istream_iterator&lt;string&gt;(iss),\n istream_iterator&lt;string&gt;(),\n back_inserter(tokens));\n\n for(int i=0;i&lt;n;i++){\n cout&lt;&lt;tokens.at(i);\n }\n\n\n}\n</code></pre>\n" }, { "answer_id": 32356675, "author": "Jehjoa", "author_id": 365908, "author_profile": "https://Stackoverflow.com/users/365908", "pm_score": 3, "selected": false, "text": "<p>As a hobbyist, this is the first solution that came to my mind. I'm kind of curious why I haven't seen a similar solution here yet, is there something fundamentally wrong with how I did it?</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nstd::vector&lt;std::string&gt; split(const std::string &amp;s, const std::string &amp;delims)\n{\n std::vector&lt;std::string&gt; result;\n std::string::size_type pos = 0;\n while (std::string::npos != (pos = s.find_first_not_of(delims, pos))) {\n auto pos2 = s.find_first_of(delims, pos);\n result.emplace_back(s.substr(pos, std::string::npos == pos2 ? pos2 : pos2 - pos));\n pos = pos2;\n }\n return result;\n}\n\nint main()\n{\n std::string text{\"And then I said: \\\"I don't get it, why would you even do that!?\\\"\"};\n std::string delims{\" :;\\\".,?!\"};\n auto words = split(text, delims);\n std::cout &lt;&lt; \"\\nSentence:\\n \" &lt;&lt; text &lt;&lt; \"\\n\\nWords:\";\n for (const auto &amp;w : words) {\n std::cout &lt;&lt; \"\\n \" &lt;&lt; w;\n }\n return 0;\n}\n</code></pre>\n\n<p><a href=\"http://cpp.sh/7wmzy\" rel=\"noreferrer\">http://cpp.sh/7wmzy</a></p>\n" }, { "answer_id": 32920320, "author": "Tristan Brindle", "author_id": 2797826, "author_profile": "https://Stackoverflow.com/users/2797826", "pm_score": 2, "selected": false, "text": "<p>Here's my entry:</p>\n\n<pre><code>template &lt;typename Container, typename InputIter, typename ForwardIter&gt;\nContainer\nsplit(InputIter first, InputIter last,\n ForwardIter s_first, ForwardIter s_last)\n{\n Container output;\n\n while (true) {\n auto pos = std::find_first_of(first, last, s_first, s_last);\n output.emplace_back(first, pos);\n if (pos == last) {\n break;\n }\n\n first = ++pos;\n }\n\n return output;\n}\n\ntemplate &lt;typename Output = std::vector&lt;std::string&gt;,\n typename Input = std::string,\n typename Delims = std::string&gt;\nOutput\nsplit(const Input&amp; input, const Delims&amp; delims = \" \")\n{\n using std::cbegin;\n using std::cend;\n return split&lt;Output&gt;(cbegin(input), cend(input),\n cbegin(delims), cend(delims));\n}\n\nauto vec = split(\"Mary had a little lamb\");\n</code></pre>\n\n<p>The first definition is an STL-style generic function taking two pair of iterators. The second is a convenience function to save you having to do all the <code>begin()</code>s and <code>end()</code>s yourself. You can also specify the output container type as a template parameter if you wanted to use a <code>list</code>, for example.</p>\n\n<p>What makes it elegant (IMO) is that unlike most of the other answers, it's not restricted to strings but will work with any STL-compatible container. Without any change to the code above, you can say:</p>\n\n<pre><code>using vec_of_vecs_t = std::vector&lt;std::vector&lt;int&gt;&gt;;\n\nstd::vector&lt;int&gt; v{1, 2, 0, 3, 4, 5, 0, 7, 8, 0, 9};\nauto r = split&lt;vec_of_vecs_t&gt;(v, std::initializer_list&lt;int&gt;{0, 2});\n</code></pre>\n\n<p>which will split the vector <code>v</code> into separate vectors every time a <code>0</code> or a <code>2</code> is encountered.</p>\n\n<p>(There's also the added bonus that with strings, this implementation is faster than both <code>strtok()</code>- and <code>getline()</code>-based versions, at least on my system.)</p>\n" }, { "answer_id": 33287535, "author": "Bushuev", "author_id": 5457601, "author_profile": "https://Stackoverflow.com/users/5457601", "pm_score": 0, "selected": false, "text": "<p>if you want split string by some chars you can use</p>\n\n<pre><code>#include&lt;iostream&gt;\n#include&lt;string&gt;\n#include&lt;vector&gt;\n#include&lt;iterator&gt;\n#include&lt;sstream&gt;\n#include&lt;string&gt;\n\nusing namespace std;\nvoid replaceOtherChars(string &amp;input, vector&lt;char&gt; &amp;dividers)\n{\n const char divider = dividers.at(0);\n int replaceIndex = 0;\n vector&lt;char&gt;::iterator it_begin = dividers.begin()+1,\n it_end= dividers.end();\n for(;it_begin!=it_end;++it_begin)\n {\n replaceIndex = 0;\n while(true)\n {\n replaceIndex=input.find_first_of(*it_begin,replaceIndex);\n if(replaceIndex==-1)\n break;\n input.at(replaceIndex)=divider;\n }\n }\n}\nvector&lt;string&gt; split(string str, vector&lt;char&gt; chars, bool missEmptySpace =true )\n{\n vector&lt;string&gt; result;\n const char divider = chars.at(0);\n replaceOtherChars(str,chars);\n stringstream stream;\n stream&lt;&lt;str; \n string temp;\n while(getline(stream,temp,divider))\n {\n if(missEmptySpace &amp;&amp; temp.empty())\n continue;\n result.push_back(temp);\n }\n return result;\n}\nint main()\n{\n string str =\"milk, pigs.... hot-dogs \";\n vector&lt;char&gt; arr;\n arr.push_back(' '); arr.push_back(','); arr.push_back('.');\n vector&lt;string&gt; result = split(str,arr);\n vector&lt;string&gt;::iterator it_begin= result.begin(),\n it_end= result.end();\n for(;it_begin!=it_end;++it_begin)\n {\n cout&lt;&lt;*it_begin&lt;&lt;endl;\n }\nreturn 0;\n}\n</code></pre>\n" }, { "answer_id": 33404623, "author": "Jonny", "author_id": 129202, "author_profile": "https://Stackoverflow.com/users/129202", "pm_score": 0, "selected": false, "text": "<p>This is an extension of one of the top answers. It now supports setting a max number of returned elements, N. The last bit of the string will end up in the Nth element. The MAXELEMENTS parameter is optional, if set at default 0 it will return an <em>unlimited</em> amount of elements. :-)</p>\n\n<p>.h:</p>\n\n<pre><code>class Myneatclass {\npublic:\n static std::vector&lt;std::string&gt;&amp; split(const std::string &amp;s, char delim, std::vector&lt;std::string&gt; &amp;elems, const size_t MAXELEMENTS = 0);\n static std::vector&lt;std::string&gt; split(const std::string &amp;s, char delim, const size_t MAXELEMENTS = 0);\n};\n</code></pre>\n\n<p>.cpp:</p>\n\n<pre><code>std::vector&lt;std::string&gt;&amp; Myneatclass::split(const std::string &amp;s, char delim, std::vector&lt;std::string&gt; &amp;elems, const size_t MAXELEMENTS) {\n std::stringstream ss(s);\n std::string item;\n while (std::getline(ss, item, delim)) {\n elems.push_back(item);\n if (MAXELEMENTS &gt; 0 &amp;&amp; !ss.eof() &amp;&amp; elems.size() + 1 &gt;= MAXELEMENTS) {\n std::getline(ss, item);\n elems.push_back(item);\n break;\n }\n }\n return elems;\n}\nstd::vector&lt;std::string&gt; Myneatclass::split(const std::string &amp;s, char delim, const size_t MAXELEMENTS) {\n std::vector&lt;std::string&gt; elems;\n split(s, delim, elems, MAXELEMENTS);\n return elems;\n}\n</code></pre>\n" }, { "answer_id": 33480125, "author": "user1438233", "author_id": 1438233, "author_profile": "https://Stackoverflow.com/users/1438233", "pm_score": 4, "selected": false, "text": "<p>Short and elegant</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nvector&lt;string&gt; split(string data, string token)\n{\n vector&lt;string&gt; output;\n size_t pos = string::npos; // size_t to avoid improbable overflow\n do\n {\n pos = data.find(token);\n output.push_back(data.substr(0, pos));\n if (string::npos != pos)\n data = data.substr(pos + token.size());\n } while (string::npos != pos);\n return output;\n}\n</code></pre>\n\n<p>can use any string as delimiter, also can be used with binary data (std::string supports binary data, including nulls)</p>\n\n<p>using:</p>\n\n<pre><code>auto a = split(\"this!!is!!!example!string\", \"!!\");\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>this\nis\n!example!string\n</code></pre>\n" }, { "answer_id": 34703527, "author": "torayeff", "author_id": 1385385, "author_profile": "https://Stackoverflow.com/users/1385385", "pm_score": 1, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\nusing namespace std;\n\nint main() {\n string str = \"ABC AABCD CDDD RABC GHTTYU FR\";\n str += \" \"; //dirty hack: adding extra space to the end\n vector&lt;string&gt; v;\n\n for (int i=0; i&lt;(int)str.size(); i++) {\n int a, b;\n a = i;\n\n for (int j=i; j&lt;(int)str.size(); j++) {\n if (str[j] == ' ') {\n b = j;\n i = j;\n break;\n }\n }\n v.push_back(str.substr(a, b-a));\n }\n\n for (int i=0; i&lt;v.size(); i++) {\n cout&lt;&lt;v[i].size()&lt;&lt;\" \"&lt;&lt;v[i]&lt;&lt;endl;\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 34705440, "author": "AlwaysLearning", "author_id": 2725810, "author_profile": "https://Stackoverflow.com/users/2725810", "pm_score": 1, "selected": false, "text": "<p>Just for convenience:</p>\n\n<pre><code>template&lt;class V, typename T&gt;\nbool in(const V &amp;v, const T &amp;el) {\n return std::find(v.begin(), v.end(), el) != v.end();\n}\n</code></pre>\n\n<p>The actual splitting based on multiple delimiters:</p>\n\n<pre><code>std::vector&lt;std::string&gt; split(const std::string &amp;s,\n const std::vector&lt;char&gt; &amp;delims) {\n std::vector&lt;std::string&gt; res;\n auto stuff = [&amp;delims](char c) { return !in(delims, c); };\n auto space = [&amp;delims](char c) { return in(delims, c); };\n auto first = std::find_if(s.begin(), s.end(), stuff);\n while (first != s.end()) {\n auto last = std::find_if(first, s.end(), space);\n res.push_back(std::string(first, last));\n first = std::find_if(last + 1, s.end(), stuff);\n }\n return res;\n}\n</code></pre>\n\n<p>The usage:</p>\n\n<pre><code>int main() {\n std::string s = \" aaa, bb cc \";\n for (auto el: split(s, {' ', ','}))\n std::cout &lt;&lt; el &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 36739701, "author": "yunhasnawa", "author_id": 1179484, "author_profile": "https://Stackoverflow.com/users/1179484", "pm_score": 2, "selected": false, "text": "<p>For those who need alternative in splitting string with a string delimiter, perhaps you can try my following solution.</p>\n\n<pre><code>std::vector&lt;size_t&gt; str_pos(const std::string &amp;search, const std::string &amp;target)\n{\n std::vector&lt;size_t&gt; founds;\n\n if(!search.empty())\n {\n size_t start_pos = 0;\n\n while (true)\n {\n size_t found_pos = target.find(search, start_pos);\n\n if(found_pos != std::string::npos)\n {\n size_t found = found_pos;\n\n founds.push_back(found);\n\n start_pos = (found_pos + 1);\n }\n else\n {\n break;\n }\n }\n }\n\n return founds;\n}\n\nstd::string str_sub_index(size_t begin_index, size_t end_index, const std::string &amp;target)\n{\n std::string sub;\n\n size_t size = target.length();\n\n const char* copy = target.c_str();\n\n for(size_t i = begin_index; i &lt;= end_index; i++)\n {\n if(i &gt;= size)\n {\n break;\n }\n else\n {\n char c = copy[i];\n\n sub += c;\n }\n }\n\n return sub;\n}\n\nstd::vector&lt;std::string&gt; str_split(const std::string &amp;delimiter, const std::string &amp;target)\n{\n std::vector&lt;std::string&gt; splits;\n\n if(!delimiter.empty())\n {\n std::vector&lt;size_t&gt; founds = str_pos(delimiter, target);\n\n size_t founds_size = founds.size();\n\n if(founds_size &gt; 0)\n {\n size_t search_len = delimiter.length();\n\n size_t begin_index = 0;\n\n for(int i = 0; i &lt;= founds_size; i++)\n {\n std::string sub;\n\n if(i != founds_size)\n {\n size_t pos = founds.at(i);\n\n sub = str_sub_index(begin_index, pos - 1, target);\n\n begin_index = (pos + search_len);\n }\n else\n {\n sub = str_sub_index(begin_index, (target.length() - 1), target);\n }\n\n splits.push_back(sub);\n }\n }\n }\n\n return splits;\n}\n</code></pre>\n\n<p>Those snippets consist of 3 function. The bad news is to use the <code>str_split</code> function you will need the other two functions. Yes it is a huge chunk of code. But the good news is that those additional two functions are able to work independently and sometimes can be useful too.. :)</p>\n\n<p>Tested the function in <code>main()</code> block like this:</p>\n\n<pre><code>int main()\n{\n std::string s = \"Hello, world! We need to make the world a better place. Because your world is also my world, and our children's world.\";\n\n std::vector&lt;std::string&gt; split = str_split(\"world\", s);\n\n for(int i = 0; i &lt; split.size(); i++)\n {\n std::cout &lt;&lt; split[i] &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<p>And it would produce:</p>\n\n<pre><code>Hello, \n! We need to make the \n a better place. Because your \n is also my \n, and our children's \n.\n</code></pre>\n\n<p>I believe that's not the most efficient code, but at least it works. Hope it helps.</p>\n" }, { "answer_id": 39334298, "author": "pz64_", "author_id": 6737471, "author_profile": "https://Stackoverflow.com/users/6737471", "pm_score": 2, "selected": false, "text": "<p>This is my solution to this problem:</p>\n\n<pre><code>vector&lt;string&gt; get_tokens(string str) {\n vector&lt;string&gt; dt;\n stringstream ss;\n string tmp; \n ss &lt;&lt; str;\n for (size_t i; !ss.eof(); ++i) {\n ss &gt;&gt; tmp;\n dt.push_back(tmp);\n }\n return dt;\n}\n</code></pre>\n\n<p>This function returns a vector of strings.</p>\n" }, { "answer_id": 39359311, "author": "solstice333", "author_id": 2630028, "author_profile": "https://Stackoverflow.com/users/2630028", "pm_score": 3, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;regex&gt;\n\nusing namespace std;\n\nint main() {\n string s = \"foo bar baz\";\n regex e(\"\\\\s+\");\n regex_token_iterator&lt;string::iterator&gt; i(s.begin(), s.end(), e, -1);\n regex_token_iterator&lt;string::iterator&gt; end;\n while (i != end)\n cout &lt;&lt; \" [\" &lt;&lt; *i++ &lt;&lt; \"]\";\n}\n</code></pre>\n\n<p>IMO, this is the closest thing to python's re.split(). See <a href=\"http://www.cplusplus.com/reference/regex/regex_token_iterator/regex_token_iterator/\" rel=\"noreferrer\">cplusplus.com</a> for more information about regex_token_iterator. The -1 (4th argument in regex_token_iterator ctor) is the section of the sequence that is not matched, using the match as separator.</p>\n" }, { "answer_id": 39428548, "author": "Saksham Sharma", "author_id": 2928458, "author_profile": "https://Stackoverflow.com/users/2928458", "pm_score": 2, "selected": false, "text": "<p>Here's my take on this. I had to process the input string word by word, which could have been done by using space to count words but I felt it would be tedious and I should split the words into vectors. </p>\n\n<pre><code>#include&lt;iostream&gt;\n#include&lt;vector&gt;\n#include&lt;string&gt;\n#include&lt;stdio.h&gt;\nusing namespace std;\nint main()\n{\n char x = '\\0';\n string s = \"\";\n vector&lt;string&gt; q;\n x = getchar();\n while(x != '\\n')\n {\n if(x == ' ')\n {\n q.push_back(s);\n s = \"\";\n x = getchar();\n continue;\n }\n s = s + x;\n x = getchar();\n }\n q.push_back(s);\n for(int i = 0; i&lt;q.size(); i++)\n cout&lt;&lt;q[i]&lt;&lt;\" \";\n return 0;\n}\n</code></pre>\n\n<ol>\n<li>Doesn't take care of multiple spaces.</li>\n<li>If the last word is not immediately followed by newline character, it includes the whitespace between the last word's last character and newline character.</li>\n</ol>\n" }, { "answer_id": 43999194, "author": "Timmmm", "author_id": 265521, "author_profile": "https://Stackoverflow.com/users/265521", "pm_score": 2, "selected": false, "text": "<p>Based on <a href=\"https://stackoverflow.com/a/27125803/265521\">Galik's answer</a> I made this. This is mostly here so I don't have to keep writing it again and again. It's crazy that C++ still doesn't have a native split function. Features:</p>\n\n<ul>\n<li>Should be very fast.</li>\n<li>Easy to understand (I think).</li>\n<li>Merges empty sections.</li>\n<li>Trivial to use several delimiters (e.g. <code>\"\\r\\n\"</code>)</li>\n</ul>\n\n\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nstd::vector&lt;std::string&gt; split(const std::string&amp; s, const std::string&amp; delims)\n{\n using namespace std;\n\n vector&lt;string&gt; v;\n\n // Start of an element.\n size_t elemStart = 0;\n\n // We start searching from the end of the previous element, which\n // initially is the start of the string.\n size_t elemEnd = 0;\n\n // Find the first non-delim, i.e. the start of an element, after the end of the previous element.\n while((elemStart = s.find_first_not_of(delims, elemEnd)) != string::npos)\n {\n // Find the first delem, i.e. the end of the element (or if this fails it is the end of the string).\n elemEnd = s.find_first_of(delims, elemStart);\n // Add it.\n v.emplace_back(s, elemStart, elemEnd == string::npos ? string::npos : elemEnd - elemStart);\n }\n // When there are no more non-spaces, we are done.\n\n return v;\n}\n</code></pre>\n" }, { "answer_id": 44246368, "author": "小文件", "author_id": 4869018, "author_profile": "https://Stackoverflow.com/users/4869018", "pm_score": 0, "selected": false, "text": "<p>my general implementation for <code>string</code> and <code>u32string</code> ~, using the <code>boost::algorithm::split</code> signature.</p>\n\n<pre><code>template&lt;typename CharT, typename UnaryPredicate&gt;\nvoid split(std::vector&lt;std::basic_string&lt;CharT&gt;&gt;&amp; split_result,\n const std::basic_string&lt;CharT&gt;&amp; s,\n UnaryPredicate predicate)\n{\n using ST = std::basic_string&lt;CharT&gt;;\n using std::swap;\n std::vector&lt;ST&gt; tmp_result;\n auto iter = s.cbegin(),\n end_iter = s.cend();\n while (true)\n {\n /**\n * edge case: empty str -&gt; push an empty str and exit.\n */\n auto find_iter = find_if(iter, end_iter, predicate);\n tmp_result.emplace_back(iter, find_iter);\n if (find_iter == end_iter) { break; }\n iter = ++find_iter; \n }\n swap(tmp_result, split_result);\n}\n\n\ntemplate&lt;typename CharT&gt;\nvoid split(std::vector&lt;std::basic_string&lt;CharT&gt;&gt;&amp; split_result,\n const std::basic_string&lt;CharT&gt;&amp; s,\n const std::basic_string&lt;CharT&gt;&amp; char_candidate)\n{\n std::unordered_set&lt;CharT&gt; candidate_set(char_candidate.cbegin(),\n char_candidate.cend());\n auto predicate = [&amp;candidate_set](const CharT&amp; c) {\n return candidate_set.count(c) &gt; 0U;\n };\n return split(split_result, s, predicate);\n}\n\ntemplate&lt;typename CharT&gt;\nvoid split(std::vector&lt;std::basic_string&lt;CharT&gt;&gt;&amp; split_result,\n const std::basic_string&lt;CharT&gt;&amp; s,\n const CharT* literals)\n{\n return split(split_result, s, std::basic_string&lt;CharT&gt;(literals));\n}\n</code></pre>\n" }, { "answer_id": 44294208, "author": "Romário", "author_id": 2507567, "author_profile": "https://Stackoverflow.com/users/2507567", "pm_score": 2, "selected": false, "text": "<p>Yes, I looked through all 30 examples.</p>\n\n<p>I couldn't find a version of <code>split</code> that works for multi-char delimiters, so here's mine: </p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n\nusing namespace std;\n\nvector&lt;string&gt; split(const string &amp;str, const string &amp;delim)\n{ \n const auto delim_pos = str.find(delim);\n\n if (delim_pos == string::npos)\n return {str};\n\n vector&lt;string&gt; ret{str.substr(0, delim_pos)};\n auto tail = split(str.substr(delim_pos + delim.size(), string::npos), delim);\n\n ret.insert(ret.end(), tail.begin(), tail.end());\n\n return ret;\n}\n</code></pre>\n\n<p>Probably not the most efficient of implementations, but it's a very straightforward recursive solution, using only <code>&lt;string&gt;</code> and <code>&lt;vector&gt;</code>.</p>\n\n<p>Ah, it's written in C++11, but there's nothing special about this code, so you could easily adapt it to C++98.</p>\n" }, { "answer_id": 44776084, "author": "Joakim L. Christiansen", "author_id": 4216153, "author_profile": "https://Stackoverflow.com/users/4216153", "pm_score": -1, "selected": false, "text": "<p>Not that we need more answers, but this is what I came up with after being inspired by Evan Teran. </p>\n\n<pre><code>std::vector &lt;std::string&gt; split(const string &amp;input, auto delimiter, bool skipEmpty=true) {\n /*\n Splits a string at each delimiter and returns these strings as a string vector.\n If the delimiter is not found then nothing is returned.\n If skipEmpty is true then strings between delimiters that are 0 in length will be skipped.\n */\n bool delimiterFound = false;\n int pos=0, pPos=0;\n std::vector &lt;std::string&gt; result;\n while (true) {\n pos = input.find(delimiter,pPos);\n if (pos != std::string::npos) {\n if (skipEmpty==false or pos-pPos &gt; 0) // if empty values are to be kept or not\n result.push_back(input.substr(pPos,pos-pPos));\n delimiterFound = true;\n } else {\n if (pPos &lt; input.length() and delimiterFound) {\n if (skipEmpty==false or input.length()-pPos &gt; 0) // if empty values are to be kept or not\n result.push_back(input.substr(pPos,input.length()-pPos));\n }\n break;\n }\n pPos = pos+1;\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 47473248, "author": "Oleg", "author_id": 8766845, "author_profile": "https://Stackoverflow.com/users/8766845", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;deque&gt;\n\nstd::deque&lt;std::string&gt; split(\n const std::string&amp; line, \n std::string::value_type delimiter,\n bool skipEmpty = false\n) {\n std::deque&lt;std::string&gt; parts{};\n\n if (!skipEmpty &amp;&amp; !line.empty() &amp;&amp; delimiter == line.at(0)) {\n parts.push_back({});\n }\n\n for (const std::string::value_type&amp; c : line) {\n if (\n (\n c == delimiter \n &amp;&amp;\n (skipEmpty ? (!parts.empty() &amp;&amp; !parts.back().empty()) : true)\n )\n ||\n (c != delimiter &amp;&amp; parts.empty())\n ) {\n parts.push_back({});\n }\n\n if (c != delimiter) {\n parts.back().push_back(c);\n }\n }\n\n if (skipEmpty &amp;&amp; !parts.empty() &amp;&amp; parts.back().empty()) {\n parts.pop_back();\n }\n\n return parts;\n}\n\nvoid test(const std::string&amp; line) {\n std::cout &lt;&lt; line &lt;&lt; std::endl;\n\n std::cout &lt;&lt; \"skipEmpty=0 |\";\n for (const std::string&amp; part : split(line, ':')) {\n std::cout &lt;&lt; part &lt;&lt; '|';\n }\n std::cout &lt;&lt; std::endl;\n\n std::cout &lt;&lt; \"skipEmpty=1 |\";\n for (const std::string&amp; part : split(line, ':', true)) {\n std::cout &lt;&lt; part &lt;&lt; '|';\n }\n std::cout &lt;&lt; std::endl;\n\n std::cout &lt;&lt; std::endl;\n}\n\nint main() {\n test(\"foo:bar:::baz\");\n test(\"\");\n test(\"foo\");\n test(\":\");\n test(\"::\");\n test(\":foo\");\n test(\"::foo\");\n test(\":foo:\");\n test(\":foo::\");\n\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>foo:bar:::baz\nskipEmpty=0 |foo|bar|||baz|\nskipEmpty=1 |foo|bar|baz|\n\n\nskipEmpty=0 |\nskipEmpty=1 |\n\nfoo\nskipEmpty=0 |foo|\nskipEmpty=1 |foo|\n\n:\nskipEmpty=0 |||\nskipEmpty=1 |\n\n::\nskipEmpty=0 ||||\nskipEmpty=1 |\n\n:foo\nskipEmpty=0 ||foo|\nskipEmpty=1 |foo|\n\n::foo\nskipEmpty=0 |||foo|\nskipEmpty=1 |foo|\n\n:foo:\nskipEmpty=0 ||foo||\nskipEmpty=1 |foo|\n\n:foo::\nskipEmpty=0 ||foo|||\nskipEmpty=1 |foo|\n</code></pre>\n" }, { "answer_id": 47733270, "author": "NL628", "author_id": 8925851, "author_profile": "https://Stackoverflow.com/users/8925851", "pm_score": 4, "selected": false, "text": "<p>This answer takes the string and puts it into a vector of strings. It uses the boost library.</p>\n\n<pre><code>#include &lt;boost/algorithm/string.hpp&gt;\nstd::vector&lt;std::string&gt; strs;\nboost::split(strs, \"string to split\", boost::is_any_of(\"\\t \"));\n</code></pre>\n" }, { "answer_id": 54134243, "author": "Porsche9II", "author_id": 1683850, "author_profile": "https://Stackoverflow.com/users/1683850", "pm_score": 4, "selected": false, "text": "<p>Using <code>std::string_view</code> and Eric Niebler's <code>range-v3</code> library:</p>\n\n<p><a href=\"https://wandbox.org/permlink/kW5lwRCL1pxjp2pW\" rel=\"noreferrer\">https://wandbox.org/permlink/kW5lwRCL1pxjp2pW</a></p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;string_view&gt;\n#include \"range/v3/view.hpp\"\n#include \"range/v3/algorithm.hpp\"\n\nint main() {\n std::string s = \"Somewhere down the range v3 library\";\n ranges::for_each(s \n | ranges::view::split(' ')\n | ranges::view::transform([](auto &amp;&amp;sub) {\n return std::string_view(&amp;*sub.begin(), ranges::distance(sub));\n }),\n [](auto s) {std::cout &lt;&lt; \"Substring: \" &lt;&lt; s &lt;&lt; \"\\n\";}\n );\n}\n</code></pre>\n\n<p>By using a range <code>for</code> loop instead of <code>ranges::for_each</code> algorithm:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;string_view&gt;\n#include \"range/v3/view.hpp\"\n\nint main()\n{\n std::string str = \"Somewhere down the range v3 library\";\n for (auto s : str | ranges::view::split(' ')\n | ranges::view::transform([](auto&amp;&amp; sub) { return std::string_view(&amp;*sub.begin(), ranges::distance(sub)); }\n ))\n {\n std::cout &lt;&lt; \"Substring: \" &lt;&lt; s &lt;&lt; \"\\n\";\n }\n}\n</code></pre>\n" }, { "answer_id": 54220083, "author": "okovko", "author_id": 5122006, "author_profile": "https://Stackoverflow.com/users/5122006", "pm_score": 1, "selected": false, "text": "<p>I have a very different approach from the other solutions that offers a lot of value in ways that the other solutions are variously lacking, but of course also has its own down sides. <a href=\"https://repl.it/repls/FirmPapayawhipArtificialintelligence\" rel=\"nofollow noreferrer\">Here</a> is the working implementation, with the example of putting <code>&lt;tag&gt;&lt;/tag&gt;</code> around words.</p>\n\n<p>For a start, this problem can be solved with one loop, no additional memory, and by considering merely four logical cases. Conceptually, we're interested in boundaries. Our code should reflect that: let's iterate through the string and look at two characters at a time, bearing in mind that we have special cases at the start and end of the string.</p>\n\n<p>The downside is that we have to write the implementation, which is somewhat verbose, but mostly convenient boilerplate.</p>\n\n<p>The upside is that we wrote the implementation, so it is very easy to customize it to specific needs, such as distinguishing left and write word boundaries, using any set of delimiters, or handling other cases such as non-boundary or erroneous positions.</p>\n\n<pre><code>using namespace std;\n\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\n#include &lt;cctype&gt;\n\ntypedef enum boundary_type_e {\n E_BOUNDARY_TYPE_ERROR = -1,\n E_BOUNDARY_TYPE_NONE,\n E_BOUNDARY_TYPE_LEFT,\n E_BOUNDARY_TYPE_RIGHT,\n} boundary_type_t;\n\ntypedef struct boundary_s {\n boundary_type_t type;\n int pos;\n} boundary_t;\n\nbool is_delim_char(int c) {\n return isspace(c); // also compare against any other chars you want to use as delimiters\n}\n\nbool is_word_char(int c) {\n return ' ' &lt;= c &amp;&amp; c &lt;= '~' &amp;&amp; !is_delim_char(c);\n}\n\nboundary_t maybe_word_boundary(string str, int pos) {\n int len = str.length();\n if (pos &lt; 0 || pos &gt;= len) {\n return (boundary_t){.type = E_BOUNDARY_TYPE_ERROR};\n } else {\n if (pos == 0 &amp;&amp; is_word_char(str[pos])) {\n // if the first character is word-y, we have a left boundary at the beginning\n return (boundary_t){.type = E_BOUNDARY_TYPE_LEFT, .pos = pos};\n } else if (pos == len - 1 &amp;&amp; is_word_char(str[pos])) {\n // if the last character is word-y, we have a right boundary left of the null terminator\n return (boundary_t){.type = E_BOUNDARY_TYPE_RIGHT, .pos = pos + 1};\n } else if (!is_word_char(str[pos]) &amp;&amp; is_word_char(str[pos + 1])) {\n // if we have a delimiter followed by a word char, we have a left boundary left of the word char\n return (boundary_t){.type = E_BOUNDARY_TYPE_LEFT, .pos = pos + 1};\n } else if (is_word_char(str[pos]) &amp;&amp; !is_word_char(str[pos + 1])) {\n // if we have a word char followed by a delimiter, we have a right boundary right of the word char\n return (boundary_t){.type = E_BOUNDARY_TYPE_RIGHT, .pos = pos + 1};\n }\n return (boundary_t){.type = E_BOUNDARY_TYPE_NONE};\n }\n}\n\nint main() {\n string str;\n getline(cin, str);\n\n int len = str.length();\n for (int i = 0; i &lt; len; i++) {\n boundary_t boundary = maybe_word_boundary(str, i);\n if (boundary.type == E_BOUNDARY_TYPE_LEFT) {\n // whatever\n } else if (boundary.type == E_BOUNDARY_TYPE_RIGHT) {\n // whatever\n }\n }\n}\n</code></pre>\n\n<p>As you can see, the code is very simple to understand and fine tune, and the actual usage of the code is very short and simple. Using C++ should not stop us from writing the simplest and most readily customized code possible, even if that means not using the STL. I would think this is an instance of what Linus Torvalds might call <a href=\"https://medium.com/@bartobri/applying-the-linus-tarvolds-good-taste-coding-requirement-99749f37684a\" rel=\"nofollow noreferrer\">\"taste\"</a>, since we have eliminated all the logic we don't need while writing in a style that naturally allows more cases to be handled when and if the need to handle them arises.</p>\n\n<p>What could improve this code might be the use of <code>enum class</code>, accepting a function pointer to <code>is_word_char</code> in <code>maybe_word_boundary</code> instead of invoking <code>is_word_char</code> directly, and passing a lambda.</p>\n" }, { "answer_id": 60732623, "author": "balki", "author_id": 463758, "author_profile": "https://Stackoverflow.com/users/463758", "pm_score": 1, "selected": false, "text": "<p>C++17 version without any memory allocation (except may be for <code>std::function</code>)</p>\n\n<pre><code>void iter_words(const std::string_view&amp; input, const std::function&lt;void(std::string_view)&gt;&amp; process_word) {\n\n auto itr = input.begin();\n\n auto consume_whitespace = [&amp;]() {\n for(; itr != input.end(); ++itr) {\n if(!isspace(*itr))\n return;\n }\n };\n\n auto consume_letters = [&amp;]() {\n for(; itr != input.end(); ++itr) {\n if(isspace(*itr))\n return;\n }\n };\n\n while(true) {\n consume_whitespace();\n if(itr == input.end())\n return;\n auto word_start = itr - input.begin();\n consume_letters();\n auto word_end = itr - input.begin();\n process_word(input.substr(word_start, word_end - word_start));\n }\n}\n\nint main() {\n iter_words(\"foo bar\", [](std::string_view sv) {\n std::cout &lt;&lt; \"Got word: \" &lt;&lt; sv &lt;&lt; '\\n';\n });\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 61621475, "author": "J. Willus", "author_id": 6327684, "author_profile": "https://Stackoverflow.com/users/6327684", "pm_score": 4, "selected": false, "text": "<p>C++20 finally blesses us with a <code>split</code> function. Or rather, a range adapter. <a href=\"https://godbolt.org/z/6mZ8hG\" rel=\"noreferrer\">Godbolt link</a>.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;ranges&gt;\n#include &lt;string_view&gt;\n\nnamespace ranges = std::ranges;\nnamespace views = std::views;\n\nusing str = std::string_view;\n\nconstexpr auto view =\n \"Multiple words\"\n | views::split(' ')\n | views::transform([](auto &amp;&amp;r) -&gt; str {\n return {\n &amp;*r.begin(),\n static_cast&lt;str::size_type&gt;(ranges::distance(r))\n };\n });\n\nauto main() -&gt; int {\n for (str &amp;&amp;sv : view) {\n std::cout &lt;&lt; sv &lt;&lt; '\\n';\n }\n}\n</code></pre>\n" }, { "answer_id": 62244701, "author": "Nur Bijoy", "author_id": 9162697, "author_profile": "https://Stackoverflow.com/users/9162697", "pm_score": 3, "selected": false, "text": "<p>Everyone answered for predefined string input.\nI think this answer will help someone for scanned input.</p>\n\n<p>I used tokens vector for holding string tokens. It's optional.</p>\n\n<pre><code>#include &lt;bits/stdc++.h&gt;\n\nusing namespace std ;\nint main()\n{\n string str, token ;\n getline(cin, str) ; // get the string as input\n istringstream ss(str); // insert the string into tokenizer\n\n vector&lt;string&gt; tokens; // vector tokens holds the tokens\n\n while (ss &gt;&gt; token) tokens.push_back(token); // splits the tokens\n for(auto x : tokens) cout &lt;&lt; x &lt;&lt; endl ; // prints the tokens\n\n return 0;\n}\n\n\n</code></pre>\n\n<p>sample input:</p>\n\n<pre><code>port city international university\n</code></pre>\n\n<p>sample output:</p>\n\n<pre><code>port\ncity\ninternational\nuniversity\n</code></pre>\n\n<p>Note that by default this will work for only space as the delimiter. \nyou can use custom delimiter. For that, you have customized the code. let the delimiter be ','. so use </p>\n\n<pre><code>char delimiter = ',' ;\nwhile(getline(ss, token, delimiter)) tokens.push_back(token) ;\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>while (ss &gt;&gt; token) tokens.push_back(token);\n</code></pre>\n" }, { "answer_id": 68655819, "author": "Kaznov", "author_id": 6401179, "author_profile": "https://Stackoverflow.com/users/6401179", "pm_score": 3, "selected": false, "text": "<p>Although there was some answer providing C++20 solution, since it was posted there were some changes made and applied to C++20 as Defect Reports. Because of that the solution is a little bit shorter and nicer:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;ranges&gt;\n#include &lt;string_view&gt;\n\nnamespace views = std::views;\nusing str = std::string_view;\n\nconstexpr str text = &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&quot;;\n\nauto splitByWords(str input) {\n return input\n | views::split(' ')\n | views::transform([](auto &amp;&amp;r) -&gt; str {\n return {r.begin(), r.end()};\n });\n}\n\nauto main() -&gt; int {\n for (str &amp;&amp;word : splitByWords(text)) {\n std::cout &lt;&lt; word &lt;&lt; '\\n';\n }\n}\n</code></pre>\n<p>As of today it is still available only on the trunk branch of GCC (<a href=\"https://godbolt.org/z/x6a7rzTKn\" rel=\"noreferrer\">Godbolt link</a>). It is based on two changes: P1391 iterator constructor for <code>std::string_view</code> and P2210 DR fixing <code>std::views::split</code> to preserve range type.</p>\n<p>In C++23 there won't be any <code>transform</code> boilerplate needed, since P1989 adds a range constructor to std::string_view:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;ranges&gt;\n#include &lt;string_view&gt;\n\nnamespace views = std::views;\n\nconstexpr std::string_view text = &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&quot;;\n\nauto main() -&gt; int {\n for (std::string_view&amp;&amp; word : text | views::split(' ')) {\n std::cout &lt;&lt; word &lt;&lt; '\\n';\n }\n}\n</code></pre>\n<p>(<a href=\"https://godbolt.org/z/64Gdjnb6x\" rel=\"noreferrer\">Godbolt link</a>)</p>\n" }, { "answer_id": 69210405, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There's a way easier method to do this!!</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\nstd::vector&lt;std::string&gt; splitby(std::string string, char splitter) {\n int splits = 0;\n std::vector&lt;std::string&gt; result = {};\n std::string locresult = &quot;&quot;;\n for (unsigned int i = 0; i &lt; string.size(); i++) {\n if ((char)string.at(i) != splitter) {\n locresult += string.at(i);\n }\n else {\n result.push_back(locresult);\n locresult = &quot;&quot;;\n }\n }\n if (splits == 0) {\n result.push_back(locresult);\n }\n return result;\n}\n\nvoid printvector(std::vector&lt;std::string&gt; v) {\n std::cout &lt;&lt; '{';\n for (unsigned int i = 0; i &lt; v.size(); i++) {\n if (i &lt; v.size() - 1) {\n std::cout &lt;&lt; '&quot;' &lt;&lt; v.at(i) &lt;&lt; &quot;\\&quot;,&quot;;\n }\n else {\n std::cout &lt;&lt; '&quot;' &lt;&lt; v.at(i) &lt;&lt; &quot;\\&quot;&quot;;\n }\n }\n std::cout &lt;&lt; &quot;}\\n&quot;;\n}\n</code></pre>\n" }, { "answer_id": 69676745, "author": "AlQuemist", "author_id": 3484761, "author_profile": "https://Stackoverflow.com/users/3484761", "pm_score": 1, "selected": false, "text": "<p>A minimal solution is a function which takes as input a <code>std::string</code> and a set of delimiter characters (as a <code>std::string</code>), and returns a <code>std::vector</code> of <code>std::strings</code>.</p>\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n\nstd::vector&lt;std::string&gt;\ntokenize(const std::string&amp; str, const std::string&amp; delimiters)\n{\n using ssize_t = std::string::size_type;\n const ssize_t str_ln = str.length();\n ssize_t last_pos = 0;\n\n // container for the extracted tokens\n std::vector&lt;std::string&gt; tokens;\n\n while (last_pos &lt; str_ln) {\n // find the position of the next delimiter\n ssize_t pos = str.find_first_of(delimiters, last_pos);\n\n // if no delimiters found, set the position to the length of string\n if (pos == std::string::npos)\n pos = str_ln;\n\n // if the substring is nonempty, store it in the container\n if (pos != last_pos)\n tokens.emplace_back(str.substr(last_pos, pos - last_pos));\n\n // scan past the previous substring\n last_pos = pos + 1;\n }\n\n return tokens;\n}\n</code></pre>\n<p>A usage example:</p>\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n std::string input_str = &quot;one + two * (three - four)!!---! &quot;;\n const char* delimiters = &quot;! +- (*)&quot;;\n std::vector&lt;std::string&gt; tokens = tokenize(input_str, delimiters);\n\n std::cout &lt;&lt; &quot;input = '&quot; &lt;&lt; input_str &lt;&lt; &quot;'\\n&quot;\n &lt;&lt; &quot;delimiters = '&quot; &lt;&lt; delimiters &lt;&lt; &quot;'\\n&quot;\n &lt;&lt; &quot;nr of tokens found = &quot; &lt;&lt; tokens.size() &lt;&lt; std::endl;\n for (const std::string&amp; tk : tokens) {\n std::cout &lt;&lt; &quot;token = '&quot; &lt;&lt; tk &lt;&lt; &quot;'\\n&quot;;\n }\n\n return 0;\n}\n\n</code></pre>\n" }, { "answer_id": 71207982, "author": "Sam B", "author_id": 1058419, "author_profile": "https://Stackoverflow.com/users/1058419", "pm_score": 3, "selected": false, "text": "<p>I cannot believe how overly complicated most of these answers were. Why didnt someone suggest something as simple as this?</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;sstream&gt;\n\nstd::string input = &quot;This is a sentence to read&quot;;\nstd::istringstream ss(input);\nstd::string token;\n\nwhile(std::getline(ss, token, ' ')) {\n std::cout &lt;&lt; token &lt;&lt; endl;\n}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
How do I iterate over the words of a string composed of words separated by whitespace? Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution: ``` #include <iostream> #include <sstream> #include <string> using namespace std; int main() { string s = "Somewhere down the road"; istringstream iss(s); do { string subs; iss >> subs; cout << "Substring: " << subs << endl; } while (iss); } ```
For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL. ``` #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator> int main() { using namespace std; string sentence = "And I feel fine..."; istringstream iss(sentence); copy(istream_iterator<string>(iss), istream_iterator<string>(), ostream_iterator<string>(cout, "\n")); } ``` Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic [`copy`](https://en.cppreference.com/w/cpp/algorithm/copy) algorithm. ``` vector<string> tokens; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens)); ``` ... or create the `vector` directly: ``` vector<string> tokens{istream_iterator<string>{iss}, istream_iterator<string>{}}; ```
236,133
<p>I'm trying to get a simple search form working in my RoR site. I've got the following code:</p> <p>(in note_controller.rb)</p> <pre><code> def search @results = Note.find_with_ferret(params[:term]).sort_by(&amp;:ferret_rank) respond_to do |format| format.html format.xml { render :xml =&gt; @nootes } end end </code></pre> <p>(in note.rb)</p> <pre><code>class Note &lt; ActiveRecord::Base acts_as_ferret :fields =&gt; [ :title, :body ] end </code></pre> <p>(in index.html.erb)</p> <pre><code>&lt;%= form_tag :action =&gt; 'search'%&gt; &lt;%= text_field 'term', nil %&gt; &lt;%= submit_tag 'Search' %&gt; &lt;/form&gt; </code></pre> <p>(in search.html.erb)</p> <pre><code>&lt;h1&gt;&lt;%= pluralize(@results.size, 'result') %&gt;&lt;/h1&gt; &lt;ul&gt; &lt;% for result in @results %&gt; &lt;li&gt;&lt;%= result.ferret_score %&gt;: &lt;%= link_to result.tile, result %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; </code></pre> <p>As you can hopefully see from the above I've got a model which I've told to acts_as_ferret. I've then got a search action in my controller, which tries to render to the search.html.erb view. I've got a form in the index view which does a search. However, when I run this I get the following error:</p> <blockquote> <p>Cannot add Array to a BooleanQuery</p> </blockquote> <p>I guess I'm doing something wrong with my form so that ferret is getting the wrong data somehow. Is the form_tag thing I've done the right way to do it? Any help would be much appreciated.</p> <p><strong>Update:</strong></p> <p>Below is the only bit I can seem to extract from the log. I'm using Heroku and it doesn't seem to give quite the stardard log files. Hope this is helpful.</p> <pre><code>Processing NotesController#search (for 152.78.202.74, 127.0.0.1 at 2008-10-25 07:32:23) [POST] Session ID: BAh7BzoMY3NyZl9pZCIlZmEyMzcxZTdlYTUyODRkNzlmMzdjZWJlOGNlOGYz M2UiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhh c2h7AAY6CkB1c2VkewA=--450f51b45e38cba302e8ac6bd9b03c7ae79981e9 Parameters: {"commit"=&gt;"Search", "term"=&gt;["wheelbarrow"], "authenticity_token"=&gt;"1879a835ded87e7a28861725ec668b690de6b7f5", "action"=&gt;"search", "controller"=&gt;"notes"} configured index for class Note: { :index_dir=&gt;"/mnt/home/userapps/38385/index/development/note", :mysql_fast_batches=&gt;true, :name=&gt;:note, :single_index=&gt;false, :index_base_dir=&gt;"/mnt/home/userapps/38385/index/development/note", :reindex_batch_size=&gt;1000, :registered_models=&gt;[Note(id: integer, title: string, body: text, created_at: datetime, updated_at: datetime)], :ferret=&gt;{:dir=&gt;#, :key=&gt;[:id, :class_name], :or_default=&gt;false, :handle_parse_errors=&gt;true, :auto_flush=&gt;true, :create_if_missing=&gt;true, :path=&gt;"/mnt/home/userapps/38385/index/development/note", :default_field=&gt;[:title, :body], :analyzer=&gt;#, :lock_retry_time=&gt;2}, :ferret_fields=&gt;{:title=&gt;{:via=&gt;:title, :term_vector=&gt;:with_positions_offsets, :boost=&gt;1.0, :store=&gt;:no, :highlight=&gt;:yes, :index=&gt;:yes}, :body=&gt;{:via=&gt;:body, :term_vector=&gt;:with_positions_offsets, :boost=&gt;1.0, :store=&gt;:no, :highlight=&gt;:yes, :index=&gt;:yes}}, :fields=&gt;[:title, :body], :raise_drb_errors=&gt;false, :user_default_field=&gt;nil, :enabled=&gt;true} ArgumentError (Cannot add Array to a BooleanQuery): /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:124:in `add_query' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:124:in `scope_query_to_models' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:102:in `find_ids' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:85:in `find_id_model_arrays' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:41:in `ar_find' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:12:in `find_records' /vendor/plugins/acts_as_ferret/lib/acts_as_ferret.rb:342:in `find' /vendor/plugins/acts_as_ferret/lib/class_methods.rb:155:in `find_with_ferret' /app/controllers/notes_controller.rb:14:in `search' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:1162:in `send' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:1162:in `perform_action_without_filters' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/filters.rb:580:in `call_filters' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/filters.rb:573:in `perform_action_without_benchmark' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue_without_timeout' /usr/lib/ruby/1.8/benchmark.rb:293:in `measure' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue_without_timeout' /home/userapps_plugins/preload/request_timeout/lib/request_timeout.rb:9:in `perform_action_without_rescue' /usr/lib/ruby/1.8/timeout.rb:48:in `timeout' /home/userapps_plugins/preload/request_timeout/lib/request_timeout.rb:8:in `perform_action_without_rescue' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/rescue.rb:201:in `perform_action_without_caching' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/caching/sql_cache.rb:13:in `perform_action' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/connection_adapters/abstract/query_cache.rb:33:in `cache' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/query_cache.rb:8:in `cache' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/caching/sql_cache.rb:12:in `perform_action' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:529:in `send' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:529:in `process_without_filters' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/filters.rb:569:in `process_without_session_management_support' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/session_management.rb:130:in `process' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:389:in `process' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:149:in `handle_request' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:107:in `dispatch' /usr/lib/ruby/1.8/thread.rb:135:in `synchronize' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:104:in `dispatch' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:120:in `dispatch_cgi' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:35:in `dispatch' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/rack/adapter/rails.rb:54:in `serve_rails' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/rack/adapter/rails.rb:74:in `call' /home/heroku_rack/lib/toolbar.rb:16:in `call' /usr/lib/ruby/gems/1.8/gems/rack-0.4.0/lib/rack/urlmap.rb:42:in `call' /usr/lib/ruby/gems/1.8/gems/rack-0.4.0/lib/rack/urlmap.rb:35:in `each' /usr/lib/ruby/gems/1.8/gems/rack-0.4.0/lib/rack/urlmap.rb:35:in `call' /usr/lib/ruby/gems/1.8/gems/rack-0.4.0/lib/rack/builder.rb:53:in `call' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/connection.rb:59:in `pre_process' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/connection.rb:50:in `process' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/connection.rb:35:in `receive_data' /usr/lib/ruby/gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:224:in `run_machine' /usr/lib/ruby/gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:224:in `run' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/backends/base.rb:45:in `start' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/server.rb:146:in `start' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/controllers/controller.rb:79:in `start' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/runner.rb:166:in `send' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/runner.rb:166:in `run_command' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/runner.rb:136:in `run!' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/bin/thin:6 /usr/bin/thin:19:in `load' /usr/bin/thin:19 Rendering /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/templates/res </code></pre>
[ { "answer_id": 236612, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 2, "selected": true, "text": "<p>I can't recall ever seeing that ferret error. There's two basic diagnostics: go into script/console, and do </p>\n\n<pre>Notes.find_with_ferret(\"some term that should be in index\") </pre>\n\n<p>And then see what happens when you remove the indexes' directory (/appname/index/development), do another find_with_ferret to force reindex? </p>\n\n<p>Background info: are \"title\" and \"body\" columns in table, or calculated in instance method, or children from e.g. has_many? If fields in the table, what column types are \"title\" and \"body\" declared at in the migration, and what kind fo mySQL column types are they?</p>\n\n<p>Also usually helpful to include your O/S, the versions of ruby, rails, ferret and a_a_f you're using.</p>\n" }, { "answer_id": 236829, "author": "robintw", "author_id": 1912, "author_profile": "https://Stackoverflow.com/users/1912", "pm_score": 0, "selected": false, "text": "<p>I've removed the index directory, and it seems to have regenerated itself but now my searches on the console are giving no results. Before I deleted the index directory I got results on the console, but not when used from the form in my app.</p>\n\n<p>Title and Body are both columns in my MySQL table. They were created using Rails migrations as type string and text respectively.</p>\n\n<p>I'm running on Heroku - so I'm not entirely sure what OS (probably linux) or versions though I know it is at least rails 2.1. I also can't seem to find a version number for AAF - but I guess it's relatively recent.</p>\n\n<p>Sorry I can't be more help - is what I've said any use?</p>\n\n<p>Robin</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
I'm trying to get a simple search form working in my RoR site. I've got the following code: (in note\_controller.rb) ``` def search @results = Note.find_with_ferret(params[:term]).sort_by(&:ferret_rank) respond_to do |format| format.html format.xml { render :xml => @nootes } end end ``` (in note.rb) ``` class Note < ActiveRecord::Base acts_as_ferret :fields => [ :title, :body ] end ``` (in index.html.erb) ``` <%= form_tag :action => 'search'%> <%= text_field 'term', nil %> <%= submit_tag 'Search' %> </form> ``` (in search.html.erb) ``` <h1><%= pluralize(@results.size, 'result') %></h1> <ul> <% for result in @results %> <li><%= result.ferret_score %>: <%= link_to result.tile, result %></li> <% end %> </ul> ``` As you can hopefully see from the above I've got a model which I've told to acts\_as\_ferret. I've then got a search action in my controller, which tries to render to the search.html.erb view. I've got a form in the index view which does a search. However, when I run this I get the following error: > > Cannot add Array to a BooleanQuery > > > I guess I'm doing something wrong with my form so that ferret is getting the wrong data somehow. Is the form\_tag thing I've done the right way to do it? Any help would be much appreciated. **Update:** Below is the only bit I can seem to extract from the log. I'm using Heroku and it doesn't seem to give quite the stardard log files. Hope this is helpful. ``` Processing NotesController#search (for 152.78.202.74, 127.0.0.1 at 2008-10-25 07:32:23) [POST] Session ID: BAh7BzoMY3NyZl9pZCIlZmEyMzcxZTdlYTUyODRkNzlmMzdjZWJlOGNlOGYz M2UiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhh c2h7AAY6CkB1c2VkewA=--450f51b45e38cba302e8ac6bd9b03c7ae79981e9 Parameters: {"commit"=>"Search", "term"=>["wheelbarrow"], "authenticity_token"=>"1879a835ded87e7a28861725ec668b690de6b7f5", "action"=>"search", "controller"=>"notes"} configured index for class Note: { :index_dir=>"/mnt/home/userapps/38385/index/development/note", :mysql_fast_batches=>true, :name=>:note, :single_index=>false, :index_base_dir=>"/mnt/home/userapps/38385/index/development/note", :reindex_batch_size=>1000, :registered_models=>[Note(id: integer, title: string, body: text, created_at: datetime, updated_at: datetime)], :ferret=>{:dir=>#, :key=>[:id, :class_name], :or_default=>false, :handle_parse_errors=>true, :auto_flush=>true, :create_if_missing=>true, :path=>"/mnt/home/userapps/38385/index/development/note", :default_field=>[:title, :body], :analyzer=>#, :lock_retry_time=>2}, :ferret_fields=>{:title=>{:via=>:title, :term_vector=>:with_positions_offsets, :boost=>1.0, :store=>:no, :highlight=>:yes, :index=>:yes}, :body=>{:via=>:body, :term_vector=>:with_positions_offsets, :boost=>1.0, :store=>:no, :highlight=>:yes, :index=>:yes}}, :fields=>[:title, :body], :raise_drb_errors=>false, :user_default_field=>nil, :enabled=>true} ArgumentError (Cannot add Array to a BooleanQuery): /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:124:in `add_query' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:124:in `scope_query_to_models' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:102:in `find_ids' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:85:in `find_id_model_arrays' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:41:in `ar_find' /vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb:12:in `find_records' /vendor/plugins/acts_as_ferret/lib/acts_as_ferret.rb:342:in `find' /vendor/plugins/acts_as_ferret/lib/class_methods.rb:155:in `find_with_ferret' /app/controllers/notes_controller.rb:14:in `search' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:1162:in `send' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:1162:in `perform_action_without_filters' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/filters.rb:580:in `call_filters' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/filters.rb:573:in `perform_action_without_benchmark' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue_without_timeout' /usr/lib/ruby/1.8/benchmark.rb:293:in `measure' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue_without_timeout' /home/userapps_plugins/preload/request_timeout/lib/request_timeout.rb:9:in `perform_action_without_rescue' /usr/lib/ruby/1.8/timeout.rb:48:in `timeout' /home/userapps_plugins/preload/request_timeout/lib/request_timeout.rb:8:in `perform_action_without_rescue' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/rescue.rb:201:in `perform_action_without_caching' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/caching/sql_cache.rb:13:in `perform_action' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/connection_adapters/abstract/query_cache.rb:33:in `cache' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/query_cache.rb:8:in `cache' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/caching/sql_cache.rb:12:in `perform_action' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:529:in `send' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:529:in `process_without_filters' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/filters.rb:569:in `process_without_session_management_support' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/session_management.rb:130:in `process' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:389:in `process' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:149:in `handle_request' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:107:in `dispatch' /usr/lib/ruby/1.8/thread.rb:135:in `synchronize' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:104:in `dispatch' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:120:in `dispatch_cgi' /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/dispatcher.rb:35:in `dispatch' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/rack/adapter/rails.rb:54:in `serve_rails' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/rack/adapter/rails.rb:74:in `call' /home/heroku_rack/lib/toolbar.rb:16:in `call' /usr/lib/ruby/gems/1.8/gems/rack-0.4.0/lib/rack/urlmap.rb:42:in `call' /usr/lib/ruby/gems/1.8/gems/rack-0.4.0/lib/rack/urlmap.rb:35:in `each' /usr/lib/ruby/gems/1.8/gems/rack-0.4.0/lib/rack/urlmap.rb:35:in `call' /usr/lib/ruby/gems/1.8/gems/rack-0.4.0/lib/rack/builder.rb:53:in `call' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/connection.rb:59:in `pre_process' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/connection.rb:50:in `process' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/connection.rb:35:in `receive_data' /usr/lib/ruby/gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:224:in `run_machine' /usr/lib/ruby/gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:224:in `run' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/backends/base.rb:45:in `start' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/server.rb:146:in `start' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/controllers/controller.rb:79:in `start' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/runner.rb:166:in `send' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/runner.rb:166:in `run_command' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/lib/thin/runner.rb:136:in `run!' /usr/lib/ruby/gems/1.8/gems/thin-0.8.2/bin/thin:6 /usr/bin/thin:19:in `load' /usr/bin/thin:19 Rendering /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/templates/res ```
I can't recall ever seeing that ferret error. There's two basic diagnostics: go into script/console, and do ``` Notes.find_with_ferret("some term that should be in index") ``` And then see what happens when you remove the indexes' directory (/appname/index/development), do another find\_with\_ferret to force reindex? Background info: are "title" and "body" columns in table, or calculated in instance method, or children from e.g. has\_many? If fields in the table, what column types are "title" and "body" declared at in the migration, and what kind fo mySQL column types are they? Also usually helpful to include your O/S, the versions of ruby, rails, ferret and a\_a\_f you're using.
236,151
<p>I recently started using Git as my version control system for some Cocoa projects I'm working on and wondered if there are best practices for working with version control systems on Cocoa projects.</p> <p>There is the obvious "build" directory which I exclude from versioning as it's not important and can change quite a bit when debugging some code and then there are those .pbxuser and .perspectivev3 which change ever time I open the project in Xcode but I don't really know if they are "important" enough to be checked in.</p> <p>Is there a commonly used configuration for excluding unimportant files?</p> <p>Thanks in advance</p>
[ { "answer_id": 236170, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I never commit the ${LOGNAME}.* files as they're basically preferences information for the current user; the project sources, targets, dependencies and so on are in the project.pbxproj file. And as you mentioned in your question, the build directory (assuming you have the Place Build Products in: Project directory option set) is where the derived files live, so there's no need to check that in. You can always re-generate its contents from the source code.</p>\n" }, { "answer_id": 236189, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 4, "selected": true, "text": "<p>Here's my Mercurial <code>.hgignore</code> file, which is based on <a href=\"http://boredzo.org/blog/archives/2008-03-20/hgignore-for-mac-os-x-applications\" rel=\"noreferrer\">Peter Hosey's</a>.</p>\n\n<pre><code>syntax: glob\n\n.DS_Store\n\n*.swp\n*~.nib\n\nbuild\n\n*.pbxuser\n*.perspective\n*.perspectivev3\n*.mode1v3\n\n*.pyc\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29618/" ]
I recently started using Git as my version control system for some Cocoa projects I'm working on and wondered if there are best practices for working with version control systems on Cocoa projects. There is the obvious "build" directory which I exclude from versioning as it's not important and can change quite a bit when debugging some code and then there are those .pbxuser and .perspectivev3 which change ever time I open the project in Xcode but I don't really know if they are "important" enough to be checked in. Is there a commonly used configuration for excluding unimportant files? Thanks in advance
Here's my Mercurial `.hgignore` file, which is based on [Peter Hosey's](http://boredzo.org/blog/archives/2008-03-20/hgignore-for-mac-os-x-applications). ``` syntax: glob .DS_Store *.swp *~.nib build *.pbxuser *.perspective *.perspectivev3 *.mode1v3 *.pyc ```
236,166
<p>I am using System.IO.Directory.GetCurrentDirectory() to get the current directory in my web service, but that does not give me the current directory. How do I get the current directory in a web service?</p> <p>Thanks Stuart </p>
[ { "answer_id": 236169, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 6, "selected": false, "text": "<p>In a webservice, you are running in a http context. So,</p>\n\n<pre><code>HttpContext.Current.Server.MapPath(\"~/\") \n</code></pre>\n\n<p>will give you the answer.</p>\n" }, { "answer_id": 236289, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 3, "selected": false, "text": "<p><code>HttpContext.Current.Server.MapPath(\"~/\")</code> would get you the root of the application?</p>\n\n<p>Which is plenty most likely as you probably know the path from there. </p>\n\n<p>Another option which might be of interest:</p>\n\n<pre><code>HttpContext.Current.Server.MapPath(\"/Directory/\") \n</code></pre>\n\n<p>This builds from the root of the application no matter what.</p>\n\n<p>Without the first slash this will take directory from where you call as the start:</p>\n\n<pre><code>HttpContext.Current.Server.MapPath(\"Directory/\") \n</code></pre>\n" }, { "answer_id": 2851750, "author": "felickz", "author_id": 343347, "author_profile": "https://Stackoverflow.com/users/343347", "pm_score": 5, "selected": false, "text": "<p><code>HttpContext.Current.Server.MapPath(\".\")</code> will give you the current working directory. </p>\n\n<p>But to Rohan West's comment about potentially being outside of an HttpContext it would probably be better to just call:</p>\n\n<pre><code>HostingEnvironment.MapPath(\".\")\n</code></pre>\n\n<p>See details <a href=\"https://stackoverflow.com/questions/944219/what-is-the-difference-between-server-mappath-and-hostingenvironment-mappath\">here</a></p>\n" }, { "answer_id": 6707480, "author": "MiloTheGreat", "author_id": 436725, "author_profile": "https://Stackoverflow.com/users/436725", "pm_score": 4, "selected": false, "text": "<p>HttpContext.Current.Server.MapPath(\"~/\") maps back to the root of the application or virtual directory.</p>\n\n<p>HttpContext.Current.Server.MapPath(\"~/\") &lt;-- ROOT<br/>\nHttpContext.Current.Server.MapPath(\".\") &lt;-- CURRENT DIRECTORY<br/>\nHttpContext.Current.Server.MapPath(\"..\") &lt;-- PARENT DIRECTORY<br/></p>\n\n<p>All the above is relative, so you can you any combination to traverse the directory tree.</p>\n" }, { "answer_id": 6916691, "author": "Damith", "author_id": 2558060, "author_profile": "https://Stackoverflow.com/users/2558060", "pm_score": 4, "selected": false, "text": "<p>Best way is using </p>\n\n<p><code>HostingEnvironment.ApplicationPhysicalPath</code> under <code>System.Web.Hosting</code></p>\n\n<p>for more information please refer <a href=\"http://msdn.microsoft.com/en-us/library/system.web.hosting.virtualpathprovider.aspx\">this link</a></p>\n" }, { "answer_id": 20764236, "author": "HydPhani", "author_id": 852225, "author_profile": "https://Stackoverflow.com/users/852225", "pm_score": 0, "selected": false, "text": "<p>HttpContext.Current.Server.MapPath(\"..\") [observe two(..) dots instead of (.)] gives physical directory of Virtual Directory of the site!</p>\n" }, { "answer_id": 24895963, "author": "user3866085", "author_id": 3866085, "author_profile": "https://Stackoverflow.com/users/3866085", "pm_score": 5, "selected": false, "text": "<p>You can use </p>\n\n<pre><code>AppDomain.CurrentDomain.BaseDirectory;\n</code></pre>\n\n<p>This gives you the root directory of your application.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23149/" ]
I am using System.IO.Directory.GetCurrentDirectory() to get the current directory in my web service, but that does not give me the current directory. How do I get the current directory in a web service? Thanks Stuart
In a webservice, you are running in a http context. So, ``` HttpContext.Current.Server.MapPath("~/") ``` will give you the answer.
236,172
<p>I have several <code>std::vector</code>, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold <code>int</code>s and some of them <code>std::string</code>s.</p> <p>Pseudo code:</p> <pre><code>std::vector&lt;int&gt; Index = { 3, 1, 2 }; std::vector&lt;std::string&gt; Values = { "Third", "First", "Second" }; Transformation = sort(Index); Index is now { 1, 2, 3}; ... magic happens as Transformation is applied to Values ... Values are now { "First", "Second", "Third" }; </code></pre>
[ { "answer_id": 236193, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 2, "selected": false, "text": "<p>Only one rough solution comes to my mind: create a vector that is the sum of all other vectors (a vector of structures, like {3,Third,...},{1,First,...}) then sort this vector by the first field, and then split the structures again.\n<br/><br/>Probably there is a better solution inside Boost or using the standard library.</p>\n" }, { "answer_id": 236199, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "<p>friol's approach is good when coupled with yours. First, build a vector consisting of the numbers 1…<em>n</em>, along with the elements from the vector dictating the sorting order:</p>\n\n<pre><code>typedef vector&lt;int&gt;::const_iterator myiter;\n\nvector&lt;pair&lt;size_t, myiter&gt; &gt; order(Index.size());\n\nsize_t n = 0;\nfor (myiter it = Index.begin(); it != Index.end(); ++it, ++n)\n order[n] = make_pair(n, it);\n</code></pre>\n\n<p>Now you can sort this array using a custom sorter:</p>\n\n<pre><code>struct ordering {\n bool operator ()(pair&lt;size_t, myiter&gt; const&amp; a, pair&lt;size_t, myiter&gt; const&amp; b) {\n return *(a.second) &lt; *(b.second);\n }\n};\n\nsort(order.begin(), order.end(), ordering());\n</code></pre>\n\n<p>Now you've captured the order of rearrangement inside <code>order</code> (more precisely, in the first component of the items). You can now use this ordering to sort your other vectors. There's probably a very clever in-place variant running in the same time, but until someone else comes up with it, here's one variant that isn't in-place. It uses <code>order</code> as a look-up table for the new index of each element.</p>\n\n<pre><code>template &lt;typename T&gt;\nvector&lt;T&gt; sort_from_ref(\n vector&lt;T&gt; const&amp; in,\n vector&lt;pair&lt;size_t, myiter&gt; &gt; const&amp; reference\n) {\n vector&lt;T&gt; ret(in.size());\n\n size_t const size = in.size();\n for (size_t i = 0; i &lt; size; ++i)\n ret[i] = in[reference[i].first];\n\n return ret;\n}\n</code></pre>\n" }, { "answer_id": 238075, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": "<p>I think what you <em>really</em> need (but correct me if I'm wrong) is a way to access elements of a container in some order.</p>\n\n<p>Rather than rearranging my original collection, I would borrow a concept from Database design: keep an index, ordered by a certain criterion. This index is an extra indirection that offers great flexibility.</p>\n\n<p>This way it is possible to generate multiple indices according to different members of a class.</p>\n\n<pre><code>using namespace std;\n\ntemplate&lt; typename Iterator, typename Comparator &gt;\nstruct Index {\n vector&lt;Iterator&gt; v;\n\n Index( Iterator from, Iterator end, Comparator&amp; c ){\n v.reserve( std::distance(from,end) );\n for( ; from != end; ++from ){\n v.push_back(from); // no deref!\n }\n sort( v.begin(), v.end(), c );\n }\n\n};\n\ntemplate&lt; typename Iterator, typename Comparator &gt;\nIndex&lt;Iterator,Comparator&gt; index ( Iterator from, Iterator end, Comparator&amp; c ){\n return Index&lt;Iterator,Comparator&gt;(from,end,c);\n}\n\nstruct mytype {\n string name;\n double number;\n};\n\ntemplate&lt; typename Iter &gt;\nstruct NameLess : public binary_function&lt;Iter, Iter, bool&gt; {\n bool operator()( const Iter&amp; t1, const Iter&amp; t2 ) const { return t1-&gt;name &lt; t2-&gt;name; }\n};\n\ntemplate&lt; typename Iter &gt;\nstruct NumLess : public binary_function&lt;Iter, Iter, bool&gt; {\n bool operator()( const Iter&amp; t1, const Iter&amp; t2 ) const { return t1-&gt;number &lt; t2-&gt;number; }\n};\n\nvoid indices() {\n\n mytype v[] = { { \"me\" , 0.0 }\n , { \"you\" , 1.0 }\n , { \"them\" , -1.0 }\n };\n mytype* vend = v + _countof(v);\n\n Index&lt;mytype*, NameLess&lt;mytype*&gt; &gt; byname( v, vend, NameLess&lt;mytype*&gt;() );\n Index&lt;mytype*, NumLess &lt;mytype*&gt; &gt; bynum ( v, vend, NumLess &lt;mytype*&gt;() );\n\n assert( byname.v[0] == v+0 );\n assert( byname.v[1] == v+2 );\n assert( byname.v[2] == v+1 );\n\n assert( bynum.v[0] == v+2 );\n assert( bynum.v[1] == v+0 );\n assert( bynum.v[2] == v+1 );\n\n}\n</code></pre>\n" }, { "answer_id": 238095, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 3, "selected": false, "text": "<p>Put your values in a <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/multi_index/doc/index.html\" rel=\"noreferrer\">Boost Multi-Index container</a> then iterate over to read the values in the order you want. You can even copy them to another vector if you want to.</p>\n" }, { "answer_id": 342940, "author": "lalitm", "author_id": 28555, "author_profile": "https://Stackoverflow.com/users/28555", "pm_score": 3, "selected": false, "text": "<pre><code>typedef std::vector&lt;int&gt; int_vec_t;\ntypedef std::vector&lt;std::string&gt; str_vec_t;\ntypedef std::vector&lt;size_t&gt; index_vec_t;\n\nclass SequenceGen {\n public:\n SequenceGen (int start = 0) : current(start) { }\n int operator() () { return current++; }\n private:\n int current;\n};\n\nclass Comp{\n int_vec_t&amp; _v;\n public:\n Comp(int_vec_t&amp; v) : _v(v) {}\n bool operator()(size_t i, size_t j){\n return _v[i] &lt; _v[j];\n }\n};\n\nindex_vec_t indices(3);\nstd::generate(indices.begin(), indices.end(), SequenceGen(0));\n//indices are {0, 1, 2}\n\nint_vec_t Index = { 3, 1, 2 };\nstr_vec_t Values = { \"Third\", \"First\", \"Second\" };\n\nstd::sort(indices.begin(), indices.end(), Comp(Index));\n//now indices are {1,2,0}\n</code></pre>\n\n<p>Now you can use the \"indices\" vector to index into \"Values\" vector.</p>\n" }, { "answer_id": 4265862, "author": "ltjax", "author_id": 518626, "author_profile": "https://Stackoverflow.com/users/518626", "pm_score": 2, "selected": false, "text": "<p>You can probably define a custom \"facade\" iterator that does what you need here. It would store iterators to all your vectors or alternatively derive the iterators for all but the first vector from the offset of the first. The tricky part is what that iterator dereferences to: think of something like boost::tuple and make clever use of boost::tie. (If you wanna extend on this idea, you can build these iterator types recursively using templates but you probably never want to write down the type of that - so you either need c++0x auto or a wrapper function for sort that takes ranges)</p>\n" }, { "answer_id": 8584552, "author": "aph", "author_id": 1109026, "author_profile": "https://Stackoverflow.com/users/1109026", "pm_score": 1, "selected": false, "text": "<p>ltjax's answer is a great approach - which is actually implemented in boost's zip_iterator <a href=\"http://www.boost.org/doc/libs/1_43_0/libs/iterator/doc/zip_iterator.html\" rel=\"nofollow\">http://www.boost.org/doc/libs/1_43_0/libs/iterator/doc/zip_iterator.html</a></p>\n\n<p>It packages together into a tuple whatever iterators you provide it. </p>\n\n<p>You can then create your own comparison function for a sort based on any combination of iterator values in your tuple. For this question, it would just be the first iterator in your tuple.</p>\n\n<p>A nice feature of this approach is that it allows you to keep the memory of each individual vector contiguous (if you're using vectors and that's what you want). You also don't need to store a separate index vector of ints.</p>\n" }, { "answer_id": 26533002, "author": "Tim MB", "author_id": 794283, "author_profile": "https://Stackoverflow.com/users/794283", "pm_score": 2, "selected": false, "text": "<p>A slightly more compact variant of xtofl's answer for if you are just looking to iterate through all your vectors based on the of a single <code>keys</code> vector. Create a permutation vector and use this to index into your other vectors.</p>\n\n<pre><code>#include &lt;boost/iterator/counting_iterator.hpp&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nstd::vector&lt;double&gt; keys = ...\nstd::vector&lt;double&gt; values = ...\n\nstd::vector&lt;size_t&gt; indices(boost::counting_iterator&lt;size_t&gt;(0u), boost::counting_iterator&lt;size_t&gt;(keys.size()));\nstd::sort(begin(indices), end(indices), [&amp;](size_t lhs, size_t rhs) {\n return keys[lhs] &lt; keys[rhs];\n});\n\n// Now to iterate through the values array.\nfor (size_t i: indices)\n{\n std::cout &lt;&lt; values[i] &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 27423416, "author": "user1596722", "author_id": 1596722, "author_profile": "https://Stackoverflow.com/users/1596722", "pm_score": 1, "selected": false, "text": "<p>This would have been an addendum to Konrad's answer as it an approach for a in-place variant of applying the sort order to a vector. Anyhow since the edit won't go through I will put it here</p>\n\n<p>Here is a in-place variant with a slightly higher time complexity that is due to a primitive operation of checking a boolean. The additional space complexity is of a vector which can be a space efficient compiler dependent implementation. The complexity of a vector can be eliminated if the given order itself can be modified.</p>\n\n<p>Here is a in-place variant with a slightly higher time complexity that is due to a primitive operation of checking a boolean. The additional space complexity is of a vector which can be a space efficient compiler dependent implementation. The complexity of a vector can be eliminated if the given order itself can be modified. This is a example of what the algorithm is doing. \nIf the order is 3 0 4 1 2, the movement of the elements as indicated by the position indices would be 3--->0; 0--->1; 1--->3; 2--->4; 4--->2.</p>\n\n<pre><code>template&lt;typename T&gt;\nstruct applyOrderinPlace\n{\nvoid operator()(const vector&lt;size_t&gt;&amp; order, vector&lt;T&gt;&amp; vectoOrder)\n{\nvector&lt;bool&gt; indicator(order.size(),0);\nsize_t start = 0, cur = 0, next = order[cur];\nsize_t indx = 0;\nT tmp; \n\nwhile(indx &lt; order.size())\n{\n//find unprocessed index\nif(indicator[indx])\n{ \n++indx;\ncontinue;\n}\n\nstart = indx;\ncur = start;\nnext = order[cur];\ntmp = vectoOrder[start];\n\nwhile(next != start)\n{\nvectoOrder[cur] = vectoOrder[next];\nindicator[cur] = true; \ncur = next;\nnext = order[next];\n}\nvectoOrder[cur] = tmp;\nindicator[cur] = true;\n}\n}\n};\n</code></pre>\n" }, { "answer_id": 35901428, "author": "Ziezi", "author_id": 3313438, "author_profile": "https://Stackoverflow.com/users/3313438", "pm_score": 0, "selected": false, "text": "<p>Here is a relatively simple implementation using <em>index mapping</em> between the ordered and unordered <code>names</code> that will be used to match the <code>ages</code> to the ordered <code>names</code>:</p>\n\n<pre><code>void ordered_pairs()\n{\n std::vector&lt;std::string&gt; names;\n std::vector&lt;int&gt; ages;\n\n // read input and populate the vectors\n populate(names, ages);\n\n // print input\n print(names, ages);\n\n // sort pairs\n std::vector&lt;std::string&gt; sortedNames(names);\n std::sort(sortedNames.begin(), sortedNames.end());\n\n std::vector&lt;int&gt; indexMap;\n for(unsigned int i = 0; i &lt; sortedNames.size(); ++i)\n {\n for (unsigned int j = 0; j &lt; names.size(); ++j)\n {\n if (sortedNames[i] == names[j]) \n {\n indexMap.push_back(j);\n break;\n }\n }\n }\n // use the index mapping to match the ages to the names\n std::vector&lt;int&gt; sortedAges;\n for(size_t i = 0; i &lt; indexMap.size(); ++i)\n {\n sortedAges.push_back(ages[indexMap[i]]);\n }\n\n std::cout &lt;&lt; \"Ordered pairs:\\n\";\n print(sortedNames, sortedAges); \n}\n</code></pre>\n\n<p>For the sake of completeness, here are the functions <code>populate()</code> and <code>print()</code>:</p>\n\n<pre><code>void populate(std::vector&lt;std::string&gt;&amp; n, std::vector&lt;int&gt;&amp; a)\n{\n std::string prompt(\"Type name and age, separated by white space; 'q' to exit.\\n&gt;&gt;\");\n std::string sentinel = \"q\";\n\n while (true)\n {\n // read input\n std::cout &lt;&lt; prompt;\n std::string input;\n getline(std::cin, input);\n\n // exit input loop\n if (input == sentinel)\n {\n break;\n }\n\n std::stringstream ss(input);\n\n // extract input\n std::string name;\n int age;\n if (ss &gt;&gt; name &gt;&gt; age)\n {\n n.push_back(name);\n a.push_back(age);\n }\n else\n {\n std::cout &lt;&lt;\"Wrong input format!\\n\";\n }\n }\n}\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>void print(const std::vector&lt;std::string&gt;&amp; n, const std::vector&lt;int&gt;&amp; a)\n{\n if (n.size() != a.size())\n {\n std::cerr &lt;&lt;\"Different number of names and ages!\\n\";\n return;\n }\n\n for (unsigned int i = 0; i &lt; n.size(); ++i)\n {\n std::cout &lt;&lt;'(' &lt;&lt; n[i] &lt;&lt; \", \" &lt;&lt; a[i] &lt;&lt; ')' &lt;&lt; \"\\n\";\n }\n}\n</code></pre>\n\n<p>And finally, <code>main()</code> becomes:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nvoid ordered_pairs();\nvoid populate(std::vector&lt;std::string&gt;&amp;, std::vector&lt;int&gt;&amp;);\nvoid print(const std::vector&lt;std::string&gt;&amp;, const std::vector&lt;int&gt;&amp;);\n\n//=======================================================================\nint main()\n{\n std::cout &lt;&lt; \"\\t\\tSimple name - age sorting.\\n\";\n ordered_pairs();\n}\n//=======================================================================\n// Function Definitions...\n</code></pre>\n" }, { "answer_id": 44987027, "author": "umair butt", "author_id": 8078229, "author_profile": "https://Stackoverflow.com/users/8078229", "pm_score": 0, "selected": false, "text": "<pre><code>**// C++ program to demonstrate sorting in vector\n// of pair according to 2nd element of pair\n#include &lt;iostream&gt;\n#include&lt;string&gt;\n#include&lt;vector&gt;\n#include &lt;algorithm&gt;\n\nusing namespace std;\n\n// Driver function to sort the vector elements\n// by second element of pairs\nbool sortbysec(const pair&lt;char,char&gt; &amp;a,\n const pair&lt;int,int&gt; &amp;b)\n{\n return (a.second &lt; b.second);\n}\n\nint main()\n{\n // declaring vector of pairs\n vector&lt; pair &lt;char, int&gt; &gt; vect;\n\n // Initialising 1st and 2nd element of pairs\n // with array values\n //int arr[] = {10, 20, 5, 40 };\n //int arr1[] = {30, 60, 20, 50};\n char arr[] = { ' a', 'b', 'c' };\n int arr1[] = { 4, 7, 1 };\n\n int n = sizeof(arr)/sizeof(arr[0]);\n\n // Entering values in vector of pairs\n for (int i=0; i&lt;n; i++)\n vect.push_back( make_pair(arr[i],arr1[i]) );\n\n // Printing the original vector(before sort())\n cout &lt;&lt; \"The vector before sort operation is:\\n\" ;\n for (int i=0; i&lt;n; i++)\n {\n // \"first\" and \"second\" are used to access\n // 1st and 2nd element of pair respectively\n cout &lt;&lt; vect[i].first &lt;&lt; \" \"\n &lt;&lt; vect[i].second &lt;&lt; endl;\n\n }\n\n // Using sort() function to sort by 2nd element\n // of pair\n sort(vect.begin(), vect.end(), sortbysec);\n\n // Printing the sorted vector(after using sort())\n cout &lt;&lt; \"The vector after sort operation is:\\n\" ;\n for (int i=0; i&lt;n; i++)\n {\n // \"first\" and \"second\" are used to access\n // 1st and 2nd element of pair respectively\n cout &lt;&lt; vect[i].first &lt;&lt; \" \"\n &lt;&lt; vect[i].second &lt;&lt; endl;\n }\n getchar();\n return 0;`enter code here`\n}**\n</code></pre>\n" }, { "answer_id": 46370413, "author": "cDc", "author_id": 1622193, "author_profile": "https://Stackoverflow.com/users/1622193", "pm_score": -1, "selected": false, "text": "<p>So many asked this question and nobody came up with a satisfactory answer. Here is a std::sort helper that enables to sort two vectors simultaneously, taking into account the values of only one vector. This solution is based on a custom RadomIt (random iterator), and operates directly on the original vector data, without temporary copies, structure rearrangement or additional indices:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/37368787/c-sort-one-vector-based-on-another-one/46370189#46370189\">C++, Sort One Vector Based On Another One</a></p>\n" }, { "answer_id": 56044446, "author": "kingusiu", "author_id": 328071, "author_profile": "https://Stackoverflow.com/users/328071", "pm_score": 0, "selected": false, "text": "<p>with C++11 lambdas and the STL algorithms based on answers from Konrad Rudolph and Gabriele D'Antona:</p>\n\n<pre><code>template&lt; typename T, typename U &gt;\nstd::vector&lt;T&gt; sortVecAByVecB( std::vector&lt;T&gt; &amp; a, std::vector&lt;U&gt; &amp; b ){\n\n // zip the two vectors (A,B)\n std::vector&lt;std::pair&lt;T,U&gt;&gt; zipped(a.size());\n for( size_t i = 0; i &lt; a.size(); i++ ) zipped[i] = std::make_pair( a[i], b[i] );\n\n // sort according to B\n std::sort(zipped.begin(), zipped.end(), []( auto &amp; lop, auto &amp; rop ) { return lop.second &lt; rop.second; }); \n\n // extract sorted A\n std::vector&lt;T&gt; sorted;\n std::transform(zipped.begin(), zipped.end(), std::back_inserter(sorted), []( auto &amp; pair ){ return pair.first; }); \n\n return sorted;\n}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8331/" ]
I have several `std::vector`, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold `int`s and some of them `std::string`s. Pseudo code: ``` std::vector<int> Index = { 3, 1, 2 }; std::vector<std::string> Values = { "Third", "First", "Second" }; Transformation = sort(Index); Index is now { 1, 2, 3}; ... magic happens as Transformation is applied to Values ... Values are now { "First", "Second", "Third" }; ```
friol's approach is good when coupled with yours. First, build a vector consisting of the numbers 1…*n*, along with the elements from the vector dictating the sorting order: ``` typedef vector<int>::const_iterator myiter; vector<pair<size_t, myiter> > order(Index.size()); size_t n = 0; for (myiter it = Index.begin(); it != Index.end(); ++it, ++n) order[n] = make_pair(n, it); ``` Now you can sort this array using a custom sorter: ``` struct ordering { bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) { return *(a.second) < *(b.second); } }; sort(order.begin(), order.end(), ordering()); ``` Now you've captured the order of rearrangement inside `order` (more precisely, in the first component of the items). You can now use this ordering to sort your other vectors. There's probably a very clever in-place variant running in the same time, but until someone else comes up with it, here's one variant that isn't in-place. It uses `order` as a look-up table for the new index of each element. ``` template <typename T> vector<T> sort_from_ref( vector<T> const& in, vector<pair<size_t, myiter> > const& reference ) { vector<T> ret(in.size()); size_t const size = in.size(); for (size_t i = 0; i < size; ++i) ret[i] = in[reference[i].first]; return ret; } ```
236,183
<p>I want to be able to put preformatted text (i.e. containing line breaks) into a single cell of a FitNesse fixture table. Is there a way to manipulate the FitNesse wiki markup to do this?</p>
[ { "answer_id": 236207, "author": "Matthew Murdoch", "author_id": 4023, "author_profile": "https://Stackoverflow.com/users/4023", "pm_score": 2, "selected": false, "text": "<p>One way to do this is to define a variable with the multi-line text and then refer to this from the table cell:</p>\n\n<pre><code>!define sql { SELECT *\n FROM bar\n WHERE gaz = 14\n}\n\n|sql|\n|${sql}|\n</code></pre>\n" }, { "answer_id": 587889, "author": "Johannes Brodwall", "author_id": 27658, "author_profile": "https://Stackoverflow.com/users/27658", "pm_score": 5, "selected": true, "text": "<p>Use !- -! to get multiline table cells and {{{ }}} to get preformatted text. The {{{ has to be outside the !-</p>\n\n<p>For example:</p>\n\n<pre><code>|sql|\n|{{{!- SELECT *\n FROM bar\n WHERE gaz = 14\n-!}}}|\n</code></pre>\n" }, { "answer_id": 25571927, "author": "Kenny Evitt", "author_id": 173497, "author_profile": "https://Stackoverflow.com/users/173497", "pm_score": 1, "selected": false, "text": "<p>richard's comment on <a href=\"https://stackoverflow.com/a/587889/173497\">Johannes Brodwall's answer</a> worked for me, i.e. you don't need the <a href=\"http://www.fitnesse.org/FitNesse.UserGuide.QuickReferenceGuide\" rel=\"nofollow noreferrer\">\"formatted 'as is'\" line/block markup, just the \"'as-is'/escaping\" character formatting</a> so the following is sufficient if you don't need or want the pre-formatted style too:</p>\n\n<pre><code>|sql|\n|!-Some text\nthat spans\nmultiple lines.\n-!|\n</code></pre>\n" }, { "answer_id": 26120457, "author": "Michael Técourt", "author_id": 2187110, "author_profile": "https://Stackoverflow.com/users/2187110", "pm_score": 1, "selected": false, "text": "<p>This way allows you to keep a table row on the same line in your source code :</p>\n\n<pre><code>| col1 | col2 |\n| !- col1 cell &lt;br /&gt; with line break -! | col2 cell without line break |\n</code></pre>\n" }, { "answer_id": 64265787, "author": "Jason Slobotski", "author_id": 5665753, "author_profile": "https://Stackoverflow.com/users/5665753", "pm_score": 1, "selected": false, "text": "<p>The way that ended up working best for me was using a couple of the solutions listed above together. Defining a variable and using the !- -!</p>\n<pre><code>define myVarWithLineBreaks {!-This is my\ntext with line\nbreaks-!}\n\n|col |col2 |\n|${myVarWithLineBreaks}|other value|\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
I want to be able to put preformatted text (i.e. containing line breaks) into a single cell of a FitNesse fixture table. Is there a way to manipulate the FitNesse wiki markup to do this?
Use !- -! to get multiline table cells and {{{ }}} to get preformatted text. The {{{ has to be outside the !- For example: ``` |sql| |{{{!- SELECT * FROM bar WHERE gaz = 14 -!}}}| ```
236,203
<p>I have a div with a <code>&lt;h1&gt;</code> tag in a div, with no margins. If I define any doctype, a white space appears above the div.</p> <p>If I remove the <code>&lt;h1&gt;</code> tags, or remove the doctype definition, there is no space (as there should be. Why?</p> <p>Example HTML:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; body { margin:0 } #thediv { background-color:green } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="thediv"&gt; &lt;h1&gt;test&lt;/h1&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The problem is the space above the green div, remove the DOCTYPE and the space disappears, change the <code>&lt;h1&gt;</code> tag to <code>&lt;b&gt;</code> and the space also disappears. It happens with any doctype (XHTML/HTML, strict/transitional/etc)</p> <p>Happens in almost all browsers (Using <a href="http://browsershots.org" rel="nofollow noreferrer">http://browsershots.org</a>). Amusingly, the only browser that seems to display it correctly was Internet Explorer 6.0..</p>
[ { "answer_id": 236213, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 0, "selected": false, "text": "<p>See <a href=\"http://www.opera.com/docs/specs/doctype/\" rel=\"nofollow noreferrer\">http://www.opera.com/docs/specs/doctype/</a> and <a href=\"http://hsivonen.iki.fi/doctype/\" rel=\"nofollow noreferrer\">http://hsivonen.iki.fi/doctype/</a>.</p>\n" }, { "answer_id": 236218, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 1, "selected": false, "text": "<p>The DOCTYPE signals standards mode; this is why IE6 displays it \"correctly\" (actually wrong), because its standards support sucks. Basically, in standards mode it follows CSS layout rules as defined in the spec, as opposed to what you're expecting (\"quirks mode\").</p>\n" }, { "answer_id": 236219, "author": "philistyne", "author_id": 16597, "author_profile": "https://Stackoverflow.com/users/16597", "pm_score": 2, "selected": false, "text": "<p>It's likely something to do with \"quirks\" mode which some browsers invoke in the absence of a doctype (or the presence of a malformed one).</p>\n\n<p>I'd suggest you <a href=\"http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/\" rel=\"nofollow noreferrer\">reset</a> your page's CSS and move on. Life's too short.</p>\n" }, { "answer_id": 236227, "author": "Phil Ross", "author_id": 5981, "author_profile": "https://Stackoverflow.com/users/5981", "pm_score": 4, "selected": true, "text": "<p>The space above the green div is the correct behaviour according to the <a href=\"http://www.w3.org/TR/CSS21/box.html#collapsing-margins\" rel=\"noreferrer\">CSS spec</a>. This is because the top margin of the h1 adjoins the top margin of the div.</p>\n\n<p>One way to keep the margin of the h1 inside the div is to add a border to the div:</p>\n\n<pre><code>#thediv{ background-color:green; border: 1px transparent solid; }\n</code></pre>\n" }, { "answer_id": 236678, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 0, "selected": false, "text": "<p>You have a couple of isssues here:</p>\n\n<ol>\n<li><p>Not having a DOCTYPE makes browsers use 'quirks mode' rather than interpreting your code in line with the standards. This is designed for old 'tag soup' code - if you are writing new code you should use a DOCTYPE and validate against it.</p></li>\n<li><p>Browsers are free to supply 'default styles' for HTML elements. If you want to make your page appear differently you have to specify how. Most pages at a minimum specify styles for the <code>body</code> and <code>div</code> elements. You also want to control the <code>h1</code> element so you need to style that too.</p></li>\n</ol>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
I have a div with a `<h1>` tag in a div, with no margins. If I define any doctype, a white space appears above the div. If I remove the `<h1>` tags, or remove the doctype definition, there is no space (as there should be. Why? Example HTML: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <style> body { margin:0 } #thediv { background-color:green } </style> </head> <body> <div id="thediv"> <h1>test</h1> </div> </body> </html> ``` The problem is the space above the green div, remove the DOCTYPE and the space disappears, change the `<h1>` tag to `<b>` and the space also disappears. It happens with any doctype (XHTML/HTML, strict/transitional/etc) Happens in almost all browsers (Using <http://browsershots.org>). Amusingly, the only browser that seems to display it correctly was Internet Explorer 6.0..
The space above the green div is the correct behaviour according to the [CSS spec](http://www.w3.org/TR/CSS21/box.html#collapsing-margins). This is because the top margin of the h1 adjoins the top margin of the div. One way to keep the margin of the h1 inside the div is to add a border to the div: ``` #thediv{ background-color:green; border: 1px transparent solid; } ```
236,211
<p>Is it good practice to let abstract classes define instance variables?</p> <pre><code>public abstract class ExternalScript extends Script { String source; public abstract void setSource(String file); public abstract String getSource(); } </code></pre> <p>The sub class, ExternalJavaScript.class, would then automatically get the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance. </p> <p>What is your advice?</p> <p>/Adam</p>
[ { "answer_id": 236215, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 4, "selected": false, "text": "<p>Sure.. Why not?<br>\nAbstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.<br>\nTake care however that you are not using an abstract base class where you should be using an interface. Refer to <a href=\"https://stackoverflow.com/questions/56867/interface-vs-base-class\">Interface vs Base class</a></p>\n" }, { "answer_id": 236229, "author": "Egwor", "author_id": 25308, "author_profile": "https://Stackoverflow.com/users/25308", "pm_score": 6, "selected": true, "text": "<p>I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.</p>\n\n<pre><code>public abstract class ExternalScript extends Script {\n\n private String source;\n\n public void setSource(String file) {\n source = file;\n }\n\n public String getSource() {\n return source;\n }\n}\n</code></pre>\n\n<p>Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code.\nThere are a few other reasons to think about too:</p>\n\n<ul>\n<li>If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.</li>\n<li>If your getter/setter methods aren't getting and setting, then describe them as something else.</li>\n</ul>\n\n<p>Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.</p>\n" }, { "answer_id": 236280, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31518/" ]
Is it good practice to let abstract classes define instance variables? ``` public abstract class ExternalScript extends Script { String source; public abstract void setSource(String file); public abstract String getSource(); } ``` The sub class, ExternalJavaScript.class, would then automatically get the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance. What is your advice? /Adam
I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin. ``` public abstract class ExternalScript extends Script { private String source; public void setSource(String file) { source = file; } public String getSource() { return source; } } ``` Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too: * If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier. * If your getter/setter methods aren't getting and setting, then describe them as something else. Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
236,235
<p><em>(This question specifically in C#, but applies generally to .NET)</em> </p> <p>I have a largish application that has a fairly good design, and is broken into major sections over interfaces (this was done to assist parallel development).</p> <p>We now have a primary set of concrete classes that implement the required interfaces, but we also have additional sets of concrete classes for alternative situations and testing.</p> <p>At the moment we pull all these classes together at the top level in code:</p> <pre><code>IMyInterface xComponent = new ConcreteXComponent1(); </code></pre> <p>If I want to swap out components then I only have to change that line and recompile:</p> <pre><code>// IMyInterface xComponent = new ConcreteXComponent1(); IMyInterface xComponent = new ConcreteXComponentAlternative(); </code></pre> <p>That works great, but obviously requires a recompile -- I'd rather the concrete class was chosen using a value from a config file. </p> <p>What's the standard pattern for changing concrete classes using a configuration file? Is there standard library I can use that solves this problem for me?</p> <p>Thanks!</p>
[ { "answer_id": 236237, "author": "Daniel Kreiseder", "author_id": 31406, "author_profile": "https://Stackoverflow.com/users/31406", "pm_score": 1, "selected": false, "text": "<p>Try the factory pattern</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Abstract_factory_pattern</a></p>\n" }, { "answer_id": 236240, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 3, "selected": true, "text": "<p>You want to look at IoC containers. (Spring.NET, StructureMap, Windsor, etc.)</p>\n" }, { "answer_id": 236245, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "<p>You could use the <code>Activator.CreateInstance</code> method. One of the methods overloads takes a type name and creates an instance of it using the default constructor. Then you can store the type name of the class in your config file and read it from your application.</p>\n" }, { "answer_id": 236255, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 0, "selected": false, "text": "<p>Using an IoC container will create a pool or collection of your objects that you can dynamically load. The frameworks that Romain suggested will use a configuration file that describes the objects and how they are instantiated. </p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
*(This question specifically in C#, but applies generally to .NET)* I have a largish application that has a fairly good design, and is broken into major sections over interfaces (this was done to assist parallel development). We now have a primary set of concrete classes that implement the required interfaces, but we also have additional sets of concrete classes for alternative situations and testing. At the moment we pull all these classes together at the top level in code: ``` IMyInterface xComponent = new ConcreteXComponent1(); ``` If I want to swap out components then I only have to change that line and recompile: ``` // IMyInterface xComponent = new ConcreteXComponent1(); IMyInterface xComponent = new ConcreteXComponentAlternative(); ``` That works great, but obviously requires a recompile -- I'd rather the concrete class was chosen using a value from a config file. What's the standard pattern for changing concrete classes using a configuration file? Is there standard library I can use that solves this problem for me? Thanks!
You want to look at IoC containers. (Spring.NET, StructureMap, Windsor, etc.)
236,236
<p>I have a select query that currently produces the following results: <BR></p> <pre><code>Description Code Price Product 1 A 5 Product 1 B 4 Product 1 C 2 </code></pre> <p>Using the following query: </p> <pre><code>SELECT DISTINCT np.Description, p.promotionalCode, p.Price FROM Price AS p INNER JOIN nProduct AS np ON p.nProduct = np.Id </code></pre> <p>I want to produce the following: </p> <pre><code>Description A B C Product 1 5 4 2 </code></pre>
[ { "answer_id": 236252, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 4, "selected": true, "text": "<pre><code>SELECT \n np.Id, \n np.Description, \n MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',\n MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',\n MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'\nFROM \n Price AS p \nINNER JOIN nProduct AS np ON p.nProduct = np.Id\nGROUP BY \n np.Id,\n np.Description\n</code></pre>\n\n<hr>\n\n<p>Here is a simple test example:</p>\n\n<pre><code>DECLARE @temp TABLE (\n id INT,\n description varchar(50),\n promotionalCode char(1),\n Price smallmoney\n)\n\nINSERT INTO @temp\nselect 1, 'Product 1', 'A', 5\n union\nSELECT 1, 'Product 1', 'B', 4\n union\nSELECT 1, 'Product 1', 'C', 2\n\n\n\nSELECT\n id,\n description,\n MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',\n MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',\n MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'\nFROM\n @temp\nGROUP BY \n id,\n description\n</code></pre>\n" }, { "answer_id": 236296, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 1, "selected": false, "text": "<p>Duckworth's answer is good. If you can get more than one value for each cell, you might want to use AVG or SUM instead of MIN, depending on what you want to see.</p>\n\n<p>If your DBMS supports it, you might also want to look into a Crosstab query, or a pivot query. For example, MS Access has crosstab queries.</p>\n" }, { "answer_id": 236453, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "<p>If you're using SQL Server 2005, you can use the new PIVOT operator.</p>\n\n<p>Simple PIVOT -- the number of orders a customer places for individual products.</p>\n\n<p>Structure of a simple Order table:</p>\n\n<pre><code>CREATE TABLE Sales.[Order]\n (Customer varchar(8), Product varchar(5), Quantity int)\n</code></pre>\n\n<p>The table contains the following values:</p>\n\n<pre><code>Customer Product Quantity\n Mike Bike 3\n Mike Chain 2\n Mike Bike 5\n Lisa Bike 3\n Lisa Chain 3\n Lisa Chain 4\n</code></pre>\n\n<p>Ex: a PIVOT operation on the Order table:</p>\n\n<pre><code>SELECT *\n FROM Sales.[Order]\n PIVOT (SUM(Quantity) FOR Product IN ([Bike],[Chain])) AS PVT\n</code></pre>\n\n<p>The expected output from this query is:</p>\n\n<pre><code>Customer Bike Chain\nLisa 3 7\nMike 8 2\n</code></pre>\n\n<p>If you aren't using SQL Server, you might search for \"pivot\" for your database.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a select query that currently produces the following results: ``` Description Code Price Product 1 A 5 Product 1 B 4 Product 1 C 2 ``` Using the following query: ``` SELECT DISTINCT np.Description, p.promotionalCode, p.Price FROM Price AS p INNER JOIN nProduct AS np ON p.nProduct = np.Id ``` I want to produce the following: ``` Description A B C Product 1 5 4 2 ```
``` SELECT np.Id, np.Description, MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A', MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B', MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C' FROM Price AS p INNER JOIN nProduct AS np ON p.nProduct = np.Id GROUP BY np.Id, np.Description ``` --- Here is a simple test example: ``` DECLARE @temp TABLE ( id INT, description varchar(50), promotionalCode char(1), Price smallmoney ) INSERT INTO @temp select 1, 'Product 1', 'A', 5 union SELECT 1, 'Product 1', 'B', 4 union SELECT 1, 'Product 1', 'C', 2 SELECT id, description, MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A', MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B', MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C' FROM @temp GROUP BY id, description ```
236,239
<p>I have an <em>SQLite</em> table that contains prices for various products. It's a snapshot table, so it contains the prices on 5 minute intervals. I would like to write a query that would return the difference in price from one row to the next on each item.</p> <p>The columns are id (auto inc), record_id (id of the product), price (price at that point in time), time (just seconds since epoch)</p> <p>I'm trying to return a 'difference' column that contains a value of difference between intervals.</p> <pre> Given the following id record_id price time 1 apple001 36.00 ... 67 apple001 37.87 ... 765 apple001 45.82 ... 892 apple001 26.76 ... I'd like it to return id record_id price time difference 1 apple001 36.00 ... 0 67 apple001 37.87 ... 1.87 765 apple001 45.82 ... 7.95 892 apple001 26.76 ... -19.06 </pre> <p>Is it possible with SQLite?</p> <p>Secondly, should it be possible - is there a way to limit it to the last 5 or so records?</p> <p>I'd appreciate any help, thanks.</p> <hr> <p>Just wanted to add a few things. I've found ways to do so in other databases, but I'm using XULRunner, thus SQLite. Which is why I'm working with it instead. </p> <p>The secondary question may need clarifying, I'm looking to order by the time and take and analyze the last 5 records. It's an issue I can tackle separately if need be.</p> <p>Here's a MySQL <a href="http://www.freeopenbook.com/mysqlcookbook/mysqlckbk-CHP-12-SECT-13.html" rel="noreferrer">solution</a>, kind of. It's the approach I'm heading towards, but the deal breaker is "If the table contains a sequence column but there are gaps, renumber it. If the table contains no such column, add one". By design this scenario has gaps as there is many records updated at once and won't be in order.</p>
[ { "answer_id": 236286, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "<p>I do not know if there are some limitations in SQLite, but you can try the following statements that are working in Sql Server. </p>\n\n<p>If the time difference is constant (you state that it is 5 minutes), you can write:</p>\n\n<pre><code>SELECT A.id, A.record_id, A.price, A.time, ISNULL(A.price - B.price, 0) AS difference\nFROM Table1 as A \n LEFT OUTER JOIN Table1 B ON A.record_id = B.record_id AND A.time - B.time = 5\n</code></pre>\n\n<p>otherwise</p>\n\n<pre><code>SELECT A.id, A.record_id, A.price, A.time, ISNULL(A.price - B.price, 0) AS difference\nFROM Table1 as A \n LEFT OUTER JOIN Table1 B ON B.record_id = A.record_id \n AND B.time = (SELECT MAX(time) FROM Table1 C WHERE C.time &lt; A.time AND C.record_id = A.record_id)\n</code></pre>\n\n<p>A statement without joins is the following</p>\n\n<pre><code>SELECT id, record_id, price, time,\n (SELECT A.price - B.price\n FROM Table1 as B\n WHERE B.record_id = A.record_id AND\n B.time = (SELECT MAX(time) FROM Table1 C WHERE C.time &lt; A.time AND C.record_id = A.record_id)) AS difference\nFROM Table1 as A \n</code></pre>\n\n<p>I hope that one of them will help you.</p>\n" }, { "answer_id": 61020620, "author": "Jeroen", "author_id": 7043928, "author_profile": "https://Stackoverflow.com/users/7043928", "pm_score": 4, "selected": false, "text": "<p>Yes, it is <strong>a bit late</strong>, but for completeness. <em>SQLite Release 3.25.0 in 2018 added support for window functions</em>. And the above task can now be completed by using the <a href=\"https://www.sqlite.org/windowfunctions.html\" rel=\"noreferrer\">LAG() and LEAD()</a> functions.</p>\n\n<p>Taken from: <a href=\"https://www.sqlitetutorial.net/sqlite-window-functions/\" rel=\"noreferrer\">https://www.sqlitetutorial.net/sqlite-window-functions/</a></p>\n\n<p><strong>LAG</strong> <em>Provides access to a row at a given physical offset that comes before the current row.</em></p>\n\n<p>So using the sqlite3 command in Linux, the following should match the output listed in your question. The first 2 commands are only there to display proper output format.</p>\n\n<pre><code>sqlite&gt; .mode columns\nsqlite&gt; .headers on\nsqlite&gt; CREATE TABLE data(id INT, record_id TEXT, price REAL);\nsqlite&gt; INSERT INTO data VALUES(1,\"apple001\",36.00);\nsqlite&gt; INSERT INTO data VALUES(67,\"apple001\",37.87);\nsqlite&gt; INSERT INTO data VALUES(765,\"apple001\",45.82);\nsqlite&gt; INSERT INTO data VALUES(892,\"apple001\",26.76);\nsqlite&gt; SELECT id, record_id, price, (price - LAG(price, 1) OVER (ORDER BY id)) AS difference FROM data;\nid record_id price difference\n---------- ---------- ---------- ----------\n1 apple001 36.0 \n67 apple001 37.87 1.87 \n765 apple001 45.82 7.95 \n892 apple001 26.76 -19.06\n</code></pre>\n\n<p>I hope this will save new users some time. </p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an *SQLite* table that contains prices for various products. It's a snapshot table, so it contains the prices on 5 minute intervals. I would like to write a query that would return the difference in price from one row to the next on each item. The columns are id (auto inc), record\_id (id of the product), price (price at that point in time), time (just seconds since epoch) I'm trying to return a 'difference' column that contains a value of difference between intervals. ``` Given the following id record_id price time 1 apple001 36.00 ... 67 apple001 37.87 ... 765 apple001 45.82 ... 892 apple001 26.76 ... I'd like it to return id record_id price time difference 1 apple001 36.00 ... 0 67 apple001 37.87 ... 1.87 765 apple001 45.82 ... 7.95 892 apple001 26.76 ... -19.06 ``` Is it possible with SQLite? Secondly, should it be possible - is there a way to limit it to the last 5 or so records? I'd appreciate any help, thanks. --- Just wanted to add a few things. I've found ways to do so in other databases, but I'm using XULRunner, thus SQLite. Which is why I'm working with it instead. The secondary question may need clarifying, I'm looking to order by the time and take and analyze the last 5 records. It's an issue I can tackle separately if need be. Here's a MySQL [solution](http://www.freeopenbook.com/mysqlcookbook/mysqlckbk-CHP-12-SECT-13.html), kind of. It's the approach I'm heading towards, but the deal breaker is "If the table contains a sequence column but there are gaps, renumber it. If the table contains no such column, add one". By design this scenario has gaps as there is many records updated at once and won't be in order.
Yes, it is **a bit late**, but for completeness. *SQLite Release 3.25.0 in 2018 added support for window functions*. And the above task can now be completed by using the [LAG() and LEAD()](https://www.sqlite.org/windowfunctions.html) functions. Taken from: <https://www.sqlitetutorial.net/sqlite-window-functions/> **LAG** *Provides access to a row at a given physical offset that comes before the current row.* So using the sqlite3 command in Linux, the following should match the output listed in your question. The first 2 commands are only there to display proper output format. ``` sqlite> .mode columns sqlite> .headers on sqlite> CREATE TABLE data(id INT, record_id TEXT, price REAL); sqlite> INSERT INTO data VALUES(1,"apple001",36.00); sqlite> INSERT INTO data VALUES(67,"apple001",37.87); sqlite> INSERT INTO data VALUES(765,"apple001",45.82); sqlite> INSERT INTO data VALUES(892,"apple001",26.76); sqlite> SELECT id, record_id, price, (price - LAG(price, 1) OVER (ORDER BY id)) AS difference FROM data; id record_id price difference ---------- ---------- ---------- ---------- 1 apple001 36.0 67 apple001 37.87 1.87 765 apple001 45.82 7.95 892 apple001 26.76 -19.06 ``` I hope this will save new users some time.
236,279
<pre><code>&lt;?php function toconv(string) { $gogo = array("a" =&gt; "b","cd" =&gt; "e"); $string = str_replace( array_keys( $gogo ), array_values( $gogo ), $string ); return $string; } ?&gt; </code></pre> <p>How can I implement that in JavaScript?</p>
[ { "answer_id": 236287, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>String.replace() in Javascript receives regexes instead of strings and here's a translation. You need to append the g modifier to the regex to replace all occurrences instead of only the first one. </p>\n\n<pre><code>&lt;script&gt;\nfunction toconv(str) {\n replacements = ['b','e'];\n regexes = [/a/g,/cd/g];\n\n for (i=0; i &lt; regexes.length; i++) {\n str = str.replace(regexes[i],replacements[i]);\n }\n return str;\n}\n\nalert(toconv('acdacd'));\nalert(toconv('foobar'));\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 236370, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": true, "text": "<p>And to make it in a way, where you can do it directly from an array:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction toconv(string){\n var gogo = {\"a\":\"b\", \"cd\":\"e\"}, reg;\n for(x in gogo) {\n reg = new RegExp(x, \"g\");\n string.replace(x, gogo[x]);\n }\n return string;\n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 33118570, "author": "alamin", "author_id": 4685044, "author_profile": "https://Stackoverflow.com/users/4685044", "pm_score": -1, "selected": false, "text": "<p>Convert PHP Function to JavaScript</p>\n\n<pre><code>if (preg_match('/0/', $check) || preg_match('/1/', $check) || preg_match('/2/', $check) || preg_match('/3/', $check) || preg_match('/4/', $check) || preg_match('/5/', $check) || preg_match('/6/', $check) || preg_match('/7/', $check) || preg_match('/8/', $check) || preg_match('/9/', $check))\n{\n exception(\"personal info not allowed\");\n redirect(base_url() . 'edit_profile');\n}\nelse if ((preg_match(\"~\\b@\\b~\",$check)) || (preg_match(\"~\\b.net\\b~\",$check)) || (preg_match(\"~\\b.com\\b~\",$check)) || (preg_match(\"~\\b@\\b~\",$check)) || (preg_match(\"~\\b.edu\\b~\",$check)) || (preg_match(\"~\\b.gov\\b~\",$check)))\n{\n exception(\"personal info not allowed\");\n redirect(base_url() . 'edit_profile');\n}\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21559/" ]
``` <?php function toconv(string) { $gogo = array("a" => "b","cd" => "e"); $string = str_replace( array_keys( $gogo ), array_values( $gogo ), $string ); return $string; } ?> ``` How can I implement that in JavaScript?
And to make it in a way, where you can do it directly from an array: ``` <script type="text/javascript"> function toconv(string){ var gogo = {"a":"b", "cd":"e"}, reg; for(x in gogo) { reg = new RegExp(x, "g"); string.replace(x, gogo[x]); } return string; } </script> ```
236,283
<p>I am using the following function to load a PlayList of Songs from 'PlayListJSON.aspx' but somethings seems wrong,evrytime OnFailure is getting called, I am unable to debug it further. any help would be really gr8.</p> <pre><code>Player.prototype.loadPlaylist = function(playlistId, play) { req = new Ajax.Request('/PlaylistJSON.aspx?id=' + playlistId, { method: 'GET', onSuccess: function(transport, json) { eval(transport.responseText); player.setPlaylist(playlist.tracklist, playlist.title, playlistId); player.firstTrack(); if (play) player.playSong(); }, onFailure: function() { //error } }); } </code></pre>
[ { "answer_id": 236299, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 1, "selected": false, "text": "<p>Generally, OnFailure gets called when the page you are calling out to can't be reached for some reason.</p>\n\n<p>Are you positive that the URL <strong>/PlaylistJSON.aspx</strong> is valid?</p>\n\n<hr>\n\n<p>Have you tried passing the parameters argument instead of specifying them as part of the url?</p>\n\n<pre><code>req = new Ajax.Request('/PlaylistJSON.aspx', \n { \n\n method: 'GET', \n parameters: {\n 'id': playlistId\n },\n onSuccess: function(transport,json){ \n\n eval(transport.responseText); \n\n player.setPlaylist(playlist.tracklist,playlist.title, playlistId);\n player.firstTrack();\n\n if (play)\n player.playSong(); \n\n },\n onFailure: function() {\n //error\n\n }\n });\n</code></pre>\n" }, { "answer_id": 236302, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Yes the Page PlayListJSon.aspx is in the root directory.</p>\n" }, { "answer_id": 359080, "author": "Serxipc", "author_id": 34009, "author_profile": "https://Stackoverflow.com/users/34009", "pm_score": 1, "selected": false, "text": "<p>If you are developing in windows install <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">Fiddler</a>. With <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">Fiddler</a> you will be able to see exactly what request is doing the Ajax call and what response comes from the server. This way you will know if the url is right, or if the server is responding some status code different from 200/OK.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using the following function to load a PlayList of Songs from 'PlayListJSON.aspx' but somethings seems wrong,evrytime OnFailure is getting called, I am unable to debug it further. any help would be really gr8. ``` Player.prototype.loadPlaylist = function(playlistId, play) { req = new Ajax.Request('/PlaylistJSON.aspx?id=' + playlistId, { method: 'GET', onSuccess: function(transport, json) { eval(transport.responseText); player.setPlaylist(playlist.tracklist, playlist.title, playlistId); player.firstTrack(); if (play) player.playSong(); }, onFailure: function() { //error } }); } ```
Generally, OnFailure gets called when the page you are calling out to can't be reached for some reason. Are you positive that the URL **/PlaylistJSON.aspx** is valid? --- Have you tried passing the parameters argument instead of specifying them as part of the url? ``` req = new Ajax.Request('/PlaylistJSON.aspx', { method: 'GET', parameters: { 'id': playlistId }, onSuccess: function(transport,json){ eval(transport.responseText); player.setPlaylist(playlist.tracklist,playlist.title, playlistId); player.firstTrack(); if (play) player.playSong(); }, onFailure: function() { //error } }); ```
236,290
<p>For example, say one was to include a 'delete' keyword in C# 4. Would it be possible to guarantee that you'd never have wild pointers, but still be able to rely on the garbage collecter, due to the reference-based system?</p> <p>The only way I could see it possibly happening is if instead of references to memory locations, a reference would be an index to a table of pointers to actual objects. However, I'm sure that there'd be some condition where that would break, and it'd be possible to break type safety/have dangling pointers.</p> <p>EDIT: I'm not talking about just .net. I was just using C# as an example.</p>
[ { "answer_id": 236304, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>With garbage collection, as long as you have a referenced reference to the object, it stays alive. With manual delete you can't guarantee that.</p>\n\n<p>Example (pseudocode):</p>\n\n<pre><code>obj1 = new instance;\nobj2 = obj1;\n\n// \n\ndelete obj2;\n// obj1 now references the twilightzone.\n</code></pre>\n\n<p>Just to be short, combining manual memory management with garbage collection defeats the purpose of GC. Besides, why bother? And if you really want to have control, use C++ and not C#. ;-).</p>\n" }, { "answer_id": 236307, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>The best you could get would be a partition into two “hemispheres” where one hemisphere is managed and can guarantee the absence of dangling pointers. The other hemisphere has explicit memory management and gives no guarantees. These two can coexist, but no, you can't give your strong guarantees to the second hemisphere. All you could do is to track all pointers. If one gets deleted, then all other pointers to the same instance could be set to zero. Needless to say, this is quite expensive. Your table would help, but introduce other costs (double indirection).</p>\n" }, { "answer_id": 236320, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 2, "selected": false, "text": "<p>You can - kind of: make your object disposable, and then dispose it yourself.</p>\n\n<p>A manual delete is unlikely to improve memory performance in a managed environment. It might help with unmanaged ressources, what dispose is all about. </p>\n\n<p>I'd rather have implementing and consuming Disposable objects made easier. I have no consistent, complete idea how this should look like, but managing unmanaged ressources is a verbose pain under .NET.</p>\n\n<hr>\n\n<p>An idea for implementing delete:\ndelete tags an object for manual deletion. At the next garbage collection cycle, the object is removed and all references to it are set to null.</p>\n\n<p>It sounds cool at first (at least to me), but I doubt it would be useful.\nThis isn't particulary safe, either - e.g. another thread might be busy executing a member method of that object, such an methods needs to throw e.g. when accessing object data.</p>\n" }, { "answer_id": 236503, "author": "Rob Windsor", "author_id": 28785, "author_profile": "https://Stackoverflow.com/users/28785", "pm_score": 0, "selected": false, "text": "<p>Chris Sells also discussed this on .NET Rocks. I think it was during his first appearance but the subject might have been revisited in later interviews.</p>\n\n<p><a href=\"http://www.dotnetrocks.com/default.aspx?showNum=10\" rel=\"nofollow noreferrer\">http://www.dotnetrocks.com/default.aspx?showNum=10</a></p>\n" }, { "answer_id": 237165, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 0, "selected": false, "text": "<p>My first reaction was: Why not? I can't imagine that you want to do is something as obscure as just leave an unreferenced chunk out on the heap to find it again later on. As if a four-byte pointer to the heap were too much to maintain to keep track of this chunk. </p>\n\n<p>So the issue is not leaving unreferenced memory allocated, but intentionally disposing of memory still in reference. Since garbage collection performs the function of marking the memory free at some point, it seems that we should just be able to call an alternate sequence of instructions to dispose of this particular chunk of memory. </p>\n\n<p>However, the problem lies here:</p>\n\n<pre><code>String s = \"Here is a string.\"; \nString t = s;\nString u = s;\njunk( s );\n</code></pre>\n\n<p>What do <code>t</code> and <code>u</code> point to? In a strict reference system, <code>t</code> and <code>u</code> should be <code>null</code>. So that means that you have to not only do reference <em>counting</em>, but perhaps <em>tracking</em> as well. </p>\n\n<p>However, I can see that you <em>should</em> be done with <code>s</code> at this point in your code. So <code>junk</code> can set the reference to null, and pass it to the sweeper with a sort of priority code. The gc could be activated for a limited run, and the memory freed only if not reachable. So we can't explicitly free anything that somebody has coded to use in some way again. <em>But</em> if <code>s</code> is the only reference, then the chunk is deallocated. </p>\n\n<p>So, I think it would only work with a <em>limited</em> adherence to the <em>explicit</em> side. </p>\n" }, { "answer_id": 1280781, "author": "Asik", "author_id": 154766, "author_profile": "https://Stackoverflow.com/users/154766", "pm_score": 0, "selected": false, "text": "<p>It's possible, and already implemented, in non-managed languages such as C++. Basically, you implement or use an existing garbage collector: when you want manual memory management, you call new and delete as normal, and when you want garbage collection, you call GC_MALLOC or whatever the function or macro is for your garbage collector.</p>\n\n<p>See <a href=\"http://www.hpl.hp.com/personal/Hans_Boehm/gc/\" rel=\"nofollow noreferrer\">http://www.hpl.hp.com/personal/Hans_Boehm/gc/</a> for an example.</p>\n\n<p>Since you were using C# as an example, maybe you only had in mind implementing manual memory management in a managed language, but this is to show you that the reverse is possible.</p>\n" }, { "answer_id": 2166825, "author": "Thomas Eding", "author_id": 239916, "author_profile": "https://Stackoverflow.com/users/239916", "pm_score": 0, "selected": false, "text": "<p>If the semantics of delete on a object's reference would make all other references referencing that object be null, then you could do it with 2 levels of indirection (1 more than you hint). Though note that while the underlying object would be destroyed, a fixed amount of information (enough to hold a reference) must be kept live on the heap.</p>\n\n<p>All references a user uses would reference a hidden reference (presumably living in a heap) to the real object. When doing some operation on the object (such as calling a method or relying on its identity, wuch as using the == operator), the reference the programmer uses would dereference the hidden reference it points to. When deleting an object, the actual object would be removed from the heap, and the hidden reference would be set to null. Thus the references programmers would see evaluate to null.</p>\n\n<p>It would be the GC's job to clean out these hidden references.</p>\n" }, { "answer_id": 3491714, "author": "user191535", "author_id": 191535, "author_profile": "https://Stackoverflow.com/users/191535", "pm_score": 0, "selected": false, "text": "<p>This would help in situations with long-lived objects. Garbage Collection works well when objects are used for short periods of time and de-referenced quickly. The problem is when some objects live for a long time. The only way to clean them up is to perform a resource-intensive garbage collection.</p>\n\n<p>In these situations, things would work much easier if there was a way to explicitly delete objects, or at least a way to move a graph of objects back to generation 0.</p>\n" }, { "answer_id": 8566198, "author": "Liran", "author_id": 2164233, "author_profile": "https://Stackoverflow.com/users/2164233", "pm_score": 0, "selected": false, "text": "<p>Yes ... but with some abuse.</p>\n\n<p>C# can be abused a little to make that happen.\nIf you're willing to play around with the <code>Marshal</code> class, <code>StructLayout</code> attribute and <code>unsafe code</code>, you could write your very own manual memory manager.</p>\n\n<p>You can find a demonstration of the concept here: <a href=\"http://www.liranchen.com/2011/08/writing-manual-memory-manager-in-c.html\" rel=\"nofollow noreferrer\">Writing a Manual Memory Manager in C#</a>.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18658/" ]
For example, say one was to include a 'delete' keyword in C# 4. Would it be possible to guarantee that you'd never have wild pointers, but still be able to rely on the garbage collecter, due to the reference-based system? The only way I could see it possibly happening is if instead of references to memory locations, a reference would be an index to a table of pointers to actual objects. However, I'm sure that there'd be some condition where that would break, and it'd be possible to break type safety/have dangling pointers. EDIT: I'm not talking about just .net. I was just using C# as an example.
With garbage collection, as long as you have a referenced reference to the object, it stays alive. With manual delete you can't guarantee that. Example (pseudocode): ``` obj1 = new instance; obj2 = obj1; // delete obj2; // obj1 now references the twilightzone. ``` Just to be short, combining manual memory management with garbage collection defeats the purpose of GC. Besides, why bother? And if you really want to have control, use C++ and not C#. ;-).
236,323
<p>I need to compare the integer part of two doubles for inequality and I'm currently doing this:</p> <pre><code>int iA = (int)dA; int iB = (int)dB; if( iA != iB ) { ... } </code></pre> <p>but I wonder if there's a better approach than this.</p> <p>Thanks.</p> <p>If I used Math.Truncate() instead of a cast to int, would it still be accurate to compare the two resulting double values for equality?</p> <p>About the hungarian notation comments:</p> <p>I never use HN myself, not at least in the way most of people do. But this is one of these rare cases where the semantic of a variable directly relates to its type. I could have chosen another syntax like A_As_Integer and B_As_NonInteger but what would have been the difference then?</p>
[ { "answer_id": 236331, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 2, "selected": false, "text": "<p>Yes, that is best approach.</p>\n\n<p>Assuming from your wording in you question you arent worried about rounding... just the integerr part itself.</p>\n\n<p>ie. (int)4.1 will give the same result as (int)4.9</p>\n\n<p><em>As Ovid stated, if you only need the variables for the comparison, then you will only need to cast the doubles in the comparison statement. I was looking only at the theory.</em></p>\n" }, { "answer_id": 236333, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 1, "selected": false, "text": "<p>Personally, I try to avoid creating extra variables unless I need them.</p>\n\n<pre><code>if ( (int)dA != (int)dB ) {\n ...\n}\n</code></pre>\n\n<p>As code evolves over time, having extra variables hanging around for no purpose leads to confusion. Of course, if you need those variables, that's another issue :)</p>\n\n<p>Side note: you appear to be trying to hint at the data type via a simple Hungarian notation. May I recommend not doing that? If you must prefix information to your variables, try to prefix what the variable is for, rather than its type. If you do that, mistakes in code can be easier to see:</p>\n\n<pre><code>if ( (int)ageA != (int)idB ) {\n ...\n}\n</code></pre>\n\n<p>In this case, without even knowing what the data is, seeing that you're trying to compare an 'age' with an 'id' is a good clue that something is wrong here.</p>\n" }, { "answer_id": 236340, "author": "biozinc", "author_id": 30698, "author_profile": "https://Stackoverflow.com/users/30698", "pm_score": 4, "selected": true, "text": "<p>Use Math.Truncate() i.e. </p>\n\n<pre><code>if (Math.Truncate(x) == Math.Truncate(y))\n</code></pre>\n\n<p>[Edit] Realized that if you are comparing integer parts of doubles, casting to int values first runs the risk of overflows should your doubles be outside the range that could be represented as int.</p>\n\n<p>Truncate returns either a Decimal or a double, avoiding this issue.</p>\n" }, { "answer_id": 236410, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "<p>I agree that Truncate is what you want. </p>\n\n<p>Some helpful information from <a href=\"http://msdn.microsoft.com/en-us/library/c2eabd70.aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<p>Truncate returns the number that remains after any fractional digits have been discarded.</p>\n\n<p>It rounds to the nearest integer towards zero.</p>\n\n<pre><code>double floatNumber;\n\nfloatNumber = 32.7865;\n// Displays 32 \nConsole.WriteLine(Math.Truncate(floatNumber));\n\nfloatNumber = -32.9012;\n// Displays -32 \nConsole.WriteLine(Math.Truncate(floatNumber));\n</code></pre>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
I need to compare the integer part of two doubles for inequality and I'm currently doing this: ``` int iA = (int)dA; int iB = (int)dB; if( iA != iB ) { ... } ``` but I wonder if there's a better approach than this. Thanks. If I used Math.Truncate() instead of a cast to int, would it still be accurate to compare the two resulting double values for equality? About the hungarian notation comments: I never use HN myself, not at least in the way most of people do. But this is one of these rare cases where the semantic of a variable directly relates to its type. I could have chosen another syntax like A\_As\_Integer and B\_As\_NonInteger but what would have been the difference then?
Use Math.Truncate() i.e. ``` if (Math.Truncate(x) == Math.Truncate(y)) ``` [Edit] Realized that if you are comparing integer parts of doubles, casting to int values first runs the risk of overflows should your doubles be outside the range that could be represented as int. Truncate returns either a Decimal or a double, avoiding this issue.
236,335
<p>So, simple procedure, calculate a factorial number. Code is as follows.</p> <pre><code>int calcFactorial(int num) { int total = 1; if (num == 0) { return 0; } for (num; num &gt; 0; num--) { total *= num; } return total; } </code></pre> <p>Now, this works fine and dandy (There are certainly quicker and more elegant solutions, but this works for me) for most numbers. However when inputting larger numbers such as 250 it, to put it bluntly, craps out. Now, the first couple factorial "bits" for 250 are { 250, 62250, 15126750, 15438000, 3813186000 } for reference.</p> <p>My code spits out { 250, 62250, 15126750, 15438000, <strong>-481781296</strong> } which is obviously off. My first suspicion was perhaps that I had breached the limit of a 32 bit integer, but given that 2^32 is 4294967296 I don't think so. The only thing I can think of is perhaps that it breaches a <strong>signed</strong> 32-bit limit, but shouldn't it be able to think about this sort of thing? If being signed is the problem I can solve this by making the integer unsigned but this would only be a temporary solution, as the next iteration yields 938043756000 which is far above the 4294967296 limit.</p> <p>So, is my problem the signed limit? If so, what can I do to calculate large numbers (Though I've a "LargeInteger" class I made a while ago that may be suited!) without coming across this problem again?</p>
[ { "answer_id": 236338, "author": "Stewart Johnson", "author_id": 6408, "author_profile": "https://Stackoverflow.com/users/6408", "pm_score": 5, "selected": true, "text": "<p>2^32 doesn't give you the limit for signed integers. </p>\n\n<p>The signed integer limit is actually <a href=\"http://msdn.microsoft.com/en-us/library/296az74e(VS.80).aspx\" rel=\"noreferrer\">2147483647</a> (if you're developing on Windows using the MS tools, other toolsuites/platforms would have their own limits that are probably similar).</p>\n\n<p>You'll need a C++ large number library <a href=\"http://mattmccutchen.net/bigint/\" rel=\"noreferrer\">like this one</a>.</p>\n" }, { "answer_id": 236341, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": -1, "selected": false, "text": "<p>If i remember well:</p>\n<p>unsigned short int = max 65535</p>\n<p>unsigned int = max 4294967295</p>\n<p>unsigned long = max 4294967295</p>\n<p>unsigned long long (Int64 )= max 18446744073709551615</p>\n<h3>Edited source:</h3>\n<p><a href=\"http://home.att.net/%7Ejackklein/c/inttypes.html#int\" rel=\"nofollow noreferrer\">Int/Long Max values</a></p>\n<p><a href=\"http://www.cplusplus.com/doc/tutorial/variables.html\" rel=\"nofollow noreferrer\">Modern Compiler Variable</a></p>\n" }, { "answer_id": 236342, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "<p>Yes, you hit the limit. An int in C++ is, by definition, signed. And, uh, no, C++ does not think, ever. If you tell it to do a thing, it will do it, even if it is obviously wrong.</p>\n\n<p>Consider using a large number library. There are many of them around for C++.</p>\n" }, { "answer_id": 236344, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 2, "selected": false, "text": "<p>If you don't specify signed or unsigned, the default is signed. You can modify this using a command line switch on your compiler.</p>\n\n<p>Just remember, C (or C++) is a very low-level language and does precisely <em>what you tell it to do</em>. If you tell it to store this value in a signed int, that's what it will do. <strong>You</strong> as the programmer have to figure out when that's a problem. It's not the language's job.</p>\n" }, { "answer_id": 236345, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 4, "selected": false, "text": "<p>In addition to the other comments, I'd like to point out two serious bugs in your code.</p>\n\n<ul>\n<li>You have no guard against negative numbers. </li>\n<li>The factorial of zero is one, not zero.</li>\n</ul>\n" }, { "answer_id": 236352, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": "<p>My Windows calculator (<em>Start-Run-Calc</em>) tells me that </p>\n\n<pre><code>hex (3813186000) = E34899D0\nhex (-481781296) = FFFFFFFFE34899D0\n</code></pre>\n\n<p>So yes, the cause is the signed limit. Since factorials can by definition only be positive, and can only be calculated for positive numbers, both the argument and the return value should be unsigned numbers anyway. (I know that everybody uses <code>int i = 0</code> in for loops, so do I. But that left aside, we should use always unsigned variables if the value can not be negative, it's good practice IMO).</p>\n\n<p>The general problem with factorials is, that they can easily generate <em>very</em> large numbers. You could use a float, thus sacrificing precision but avoiding the integer overflow problem.</p>\n\n<p>Oh wait, according to what I wrote above, you should make that an unsigned float ;-)</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31389/" ]
So, simple procedure, calculate a factorial number. Code is as follows. ``` int calcFactorial(int num) { int total = 1; if (num == 0) { return 0; } for (num; num > 0; num--) { total *= num; } return total; } ``` Now, this works fine and dandy (There are certainly quicker and more elegant solutions, but this works for me) for most numbers. However when inputting larger numbers such as 250 it, to put it bluntly, craps out. Now, the first couple factorial "bits" for 250 are { 250, 62250, 15126750, 15438000, 3813186000 } for reference. My code spits out { 250, 62250, 15126750, 15438000, **-481781296** } which is obviously off. My first suspicion was perhaps that I had breached the limit of a 32 bit integer, but given that 2^32 is 4294967296 I don't think so. The only thing I can think of is perhaps that it breaches a **signed** 32-bit limit, but shouldn't it be able to think about this sort of thing? If being signed is the problem I can solve this by making the integer unsigned but this would only be a temporary solution, as the next iteration yields 938043756000 which is far above the 4294967296 limit. So, is my problem the signed limit? If so, what can I do to calculate large numbers (Though I've a "LargeInteger" class I made a while ago that may be suited!) without coming across this problem again?
2^32 doesn't give you the limit for signed integers. The signed integer limit is actually [2147483647](http://msdn.microsoft.com/en-us/library/296az74e(VS.80).aspx) (if you're developing on Windows using the MS tools, other toolsuites/platforms would have their own limits that are probably similar). You'll need a C++ large number library [like this one](http://mattmccutchen.net/bigint/).
236,349
<p>What's the best way to handle a visitor constructing their own URL and replacing what we expect to be an ID with anything they like?</p> <p>For example:</p> <p><a href="https://stackoverflow.com/questions/236349">ASP.Net MVC - handling bad URL parameters</a></p> <p>But the user could just as easily replace the URL with:</p> <p><a href="https://stackoverflow.com/questions/foo">https://stackoverflow.com/questions/foo</a></p> <p>I've thought of making every Controller Function parameter a <code>String</code>, and using <code>Integer.TryParse()</code> on them - if that passes then I have an ID and can continue, otherwise I can redirect the user to an Unknown / not-found or index View.</p> <p>Stack Overflow handles it nicely, and I'd like to too - how do you do it, or what would you suggest?</p>
[ { "answer_id": 236353, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 0, "selected": false, "text": "<p>The problem with that approach is that they still might pass an integer which doesn't map to a page. Just return a 404 if they do that, just as you would with \"foo\". It's not something to worry about unless you have clear security implications.</p>\n" }, { "answer_id": 236386, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 2, "selected": false, "text": "<p>In ASP.NET MVC, you can define a filter implementing IActionFilter interface. You will be able to decorate your action with this attribute so that it will be executed on, before or after your action.</p>\n\n<p>In your case, you will define it to be executed \"before\" your action. So that, you will be able to cancel it if there is an error in the passed parameters. The key benefit here that you only write the code which checking the passed paramaters once (i.e you define it in your filter) and use it wherever you want in your controller actions.</p>\n\n<p>Read more about MVC filters here: <a href=\"http://haacked.com/archive/2008/08/14/aspnetmvc-filters.aspx\" rel=\"nofollow noreferrer\">http://haacked.com/archive/2008/08/14/aspnetmvc-filters.aspx</a></p>\n" }, { "answer_id": 236405, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 2, "selected": false, "text": "<p>You can specify constraints as regular expressions or define custom constraints. Have a look at this blog post for more information:</p>\n\n<p><a href=\"http://weblogs.asp.net/stephenwalther/archive/2008/08/06/asp-net-mvc-tip-30-create-custom-route-constraints.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/stephenwalther/archive/2008/08/06/asp-net-mvc-tip-30-create-custom-route-constraints.aspx</a></p>\n\n<p>You will still need to deal with the situation where id 43243 doesn't map to anything which could be dealt with as an IActionFilter or in your controller directly.</p>\n" }, { "answer_id": 237232, "author": "Schotime", "author_id": 29376, "author_profile": "https://Stackoverflow.com/users/29376", "pm_score": 3, "selected": false, "text": "<p>Here is some useful infromation that might help.\nIf you have a action method </p>\n\n<pre><code>public ActionResult Edit(int? id)\n{}\n</code></pre>\n\n<p>then if someone types in </p>\n\n<pre><code>/Home/Edit/23\n</code></pre>\n\n<p>the parameter id will be 23.\nhowever if someone types in </p>\n\n<pre><code>/Home/Edit/Junk\n</code></pre>\n\n<p>then id will be null which is pretty cool. I thought it would throw a cast error or something. It means that if id is not a null value then it is a valid integer and can be passed to your services etc. for db interaction.</p>\n\n<p>Hope this provides you with some info that I have found whilst testing.</p>\n" }, { "answer_id": 237390, "author": "Dan Atkinson", "author_id": 31532, "author_profile": "https://Stackoverflow.com/users/31532", "pm_score": 5, "selected": true, "text": "<p>Here's an example of a route like yours, with a constraint on the number:</p>\n\n<pre><code>routes.MapRoute(\n \"Question\",\n \"questions/{questionID}\",\n new { controller = \"StackOverflow\", action = \"Question\" },\n new { questionID = @\"\\d+\" } //Regex constraint specifying that it must be a number.\n);\n</code></pre>\n\n<p>Here we set the questionID to have at least one number. This will also block out any urls containing anything but an integer, and also prevents the need for a nullable int.</p>\n\n<p><em>Note:</em> This does not take into account numbers that larger than the range of Int32 (-2147483647 - +2147483647). I leave this as an exercise to the user to resolve. :)</p>\n\n<p>If the user enters the url \"questions/foo\", they will not hit the Question action, and fall through it, because it fails the parameter constraint. You can handle it further down in a catchall/default route if you want:</p>\n\n<pre><code>routes.MapRoute(\n \"Catchall\",\n \"{*catchall}\", // This is a wildcard routes\n new { controller = \"Home\", action = \"Lost\" }\n);\n</code></pre>\n\n<p>This will send the user to the Lost action in the Home controller. More information on the wildcard can be found <a href=\"http://richarddingwall.name/2008/08/09/three-common-aspnet-mvc-url-routing-issues/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>NB: The Catchall should reside as the LAST route.</strong> Placing it further up the chain will mean that this will handle all others below it, given the lazy nature of routes in ASP.NET MVC.</p>\n" } ]
2008/10/25
[ "https://Stackoverflow.com/questions/236349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
What's the best way to handle a visitor constructing their own URL and replacing what we expect to be an ID with anything they like? For example: [ASP.Net MVC - handling bad URL parameters](https://stackoverflow.com/questions/236349) But the user could just as easily replace the URL with: <https://stackoverflow.com/questions/foo> I've thought of making every Controller Function parameter a `String`, and using `Integer.TryParse()` on them - if that passes then I have an ID and can continue, otherwise I can redirect the user to an Unknown / not-found or index View. Stack Overflow handles it nicely, and I'd like to too - how do you do it, or what would you suggest?
Here's an example of a route like yours, with a constraint on the number: ``` routes.MapRoute( "Question", "questions/{questionID}", new { controller = "StackOverflow", action = "Question" }, new { questionID = @"\d+" } //Regex constraint specifying that it must be a number. ); ``` Here we set the questionID to have at least one number. This will also block out any urls containing anything but an integer, and also prevents the need for a nullable int. *Note:* This does not take into account numbers that larger than the range of Int32 (-2147483647 - +2147483647). I leave this as an exercise to the user to resolve. :) If the user enters the url "questions/foo", they will not hit the Question action, and fall through it, because it fails the parameter constraint. You can handle it further down in a catchall/default route if you want: ``` routes.MapRoute( "Catchall", "{*catchall}", // This is a wildcard routes new { controller = "Home", action = "Lost" } ); ``` This will send the user to the Lost action in the Home controller. More information on the wildcard can be found [here](http://richarddingwall.name/2008/08/09/three-common-aspnet-mvc-url-routing-issues/). **NB: The Catchall should reside as the LAST route.** Placing it further up the chain will mean that this will handle all others below it, given the lazy nature of routes in ASP.NET MVC.